18

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 using fputs after fgets. The file indicator is at position 9 so fputs must write after that, but it doesn't do anything.

In file:

abcd efgh ijkl mnor

In source code:

char c;
char str[15];

FILE *fp = fopen("d:\\data.txt","r+");

fgets(str, 10, fp);

// fseek(fp, 9, SEEK_SET);
// rewind(fp);

printf("%d\n", ftell(fp));
// ftel shows that it's in "9".

printf("%s", str);

fputs(str, fp);
// why its not working

fclose(fp);
Exon
  • 315
  • 2
  • 9
  • 10
    When and where and how do you check the output? Between the `fputs` and `fclose` calls? Perhaps you should `fflush` the file buffers? – Some programmer dude Sep 11 '17 at 09:17
  • 1
    Suppose the file, which was opened for reading and updating, contains two lines of text. You read the first line, and then write it to the same file. Where do you suppose that will be written? Can you see a need for explicitly setting the file pointer after a read, before writing? – Weather Vane Sep 11 '17 at 09:34
  • to edit from the current location use `fseek ( fp , 0L , SEEK_CUR);` – krpra Sep 11 '17 at 09:58

2 Answers2

26

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);
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
7

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 an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56