Write to a file using fputs in C

后端 未结 2 1802
走了就别回头了
走了就别回头了 2020-12-17 10:24

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

2条回答
  •  半阙折子戏
    2020-12-17 10:39

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

提交回复
热议问题