在windows vs linux上使用"r +"

Mik*_*ike 5 c linux windows file-io fopen

我正在玩弄一些打开,阅读和修改文本文件的代码.一个快速(简化)的例子是:

#include <stdio.h>
int main()
{
    FILE * fp = fopen("test.txt", "r+");
    char line[100] = {'\0'};
    int count = 0;
    int ret_code = 0;
    while(!feof(fp)){
        fgets(line, 100, fp);
        // do some processing on line...
        count++;
        if(count == 4) {
          ret_code = fprintf(fp, "replaced this line\n");
          printf("ret code was %d\n", ret_code);
          perror("Error was: ");
        }
    }
    fclose(fp);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在在Linux上,使用gcc(4.6.2)编译此代码,并修改文件的第5行.在使用Visual C++ 2010编译的Windows7上运行的相同代码运行并声称已成功(报告返回代码为19个字符并perror说"无错误")但无法替换该行.

在Linux上,我的文件具有完全权限:

-rw-rw-rw- 1 mike users 191 Feb 14 10:11 test.txt
Run Code Online (Sandbox Code Playgroud)

据我所知,它在Windows上也是如此:

test.txt(右键单击) - >属性 - >安全性
"允许"被检查用户,系统和管理员的读写.

我在Windows上使用MinGW的gcc得到了相同的结果,所以我知道它不是Visual C++的"功能".

我失去了一些东西明显,或者是我没有得到任何错误的情况,也没有使用的输出只是一个无证"功能" r+fopen()在Windows?


编辑:
即使在微软的网站上,他们说"r +"应该打开阅读写作.他们还做了这个说明:

当指定"r +","w +"或"a +"访问类型时,允许读取和写入(该文件被称为"更新"打开).但是,当您在读取和写入之间切换时,必须进行干预fflush,fsetpos,fseek或倒带操作.如果需要,可以为fsetpos或fseek操作指定当前位置.

所以我尝试过:

        ...
        if(count == 4) {
          fflush(fp);
          ret_code = fprintf(fp, "replaced this line\n");
          fflush(fp);
          printf("ret code was %d\n", ret_code);
          ...
Run Code Online (Sandbox Code Playgroud)

无济于事.

Has*_*kun 3

根据Linux 手册页fopen()

读取和写入可以以任何顺序在读/写流上混合。请注意,ANSI C 要求文件定位函数介入输出和输入之间,除非输入操作遇到文件结尾。(如果不满足此条件,则允许读取返回最近写入以外的结果。)因此,放置 fseek(3) 或 fgetpos(3 是一种很好的做法(在 Linux 下有时确实是必要的) ) 此类流上的写入和读取操作之间的操作。此操作可能是一个明显的无操作(如 fseek(..., 0L, SEEK_CUR) 中调用的同步副作用。

因此,在从文件读取和写入之间切换时,您应该始终调用fseek()(例如, )。fseek(..., 0, SEEK_CUR)