【问题标题】:Is there a way to change a single line of a file with fseek()?有没有办法用 fseek() 改变文件的一行?
【发布时间】:2021-01-28 03:14:11
【问题描述】:

我正在用 C 训练文件处理,我尝试使用 fseek() 更改文件的单行或位置,同时使用 fread()fwrite() 进行写入和读取,而不更改变量并写入整个文件再次,但显然附加模式和写入模式都不允许你这样做,因为我在下面的示例中尝试过:

void main()
{
    FILE *file;
    char answer;
    char text[7]  = "text 1\n";
    char text2[7] = "text 2\n";

    file = fopen("fseek.txt", "w"); //creating 'source' file
    fwrite(text, sizeof(char), sizeof(text), file);
    fwrite(text, sizeof(char), sizeof(text), file);
    fwrite(text, sizeof(char), sizeof(text), file);
    fclose(file);

    scanf("%c", &answer);

    switch(answer)
    {
    case 'a':
        //attempt to change single line with append mode
        file = fopen("fseek.txt", "a");
        fseek(file, 7, SEEK_SET); //7 characters offset is the second line of the file
        fwrite(text2, sizeof(char), sizeof(text), file);
        fclose(file);
        break;
    case 'w':
        //attempt to change single line with write mode
        file = fopen("fseek.txt", "w");
        fseek(file, 7, SEEK_SET); //7 characters offset is the second line of the file
        fwrite(text2, sizeof(char), sizeof(text), file);
        fclose(file);
        break;
    }
}

但是在附加模式下,即使事先使用fseek() 函数,它也只会将变量写入文件末尾,而写入模式只会擦除文件并重写它。那么如何使用fseek() 或类似名称更改文件的一行?

【问题讨论】:

  • 只有在不改变行长的情况下才能这样做。无法移动文件的其余部分以适应更改行长。
  • 为了扩展 Barmar 所说的内容,如果你写出 完全 相同数量的字节你没问题,否则你需要重写文件过去那一点。
  • 没有,没有。阅读Modern C

标签: c file-handling fwrite fread fseek


【解决方案1】:

您需要以r+ 模式打开。 w 模式会先清空文件,r 不会,因为它是用来读取文件的。 + 修饰符也允许您写入文件。

更改行时,新文本需要与原始行的长度相同。如果它更短,则原始行的其余部分将留在文​​件中。如果它更长,您将覆盖下一行的开头。

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2011-01-06
    • 2014-06-02
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多