XBigTK13X
XBigTK13X

Reputation: 2755

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

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);
        }
    }
}

Upvotes: 0

Views: 233

Answers (2)

Blastfurnace
Blastfurnace

Reputation: 18651

Try changing BUFFER_SIZE to bytesRead in your write function call.

Upvotes: 1

Graham Perks
Graham Perks

Reputation: 23390

Try: write(fdWrite,readBuffer, bytesRead).

Upvotes: 6

Related Questions