tags:

views:

44

answers:

2

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);
        }
    }
}
+5  A: 

Try: write(fdWrite,readBuffer, bytesRead).

Graham Perks
Worked like a charm. Thanks!
XBigTK13X
+1  A: 

Try changing BUFFER_SIZE to bytesRead in your write function call.

Blastfurnace