Skip to content
Advertisement

C Program that makes a copy of a file using standard I/O and system calls

I am trying to write a C program which uses standard I/O and System calls to perform copying of contents of one file to another file.

So far, I have done this :

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

int main(int argc, char *argv[])
{
    int fd1, fd2;
    char buffer[1024];
    long int n1;

    if(((fd1 = open(argv[1], O_RDONLY)) == -1) || ((fd2=open(argv[2],O_CREAT|O_WRONLY|O_TRUNC, 0700)) == -1)){
        perror("file problem");
        exit(1);
    }

    while((n1=read(fd1, buffer, 1024) > 0)){
        if(write(fd2, buffer, n1) != n1){
            perror("writing problem ");
            exit(3);
        }
    }
    close(fd1);
    close(fd2);
}

When I run the program like this :

cc copyContents.c 
./a.out one.txt two.txt

Assuming that one.txt is well defined, what I want is to create a new file called two.txt and copy over all the contents of one.txt

When I look into the contents of two.txt after running the program, it has literally nothing in it. Just a blank file.

Where am I going wrong?

Advertisement

Answer

You wrote

 while((n1=read(fd1, buffer, 1024) > 0)){

instead of

 while ( (n1 = read(fd1, buffer, 1024)) > 0)

In your code the code int the while condition boils down to:

n1 = (read(fd1, buffer, 1024) > 0)

So the read is done correctly, it’s return value is compared to 0, the result of the comparision (0 or 1) is assigned to n1.

This shows once more how important it is to format your code in a way that makes it readable.

You could have debugged this easily yourself with a debugger or by inserting one or two printfs in your code.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement