How to properly append lines to already existing file

user193239 picture user193239 · May 13, 2015 · Viewed 10.8k times · Source

I looked over the internet trying to find a solution for writing line by line into a file in c. I found solutions like changing the mode of fopen() to w+, wt, wb but it did not work for me. I even read to put \r instead of \n in the end of the line but still when I try to write to the file the only thing that is written there is the last line.

    FILE *log = NULL;
    log = fopen(fileName, "w");
    if (log == NULL)
    {
        printf("Error! can't open log file.");
        return -1;
    }

    fprintf(log, "you bought %s\n", pro[item].name);
    fclose(log);

Many thanks for your time and help.

Answer

Gowtham Ganesh picture Gowtham Ganesh · May 13, 2015

It is because everytime you execute fprintf in "w" mode, the log gets overwritten with the new contents as the file was not opened in the 'append' mode but in 'write' mode.

Better thing would be to use:

fopen("filename", "a");