I'm writing my own server in ANSI C (on Linux) and I've got one problem with sending images to a web browser. I'm using the function "send()" to send it and it required a char *. So I was reading a file char by char (using fgetc), I used fread and fgets, but everything had a problem with casting the content(int in most cases) to a bufor - some bytes still were missing (e.g 2008 was send instead of 2020). I think there is some problem with conversion, but I used sprintf and wchar_t and it is still not working.

I've got a function:

void send_www(char *buff, int cd){      
if(send (cd, buff, strlen(buff), 0) < 0) {
        perror ("send()");
        exit (1);

which I use here:

//  while (fread(znak, sizeof(char), i,  handler) != 0) {
    for (j = 0; j < i; j++) {
    a = fgetc(handler);
    sprintf(znak, "%ls", a);
    send_www(znak, cd);
    }

where i is the length of the image file, znak is the char* (in this version wchar_t*). You can also see my earlier try of using fread.

Accepted Answer

You are using strlen(). strlen() stops and returns the size after it reaches a \0 byte. Images and binary data are allowed to have a byte valued zero anywhere, so strlen() is useless in those cases.

You need to modify your function to:

send_www(unsigned char *buff, size_t buf_len int cd);

And pass the image size to it, so you can safely send() it with the appropriate size.

In your case, it seems you are sure it is a wchar_t string, use the appropriate function, wcslen(), not strlen() :)

Written by hexa
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki