-2

im trying to write a program that gets two text files and copy`s the text from one file to the other. the function seems to be working but it changes the file that I write in not in to a text file.

please help!!!!

int main(int argc, char *argv[]) {
    printf("Hello World!\n"); 
    char* file1 = argv[1];
    char* file2 = argv[2];
    char buffer1[SIZE+1];
    //char buffer2[SIZE+1];
    int fd1, fd2;
    int run = 1;
    int run2;



    fd1 = open(file1, O_RDONLY);

    if(fd1 < 0){
        perror("after open ");   // checks if the file was open ok 
        exit(-1);   
    }

    fd2 = open(file2, O_RDWR );

        if(fd2 < 0){
        perror("after open ");   // checks if the file was open ok  
        exit(-1);
        }

    while(run != 0){
        run = read(fd1, buffer1, SIZE);     
        run2 = write(fd2, buffer1, SIZE);
        printf("run 2: %d", run2);
    }



    close(fd1);
    close(fd2);
    return 1;

}
Gal Sosin
  • 714
  • 7
  • 27
  • Did you try perror after the write? What did it say? – nneonneo May 07 '15 at 21:01
  • [Here is a question very similar to yours.](http://stackoverflow.com/questions/8333869/copying-data-from-one-text-file-to-another-in-c) You may want to reconstruct your code. – abuv May 07 '15 at 21:02
  • Which language, C or C++? There is a fast and simple method in C++ using the `rdbuf` structure, which isn't present in C. – Thomas Matthews May 07 '15 at 23:02

2 Answers2

2

Probably because

 fd2 = open(file2, O_RDONLY);

Read only file -> fd2

warzon
  • 178
  • 6
0

Your program doesn't handle the case where the quantity of data read is less than the buffer size:

while(run != 0){
    run = read(fd1, buffer1, SIZE);     
    run2 = write(fd2, buffer1, SIZE);
    printf("run 2: %d", run2);
}

If the amount read is less than SIZE, you will be writing garbage to the second file.

Why are you using low level file I/O?

This can be done using C language functions, at a high level:

FILE * input;
FILE * output;
input = fopen("input_file.bin", "rb");
output = fopen("output_file.bin", "wb");
while (!feof(input))
{
  int quantity = fread(&buffer1[0], SIZE, 1, input);
  int bytes_written = fwrite(&buffer1[0], quantity, 1, output);
}

In the above example, the number of bytes written is the number of bytes read. If the quantity of bytes read is less than SIZE, it will write the quantiy of bytes read to the output file, no more, no less.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154