why this c program for copying a file is not working correctly?

Viewed 67
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    int fd1 = open(argv[1], O_RDONLY); 
    int fd2 = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0700);

    if (fd1 == -1 || fd2 == -1) {
        perror("cannot open file");
        exit(-1);
    }
    
    char buffer[100];
    int n;
    while (n = read(fd1, buffer, 100) > 0) { // not working
        write(fd2, buffer, n);
    }
    
    close(fd1);
    close(fd2); 
    return 0;   
}

I am trying to write a C program that copies the content of one file to another. I think there is a problem with the reading in the while loop but I am not sure.

2 Answers
while( n = read( fd1, buffer, 100) > 0)

That isn't correct as it assigns the result of read( fd1, buffer, 100) > 0 into n. This happens because > has higher precedence than =.

To correct this uses parentheses:

while((n = read( fd1, buffer, 100)) > 0)

Never use assignment inside conditions. It's a very easy way to get various bugs related to operator precedence, side-effects, mistyped == and so on.

In your case the bug is that > has higher precedence than =.

In this case the code could be rewritten as:

int n;
while(1)
{
  n = read(fd1, buffer, 100);
  if(n==0)
    break;

  if(write(fd2, buffer, n) != n)
  { 
    /* handle errors */ 
  }
}
Related