在C中使用fputs写入文件 [英] Write to a file using fputs in C

查看:376
本文介绍了在C中使用fputs写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么文件不更改吗?当我使用rewindfseek时可以使用,但是不能使用其他方式.

Could someone tell me why the file doesn't change? It works when I use rewind or fseek but not otherwise.

fgets之后使用fputs的标准方式是什么.文件指示器位于位置9处,因此fputs必须在那之后写入,但是它什么也没做.

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.

在文件中:

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标准中)(例如,如此在线C标准草案),从读取到写入的切换需要对文件定位功能的中间调用(重点是我的):

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 fopen函数

(7)以更新模式打开文件时(第二个或第三个为'+' 上面的模式参数值列表中的字符),输入和 输出可以在相关的流上执行.但是,输出 不得在没有中间调用的情况下直接输入 fflush功能或文件定位功能(fseek,fsetpos, 或快退),并且在没有输入的情况下,输入后不能直接跟在输出后 对文件定位功能的中间调用,除非输入 操作遇到文件结尾.打开(或创建)文本文件 使用更新模式可能会在某些情况下打开(或创建)二进制流 实施.

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

这篇关于在C中使用fputs写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆