I'm trying to send a binary file through socket in C to an embedded platform, but when I run it after its sent it just gives me segfault (sending through ftp works fine, but its very slow).
Sending the binary file in same system works ok (the embedded is little-endian so I don't think its endian problem).
What can be the problem? the program is mft.cpp
Add a comment
|
1 Answer
You are assuming that every read returns the number of bytes that you want to read. That is incorrect. You should always check the read return value to see if you got as many bytes as you wanted.
This also means that you can rewrite your send loop as:
int bytesLeft = file_length;
char buf[1024]; //no need to reallocate it in the loop
while(bytesLeft > 0)
{
int to_read = 1024;
if(bytesLeft < to_read)
to_read = bytesLeft
int bytesRead = read(new_sock_id, buf, to_read);
if(error("reading file", false)) continue;
write(file, buf, bytesRead);
if(error("writing file", false)) continue;
bytesLeft -= bytesRead ;
}
6 Comments
Daniel
I don't need to allocate fixed size buffer
jgauffin
Correct. I haven't coded C++ for a couple of years. The rest still apply
mark4o
And if the socket fills up, write will write a partial buffer and return the number of bytes written.
Daniel
This still doesn't work... @mark4o: how do I know if the socket fills up?
mark4o
You have to check the return value of
write(). If it is less than bytesRead then it did not write all of the data. |