有没有办法用 fseek() 更改文件的一行?

Vin*_*doy 1 c fseek fwrite file-handling fread

我正在用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Bar*_*mar 5

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

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