开发者

Extra character added to buffer when writing to a file in C

开发者 https://www.devze.com 2023-01-21 07:28 出处:网络
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, bu

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));
   开发者_Python百科       exit(EXIT_FAILURE);
        }
    }
}


Try: write(fdWrite,readBuffer, bytesRead).


Try changing BUFFER_SIZE to bytesRead in your write function call.

0

精彩评论

暂无评论...
验证码 换一张
取 消