简体   繁体   English

C读取后无法写入文件

[英]C cannot write to file after reading

I have a function in the program that has to remove a given string from a file.我在程序中有一个函数,它必须从文件中删除给定的字符串。 To do this, rewrites the entire file into a temporary file and then overwrites the original file.为此,将整个文件重写为临时文件,然后覆盖原始文件。 Saving a temporary file with the removed string works, but overwriting the original file does't work.使用已删除的字符串保存临时文件有效,但覆盖原始文件无效。

What's wrong here?这里有什么问题?

#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+ allows you to read the file and overwrite it. r+ 允许您读取文件并覆盖它。 I'm wrong?我错了?

Referring to @KamilCuk answer, here's the solution:参考@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");
    }
}

Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM