C读取后无法写入文件

问题描述 投票:0回答:1

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

这里怎么了?

#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 +允许您读取文件并覆盖它。我错了?

c printf fgets
1个回答
0
投票

参考@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");
    }
}

谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.