Could someone tell me why the file doesn\'t change? It works when I use rewind
or fseek
but not otherwise.
What\'s the standard way of usin
Regarding the definition of fopen/'+' in the C standard (e.g. as in this online C standard draft), switching from reading to writing requires an intermediate call to a file positioning function (emphasis are mine):
7.21.5.3 The fopen function
(7) When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.
So I'd suggest you write the following code to overcome your problem:
fseek ( fp , 0, SEEK_CUR);
fputs(str, fp);
The MS documentation for fopen
says this:
When the
"r+"
,"w+"
, or"a+"
access type is specified, both reading and writing are enabled (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter anEOF
marker. If there is noEOF
, you must use an intervening call to a file positioning function. The file positioning functions arefsetpos
,fseek
, andrewind
. When you switch from writing to reading, you must use an intervening call to eitherfflush
or to a file positioning function.