C读取后无法写入文件

C cannot write to file after reading

我在程序中有一个函数必须从文件中删除给定的字符串。为此,将整个文件重写为一个临时文件,然后覆盖原始文件。 使用删除的字符串保存临时文件有效,但覆盖原始文件无效。

这是怎么回事?

#define MAXCHAR 10000
void delPath(char stringToDelete[], char bashrcDir[]) {
    FILE *bashrc = fopen(bashrcDir, "r+");
    char str[MAXCHAR];

    if (bashrc != NULL) {
        FILE *tempfile = fopen("./tempFile.txt", "w+");
        // Create tempFile and copy content without given string
        while (fgets(str, MAXCHAR, bashrc) != NULL) {
            if (!strstr(str, stringToDelete)) {
                fprintf(tempfile, "%s", str);
            }
        }

        // Read tempFile and overwrite original file - this doesn't work
        while (fgets(str, MAXCHAR, tempfile) != NULL) {
            fprintf(bashrc, "%s", str);
        }

        fclose(tempfile);
    }

    fclose(bashrc);
}

r+ 允许您读取文件并覆盖它。我错了?

参考@KamilCuk 的回答,解决方法如下:

#define MAXCHAR 10000
void delPath(char stringToDelete[], char bashrcDir[]) {
    FILE *bashrc = fopen(bashrcDir, "r");
    char str[MAXCHAR];

    if (bashrc != NULL) {
        FILE *tempfile = fopen("./tempFile.txt", "w");

        while (fgets(str, MAXCHAR, bashrc) != NULL) {
            if (!strstr(str, stringToDelete)) {
                fprintf(tempfile, "%s", str);
            }
        }
        fclose(bashrc);
        fclose(tempfile);

        FILE *newTempfile = fopen("./tempFile.txt", "r");
        FILE *newBashrc = fopen(bashrcDir, "w");
        while (fgets(str, MAXCHAR, newTempfile) != NULL) {
            fprintf(newBashrc, "%s", str);
        }

        fclose(newTempfile);
        fclose(newBashrc);

        remove("./tempFile.txt");
    }
}

谢谢!