gpt4 book ai didi

c - 在 C 中使用 fputs 写入文件

转载 作者:太空狗 更新时间:2023-10-29 16:29:21 25 4
gpt4 key购买 nike

有人能告诉我为什么文件没有改变吗?它在我使用 rewindfseek 时有效,但在其他情况下无效。

fgets 之后使用 fputs 的标准方法是什么。文件指示器位于位置 9,因此 fputs 必须在其后写入,但它什么都不做。

在文件中:

abcd efgh ijkl mnor

在源代码中:

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

最佳答案

关于fopen/'+'的定义在 C 标准中(例如 this online C standard draft ),从读取切换到写入需要中间调用文件定位函数(重点是我的):

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.

所以我建议您编写以下代码来解决您的问题:

fseek ( fp , 0, SEEK_CUR);
fputs(str, fp);

关于c - 在 C 中使用 fputs 写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46152077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com