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