通过套接字发送二进制文件

时间:2011-06-30 13:14:17

标签: c++ sockets binaryfiles

我正在尝试通过C中的套接字将二进制文件发送到嵌入式平台,但是当我在发送它之后运行它只是给了我段错误(通过ftp发送工作正常,但它非常慢)。
在同一系统中发送二进制文件工作正常(嵌入式是little-endian所以我不认为它的endian问题)。
可能是什么问题?该计划是mft.cpp

1 个答案:

答案 0 :(得分:1)

您假设每个read都返回您想要读取的字节数。那是不对的。您应该始终检查read返回值,看看是否有你想要的字节数。

这也意味着您可以将发送循环重写为:

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 ;
}
相关问题