C 读取文件后无法写入

标签 c printf fgets

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

这里出了什么问题?

#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");
    }
}

谢谢!

关于C 读取文件后无法写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726763/

相关文章:

c - 如何用C读取主文件表(MFT)?

c++ - 枚举类 - printf 打印出错误的值

c - realloc 与 free 一起使用

c - 'restrict' 关键字 - 为什么允许从外部限制变量分配给内部限制变量?

c - 警告 : assignment makes integer from pointer without a cast

c - wprintf : %p with NULL pointer

c++ - 这段代码的输出是什么?为什么?

c - c中fputs和puts的区别

c - 为什么这个 fgets() 循环永远不会结束?

c - 在 C 中读取十六进制文件