在 C 中写入文件时添加到缓冲区的额外字符

发布于 2024-09-28 22:39:52 字数 958 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如歌彻婉言 2024-10-05 22:39:52

尝试:write(fdWrite,readBuffer,bytesRead)。

Try: write(fdWrite,readBuffer, bytesRead).

听风念你 2024-10-05 22:39:52

尝试在写入函数调用中将 BUFFER_SIZE 更改为 bytesRead。

Try changing BUFFER_SIZE to bytesRead in your write function call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文