Search code examples
clinuxappendmode

Appending to existing file from resource file in Linux C Program


i've trying to perform appending to an existing file from resource file using the C programming in Linux. However, my code doesn't work for that, can any1 do tell me what's wrong with the code and also how O_APPEND is working? thanks :)

char ifile[150];
char tfile[150];
char cc;

system("clear");
printf("Please enter your resource file name : ");
gets(ifile);
printf("Please enter your destination file name : ");
gets(tfile);

int in, out;

in = open(ifile, O_RDONLY);
int size = lseek(in,0L,SEEK_END);
out = open(tfile, O_WRONLY |O_APPEND);
char block[size];
int pdf;
while(read(in,&block,size) == size)
    pdf = write(out,&block,size);
close(in);close(out);
if(pdf != -1)
    printf("Successfully copy!");
else
    perror("Failed to append! Error : ");
printf("Press enter to exit...");
do
{
    cc = getchar();
} while(cc != '\n');

Solution

  • The problem here is that you deplace the reading cursor at the end of the file in order to know its size, but you don't rewind to the start of the file to be able to read. So read() reads EOF, and returns 0.

    int size = lseek(in, 0L, SEEK_END);
    out = open(tfile, O_WRONLY | O_APPEND);
    

    should be

    int size = lseek(in, 0L, SEEK_END);
    lseek(in, 0L, SEEK_SET);
    out = open(tfile, O_WRONLY | O_APPEND);
    

    In addition, when you read and write, you should use block and not &block, since block is already a pointer (or an address).

    Oh, and also... When you open the file out for writing... It will fail if the file does not exist already.

    Here how to create it with rights set to 644:

    out = open(tfile, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    

    (This won't have any effect if the file already exists)