Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

string - Write to a file using fputs in C

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
", ftell(fp));
// ftel shows that it's in "9".

printf("%s", str);

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

fclose(fp);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...