有关fscanf和fprintf的问题

snser 2010-06-30 02:52:09
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
FILE *temp=fopen("e:\\temp.ini","w");
fprintf(temp,"123\n456");
fclose(temp);
temp=fopen("e:\\temp.ini","r+");
//fseek(temp,5,1);
fscanf(temp,"%*s%*c");fflush(stdin);
//printf("loc=%d",ftell(temp));system("pause");
fprintf(temp,"000");
fclose(temp);
system("start e:\\temp.ini");
return 0;
}

先建立一个temp.ini,内容是
123
456
如果用fscanf(temp,"%*s%*c");读掉123和回车,再写000,最终并没有写进去,这是为什么啊?
但要是把fscanf换成fseek(temp,5,1); ,就能写进000
可以用printf("loc=%d",ftell(temp));验证:fscanf或fseek之后,ftell(temp)的值都是5
...全文
287 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
snser 2010-06-30
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 huanmie_09 的回复:]
When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.
http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
[/Quote]

谢谢~~~
huanmie_09 2010-06-30
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 snser 的回复:]
回复6L:
你的方法试了,终于得到了我想要的结果,谢谢~
fseek(temp, 0L, SEEK_CUR); 是从当前位置向前移0个字节,这个跟没移有什么区别呃?
能解释一下原因吗?
[/Quote]
When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.
http://msdn.microsoft.com/en-us/library/yeby3zcb%28VS.71%29.aspx
snser 2010-06-30
  • 打赏
  • 举报
回复
回复1L:
"r+"是读写,"r"是只读

回复2L:
"wb+"是为读写打开二进制文件吧,我运行了下
如果用fseek(temp,5,1);结果是:
000
如果用 fscanf(temp,"%*s%*c");结果是:
000
貌似"wb+"和"w"的共同点是删除原来的temp.ini,再新建一个

回复3L:
额。。。windows和linux下的结果不一样。。。o(╯□╰)o

回复4L:
同学习~~~

回复5L:
%*s读掉123 %*c读掉\n 然后不就到465处了吗?用ftell(temp);显示结果也是5啊 和fseek(temp,5,1);一样啊

回复6L:
你的方法试了,终于得到了我想要的结果,谢谢~
fseek(temp, 0L, SEEK_CUR); 是从当前位置向前移0个字节,这个跟没移有什么区别呃?
能解释一下原因吗?
huanmie_09 2010-06-30
  • 打赏
  • 举报
回复
把fflush(stdin);
改为:
fseek(temp, 0L, SEEK_CUR);
qvbnlaw 2010-06-30
  • 打赏
  • 举报
回复
fprintf(temp,"123\n456");
fscanf(temp,"%*s%*c")
着两个的格式要一样!!!不然会出错!!!
Arthur_ 2010-06-30
  • 打赏
  • 举报
回复
学习了
njuhuangmy 2010-06-30
  • 打赏
  • 举报
回复
我在 ubuntu 下面试了你的代码 ( e:\\temp.ini 被我改成 temp.ini , system函数注释掉)
发现结果是

123
000
Luyi06292 2010-06-30
  • 打赏
  • 举报
回复
temp=fopen("e:\\temp.ini","wb+");
zsjsgyy 2010-06-30
  • 打赏
  • 举报
回复
temp=fopen("e:\\temp.ini","r+");
你是以只读的方式打开的

69,374

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧