Search code examples
cfilecopygarbage

garbage when copying two files in C?


I have this copying code from infile to outfile, the problem is that there is a lot of garbage added at the end of the outfile

ssize_t nread;
int bufsize=512;
char buffer[bufsize];

while ( (nread=read(infile, buffer, bufsize)>0))
{
    if( write(outfile, buffer, bufsize)<nread ) 
    {
        close(outfile); close(infile); printf("error in write loop !\n\n");
        return (-4);
    }
}
if( nread == -1) {
  printf ("error on last read\n"); return (-5);
}//error on last read /

what should i do to fix this ?


Solution

  • while ( (nread=read(infile, buffer, bufsize)>0))
    

    should be:

    while ( (nread=read(infile, buffer, bufsize)) >0 )
    

    as > has higher precedence when compared to =.

    Also

    write(outfile, buffer, bufsize)
    

    you are always writing bufsize number of bytes. But there need not be those many bytes read in the read operation. This could happen in the last iteration of the copying. To fix this you should be writing nread number of bytes.