Oscar Nydza
Oscar Nydza

Reputation: 33

File deletes content after stopping execution in C

So I'm trying to save a bunch of data in a text file to load it later. The function prints the data to the text file correctly, but when I stop the execution and start it again to see if it loads, there is no data in the text file. It happens right after I stop the program.

Here is the function used:

void saveGame(t_game game, int width, int height){
FILE * file= fopen("save.txt", "w+");
int i = 0;
int j = 0;

fprintf(file,"%d%d", game.origbomb, game.wincount);

for(i=0;i<width;i++){
    for(j=0;j<height;j++){
        fprintf(file,"%c",game.map[i][j]);
    }
}
for(i=0;i<width;i++){
        for(j=0;j<height;j++){
            fprintf(file,"%c",game.bombmap[i][j]);
        }
    }
fclose(file);}

Upvotes: 1

Views: 83

Answers (2)

jpo38
jpo38

Reputation: 21584

If you "stop the execution", then I suppose fclose was not called, then only flushed data will be present in the file. Use fflush to manually force the file content to be flushed just after you called fprintf.

Also, consider checking file content from a file editor rather than a program. Maybe you are not reading it correctly.

Finally, consider opening the file with "a" option if you mean to extend an existing content without creating a new file.

Upvotes: 1

prmottajr
prmottajr

Reputation: 1824

You should use:

FILE * file= fopen("save.txt", "a+");

This will append to the file.

Upvotes: 3

Related Questions