L4nce0
L4nce0

Reputation: 67

Sending Binary files over a socket. Text files work, nothing else does?

I can send very large text files no problem. I try to send a jpg, etc and it wont work. The file is the correct size. I don't know what I'm missing.. I check my read and write functions by writing the data before sending to a temp.foo file. I check it, and it handles anything.

I send it like this

for(vector< .... >::iterator it = v.begin(); it!=v.end(); ++it ){
    pair<...> p=*it;
    send(s,p.first,p.second,0);
}

Then the other program reads it

    for(i = 0; i < size; i+=max){
    b= 0;
    while (b== 0) {
        if ((b = recv(s, buf, max, 0)) == -1) {
            perror("recv");
            exit(1);
        }
}
    stringstream ss;
    ss << buf;
    char * out = (char*)malloc(b); 
    memcpy(out,buff,numbytes);// Perhaps my error is here?
}
// write function call here

Upvotes: 0

Views: 1214

Answers (1)

John Kugelman
John Kugelman

Reputation: 361645

Some general points about handling binary data:

  1. Make sure you open the input and output files in binary mode, such as with the ios::binary flag or the "rb" or "wb" format. The default is text mode, which will mangle end-of-line characters in a binary file.

  2. Binary files can have NUL bytes (\0), which means you can't use string-handling functions that work on NUL-terminated strings. C strings are not NUL safe. For instance, this code won't fill ss properly since it interprets buf as a NUL-terminated string:

    stringstream ss;
    ss << buf;
    

Also, on the line you point out, is buff with two fs a typo? On the other lines you reference buf with one f.

memcpy(out,buff,numbytes);// Perhaps my error is here?

Upvotes: 4

Related Questions