Question

I'm trying to write a wchar array to a file in C, however there is some sort of corruption and unrelevant data like variables and paths like this

c.:.\.p.r.o.g.r.a.m. .f.i.l.e.s.\.m.i.c.r.o.s.o.f.t. .v.i.s.u.a.l. .s.t.u.d.i.o. 1.0...0.\.v.c.\.i.n.c.l.u.d.e.\.x.s.t.r.i.n.g..l.i.s.t...i.n.s.e.r.t 

are written on to the file along with the correct data (example) I have confirmed that the buffer is null-terminated and contains proper data.

Heres my code:

        myfile = fopen("logs.txt","ab+");
        fseek(myfile,0,SEEK_END); 
        long int size = ftell(myfile);
        fseek(myfile,0,SEEK_SET);
        if (size == 0)
        {
            wchar_t bom_mark = 0xFFFE; 
            size_t written = fwrite(&bom_mark,sizeof(wchar_t),1,myfile); 
        }
// in another func
            while (true)
            {
            [..]
                unsigned char Temp[512];
                iBytesRcvd = recv(sclient_socket,(char*)&Temp,iSize,NULL);
                if(iBytesRcvd > 0 )
                {
                    WCHAR* unicode_recv = (WCHAR*)&Temp;
                    fwrite(unicode_recv,sizeof(WCHAR),wcslen(unicode_recv),myfile);
                    fflush(myfile);
                }
            [..]
            }

What could be causing this?

Was it helpful?

Solution

recv() will not null-terminate &Temp, so wcslen() runs over the bytes actually written by recv(). You will get correct results if you just use iBytesReceived as byte count for fwrite() instead of using wcslen() and hoping the data received is correctly null-terminated (wide-NULL-terminated, that is):

fwrite(unicode_recv, 1, iBytesReceived, myfile);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top