|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- rewind(fp);
- printf("%ld\n",ftell(fp));//0
- //update the content of ftell.txt with "hello"
- fputs("hello",fp);
- //print the current position of fp
- printf("%ld\n",ftell(fp--));//5
- printf("%ld\n",ftell(fp));//4
- fclose(fp);
复制代码
ftell.txt文件中原来存储的内容是Fishc,我rewind以后,存入hello,
这时候使用ftell(fp),打印得到5,同时fp指针执行fp--,
再打印时不应该是4吗
但是打印结果为0,请问这是为什么呢
本帖最后由 jackz007 于 2019-10-18 10:01 编辑
文件指针是个 handle,就是一个句柄,用来代表被读写的文件,在用 fopen() 函数打开文件的时候,由系统分配得到这个指针,文件操作完毕以后,要用 fclose() 函数进行关闭,用户永远不可以自行改变文件指针的数值。可以改变的应该是文件的读写指针位置,而不是文件指针本身,读写指针会随着文件的读写操作而自动改变。所以,下面这一句是错误用法:
- printf("%ld\n",ftell(fp--));//5
复制代码
我想,你的代码应该写成这样:
- #include <stdio.h>
- main()
- {
- FILE * fp ;
- if((fp = fopen("ftell.txt" , "w")) != NULL) {
- fputs("I love Fishc\n" , fp) ;
- printf("ftell() = %d\n" , ftell(fp)) ;
- rewind(fp) ;
- printf("ftell() = %d\n" , ftell(fp)) ;
- fputs("hello\n" , fp) ;
- printf("ftell() = %d\n" , ftell(fp)) ;
- fclose(fp) ;
- }
- }
复制代码
|
|