I am trying to overwrite the contents of a FILE in C. Currently I have:
FILE* file = fopen("filename.txt", "r+");
fprintf(file, "%d", 1); // regardless of what's in the file, i want to clear it and put 1 in there
...
// legacy code somewhere else in the code base. can't change.
rewind(file);
fprintf(file, "%d", 2);
fflush(file);
However, this will not work properly. The result will be:
1, 21
Each subsequent number will be written to the beginning of the 1. For example:
1, 21, 31, 41, ...
I would like to know if there is a way to always overwrite what's in the file so the following is produced:
1, 2, 3, 4, ...
Any assistance would be appreciated.
Thank you.
EDIT:
I have changed the code to:
FILE* file = fopen("filename.txt", "w+");
The problem still persists.
If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.
You can also overwrite data by replacing old files with new ones. If you are saving a document with the same filename as an already existing document, then the old document will be overwritten by the new one.
fopen() for an existing file in write mode When mode “w” is specified, it creates an empty file for output operations. What if the file already exists? If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
fwrite() does not exactly overwrite by using fseek(). Instead, there are several cases: if the open permissions was 'r' then writing is an error.
You decide that in fopen
. Just use "w"
or "w+"
instead of "r+"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With