简体   繁体   English

将每行末尾的元素追加到文件中

[英]Append elements at the end of each line into a file

I want to append elements into a file line by line, not the end of the file. 我想将元素逐行附加到文件中,而不是文件的末尾。 I wrote this code, but the result was that I could only append elements at the end of the file. 我写了这段代码,但结果是我只能在文件末尾附加元素。

#include <stdio.h>
#include <stdio.h>

int main(void)
{
    static const char filename[] = "m.txt";
    FILE *file = fopen(filename, "r+a");
    char *a = "ok";

    if (file != NULL)
    {
        char line[128];         /* or other suitable maximum line size */

        while (fgets(line, sizeof line, file) != NULL)  /* read a line */
        {
            fputs(a, file);     /* write the line */
        }
        fclose(file);
    }
    else
    {
        perror(filename);       /* why didn't the file open? */
    }
    return 0;
}

Some answers have mentioned buffer. 一些答案提到了缓冲区。
I am a little confused with the buffer here. 我对这里的缓冲区有些困惑。 Does it mean I have to read more than one line into memory and then modify them? 这是否意味着我必须将多行读入内存,然后对其进行修改? And is buffer the same as BufferedReader class in Java? 缓冲区与Java中的BufferedReader类相同吗​​?

Files are not stored as an array of lines you can append to and manipulate at will, they are one big chunk of data you interpret. 文件不是存储为可以附加和随意操作的行数组,它们是您要解释的一大块数据。 So if you were to do such a thing, you'd overwrite the rest of the file that follows your current line. 因此,如果要执行此操作,则将覆盖当前行之后的文件其余部分。

What you have to do is re-write at least the entire rest of the file whenever you do this. 每当您执行此操作时,您至少要重写文件的其余全部内容。 You can do that easily using a buffer. 您可以使用缓冲区轻松地做到这一点。

Lines in files are just formatting and logical points marked by the newline character. 文件中的行仅是格式,逻辑点由换行符标记。

You need to read each line one at a time, modify it as you see fit, and then rewrite the whole line to a new file . 您需要一次阅读每一行,根据需要对其进行修改,然后将整行重写为一个新文件 Then when you have read the whole file you rename the new file as the old file. 然后,当您阅读了整个文件后,将新文件重命名为旧文件。

Or you read the whole file into memory, for example into an array, one line per element of the array, modify the lines, and overwrite the contents of the file. 或者,您将整个文件读入内存,例如读入一个数组,该数组的每个元素一行,修改行,并覆盖文件的内容。

The problem with modifying a variable-length text file is that you nee4d to shift all data after the insertion point, which is not easy to do in a file. 修改可变长度文本文件的问题是您需要将所有数据移动到插入点之后,这在文件中不容易做到。 That's why it's easier to read the whole file into memory and do the modifications there, or use a temporary file that you then rename. 这就是为什么将整个文件读入内存并在其中进行修改,或者使用您随后重命名的临时文件都更容易的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM