Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 236
user193239 Avatar asked Oct 27 '25 06:10

user193239


1 Answers

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");
like image 123
Gowtham Ganesh Avatar answered Oct 28 '25 21:10

Gowtham Ganesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!