作者scan33scan33 (亨利喵)
看板b98902HW
标题Re: [问题] 求助强者 "r+" 的奇怪现象
时间Sat Dec 5 01:50:49 2009
路人低调路过,想回一下唷!
详见:
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
有一段说:
For the modes where both read and writing (or appending) are allowed (those
which include a "+" sign), the stream should be flushed (fflush) or
repositioned (fseek, fsetpos, rewind) between either a reading operation
followed by a writing operation or a writing operation followed by a reading
operation.
就是你读/写切换要fseek一下就是了,详情为啥我有点忘,想到再跟你讲好了XD
好像是buffer问题啦!...
Read/Write buffer似乎是共用的之类的事情.....
AC的code应该像这样...
#include<stdio.h>
int main()
{
FILE *ptr;
int data;
ptr=fopen("in.txt","r+");
fscanf(ptr,"%d",&data);
fseek(ptr,0,SEEK_CUR);
fprintf(ptr,"test");
fprintf(ptr,"%d\n",data);
fclose(ptr);
return 0;
}
※ 引述《barry800414 (小铭)》之铭言:
: 本来我是打算读书会把fopen 的参数都讲一下
: 然实际的看有什麽现象发生
: 不过我今天试了好久
: 发现了奇怪的事情...
: 自己都爆炸了 XD
: #include<stdio.h>
: int main()
: {
: FILE *ptr;
: int data;
: ptr=fopen("in.txt","r+");
: fscanf(ptr,"%d",&data);
: fprintf(ptr,"test");
: fprintf(ptr,"%d\n",data);
: fclose(ptr);
: return 0;
: }
: in.txt的内容
: 第一种是只有123456
: 这六个字元 连换行都没有
: 这个程式可以成功的让in.txt的内容变成
: 123456test123456
: 第二种是123456这六个字元加一个换行
: 奇怪的事情发生了
: 跑完之後in.txt的内容还是123456
: 连"test" 都没办法输出
: 而我看上课的讲义上r+是这麽写:
: Open an existing file for update (reading and writing)
: update的定义到底是什麽?
: 为什麽上面的程式在第二种状况会这样ˊˋ?
: 请诸位强者知道的帮忙一下 感激不尽
: 噢我是用devcpp 跑的 附档名存.c
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.90.67
※ 编辑: scan33scan33 来自: 140.112.90.67 (12/05 01:58)
1F:→ purincess:感觉还是写fflush(ptr); 比较有fu XD 12/05 02:07
2F:推 ckclark:可是fflush(ptr)好像有时会失灵 12/05 02:13
3F:→ scan33scan33:对耶!是会失效...我刚刚对这份code试过好像就不行. 12/05 02:14
4F:→ scan33scan33:话说dev-C的 FILE header跟工作站上的不一样. 12/05 02:15
5F:→ scan33scan33:所以效果应该是会不一样. 12/05 02:15