gpt4 book ai didi

c - 在 C 中复制两个文件时出现垃圾?

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:43 26 4
gpt4 key购买 nike

我有这段从输入文件到输出文件的复制代码,问题是在输出文件的末尾添加了很多垃圾

ssize_t nread;
int bufsize=512;
char buffer[bufsize];

while ( (nread=read(infile, buffer, bufsize)>0))
{
if( write(outfile, buffer, bufsize)<nread )
{
close(outfile); close(infile); printf("error in write loop !\n\n");
return (-4);
}
}
if( nread == -1) {
printf ("error on last read\n"); return (-5);
}//error on last read /

我应该怎么做才能解决这个问题?

最佳答案

while ( (nread=read(infile, buffer, bufsize)>0))

应该是:

while ( (nread=read(infile, buffer, bufsize)) >0 )

因为 >= 相比具有更高的优先级。

还有

write(outfile, buffer, bufsize)

您总是写入 bufsize 个字节。但是在读取操作中不需要读取那么多字节。这可能发生在复制的最后一次迭代中。要解决此问题,您应该编写 nread 字节数。

关于c - 在 C 中复制两个文件时出现垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com