在 C 中写入文件时添加到缓冲区的额外字符
m当尝试用 C 语言创建文件的备份副本时,我发现下面的算法有时会生成额外的字符。我还尝试在 while 循环中声明 readBuffer,但这并没有解决问题。这是这个问题的一个例子。
原始文件内容
Hello there.
My name is Alice.
Done.
备份文件内容
Hello there.
My name is Alice.
Done.ice
可以看到,最后一行还剩下之前的字符缓冲的消息。这只发生在文件的最后几行,因为任何其他时间缓冲区都会填充新内容。如何纠正我的以下逻辑以解决此问题?
while(0 != bytesRead)
{
bytesRead = read(fdRead,readBuffer, BUFFER_SIZE);
if(0>bytesRead)
{
fprintf(stderr,"read() on '%s' for backup failed.\nError Info: %s\n",fileName,strerror(errno));
exit(EXIT_FAILURE);
}
else if(0<bytesRead)
{
if(-1 == write(fdWrite,readBuffer,BUFFER_SIZE))
{
fprintf(stderr,"An error occurred while writing backup for '%s'.\nError Info: %s\n",fileName,strerror(errno));
exit(EXIT_FAILURE);
}
}
}
mWhile attempting to make a backup copy of a file in C, I find that extra characters are sometimes generated by the algorithm below. I've also tried declaring the readBuffer within the while loop, but that did not solve the problem. Here's an example of the issue.
Original File Contents
Hello there.
My name is Alice.
Done.
Backup File Contents
Hello there.
My name is Alice.
Done.ice
As you can see, there are characters left in the last line from the previously buffered message. This only happens on the last lines of the file since any other time the buffer is filled with new contents. How can my logic below be corrected to resole this issue?
while(0 != bytesRead)
{
bytesRead = read(fdRead,readBuffer, BUFFER_SIZE);
if(0>bytesRead)
{
fprintf(stderr,"read() on '%s' for backup failed.\nError Info: %s\n",fileName,strerror(errno));
exit(EXIT_FAILURE);
}
else if(0<bytesRead)
{
if(-1 == write(fdWrite,readBuffer,BUFFER_SIZE))
{
fprintf(stderr,"An error occurred while writing backup for '%s'.\nError Info: %s\n",fileName,strerror(errno));
exit(EXIT_FAILURE);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:write(fdWrite,readBuffer,bytesRead)。
Try: write(fdWrite,readBuffer, bytesRead).
尝试在写入函数调用中将 BUFFER_SIZE 更改为 bytesRead。
Try changing BUFFER_SIZE to bytesRead in your write function call.