user193239
user193239

Reputation: 109

How to properly append lines to already existing file

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.

Upvotes: 4

Views: 15881

Answers (2)

Gowtham Ganesh
Gowtham Ganesh

Reputation: 340

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");

Upvotes: 7

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

If I understood your problem correctly, you can have two approaches,

Case 1 (Opening / closing multiple times, write one value at a time)

You need to open the file in append mode to preserve the previous content. Check the man page of fopen() for a or append mode.

Case 2 (Opening / Closing once, writing all the values at a stretch)

you need to put the fprintf() statement in some kind of loop to get all the elements printed, i.e., the index (item) value goes from 0 to some max value.

Upvotes: 4

Related Questions