Search code examples
cprintffgets

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. I'm wrong?


Solution

  • Referring to @KamilCuk answer, here's the solution:

    #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!