如何正确地将行附加到现有文件

时间:2021-12-30 03:48:08

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.

我查看了互联网,试图找到一个逐行写入c文件的解决方案。我找到了将fopen()的模式改为w +,wt,wb的解决方案,但它对我不起作用。我甚至读到把\ r而不是\ n放在行的末尾但是当我尝试写入文件时,唯一写入的是最后一行。

    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.

非常感谢您的时间和帮助。

2 个解决方案

#1


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.

这是因为每次在“w”模式下执行fprintf时,日志都会被新内容覆盖,因为文件未在“追加”模式下打开,而是处于“写入”模式。

Better thing would be to use:

更好的是使用:

fopen("filename", "a");

#2


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

如果我理解你的问题,你可以有两种方法,

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

案例1(多次打开/关闭,一次写入一个值)

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.

您需要以附加模式打开文件以保留以前的内容。检查fopen()的手册页以获取或附加模式。

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

案例2(打开/关闭一次,一次性写入所有值)

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.

你需要将fprintf()语句放在某种循环中以获得所有打印的元素,即索引(item)值从0变为某个最大值。

#1


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.

这是因为每次在“w”模式下执行fprintf时,日志都会被新内容覆盖,因为文件未在“追加”模式下打开,而是处于“写入”模式。

Better thing would be to use:

更好的是使用:

fopen("filename", "a");

#2


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

如果我理解你的问题,你可以有两种方法,

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

案例1(多次打开/关闭,一次写入一个值)

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.

您需要以附加模式打开文件以保留以前的内容。检查fopen()的手册页以获取或附加模式。

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

案例2(打开/关闭一次,一次性写入所有值)

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.

你需要将fprintf()语句放在某种循环中以获得所有打印的元素,即索引(item)值从0变为某个最大值。