0

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

0

1 Answer 1

1

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 ;
}
Sign up to request clarification or add additional context in comments.

6 Comments

I don't need to allocate fixed size buffer
Correct. I haven't coded C++ for a couple of years. The rest still apply
And if the socket fills up, write will write a partial buffer and return the number of bytes written.
This still doesn't work... @mark4o: how do I know if the socket fills up?
You have to check the return value of write(). If it is less than bytesRead then it did not write all of the data.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.