[英]How to Write in a loop into a binary file in C sockets
I have the following snippet where I read sent bytes using read()
and store the data in a buffer which works well.我有以下代码段,我使用read()
读取发送的字节并将数据存储在运行良好的缓冲区中。 But how do i make it so that I can continue to write in binary file after every read.但是我如何做到这一点,以便我可以在每次读取后继续写入二进制文件。 My assumption is that it might have something to do with not resetting the buffer.我的假设是它可能与不重置缓冲区有关。 Thanks for the help!谢谢您的帮助!
fp = fopen (filename, "wb"); //create a file
while (size > 0){
n = read(socket,buffer,size*sizeof(char));
if (n <=0)
return -1;
p += n;
size -= n;
fwrite(buffer,sizeof(char),size*sizeof(char),fp); //write the content to the file
}
You should use n
in the call to fwrite()
, not size
.您应该在调用fwrite()
使用n
,而不是size
。 n
is the amount you just read from the socket, size
is how many more bytes you're still waiting for. n
是您刚刚从套接字读取的数量, size
是您仍在等待的字节数。
fwrite(buffer,sizeof(char),n,fp);
You also shouldn't multiply by sizeof
there.你也不应该在那里乘以sizeof
。 The second argument is the size of each element, the third argument is the number of elements;第二个参数是每个元素的大小,第三个参数是元素的数量; fwrite()
performs the multiplication internally. fwrite()
在内部执行乘法。 It happens to work in your case because sizeof(char)
is always 1
, so the multiplication didn't change anything.它恰好适用于您的情况,因为sizeof(char)
始终为1
,因此乘法没有改变任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.