I need to read, and then write to a file. I don’t want to use “r+” because I completely overwrite it anyway. But I am unable to completely close the file. If I try to open the file for the second time, the applications crashes (can’t open). Does anyone know how to completely close the file.
And this is not the actually code, just a summary of what I want to do:
FILE* f;
fopen_s(&f, "test.txt", "r");
// read file and edit data
fclose(f);
f = 0;
fopen_s(&f, "test.txt", "w");
fprintf(f, "%c", data);
fclose(f);
fclose()closes the file. It doesn’t half close it. The notion of “completely closing” a file doesn’t exist. A file is either open or closed. There’s no in-between.Although in your code you’re using
fopen_s()to open the file. I’ve no idea what that function is. I assume it works likefopen(), but instead of returning aFILEpointer, it instead stores it in its argument.So the answer to your question is: to “completely” close a file, use
fclose(). As you already do. That means the problem you’re having lies elsewhere.