源代码:
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *pf=fopen("test.txt","w");
fputs("我是帅哥",pf);
FILE *pd=fopen("test.txt","r");
char name[20];
fgets(name,strlen("我是帅哥")*2+1,pd);
printf("%s",name);
fclose(pf);
pf=NULL;
fclose(pd);
pd=NULL;
return 0;
}
输入以上代码后为什么输出的结果是这样?(原字符串是NULL)
因为数据缓冲区!!!
此时pf指针对文件的写操作,“我是帅哥”字符串会被放入缓冲区,而不是直接放入文件!!!
对此的解决方案有多种
- 用flush()强迫将缓冲区内的数据写回参数stream 指定的文件中。
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *pf=fopen("test.txt","w");
fputs("我是帅哥",pf);
FILE *pd=fopen("test.txt","r");
fflush(pf);//解决方法
char name[20];
fgets(name,strlen("我是帅哥")*2+1,pd);
printf("%s",name);
fclose(pf);
pf=NULL;
fclose(pd);
pd=NULL;
return 0;
}
- 关闭文件之后,缓冲区内的数据会被读入文件;所以先操作完pf写文件将其关闭再操作读文件
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *pf=fopen("test.txt","w");
fputs("我是帅哥",pf);
FILE *pd=fopen("test.txt","r");
//解决方法,先关闭该文件再打开
fclose(pf);
pf=NULL;
char name[20];
fgets(name,strlen("我是帅哥")*2+1,pd);
printf("%s",name);
fclose(pd);
pd=NULL;
return 0;
}
- rewind(),fseek()等操作文件内部位置指针也可以刷新数据缓冲区,做到fflush的效果
#include<stdio.h>
#include<string.h>
int main(void)
{
FILE *pf=fopen("test.txt","w");
fputs("我是帅哥",pf);
FILE *pd=fopen("test.txt","r");
//解决方法二选一
rewind(pf);//
fseek(pf,0,SEEK_SET);//偏移量和起始位置任选
//注意不推荐使用,因为这两个函数主要功能是起到指向一个所需的位置,刷新缓冲区只是附带的
char name[20];
fgets(name,strlen("我是帅哥")*2+1,pd);
printf("%s",name);
fclose(pf);
pf=NULL;
fclose(pd);
pd=NULL;
return 0;
}
小编刚开始以为这个是与文件位置指针有关(刚开始认为可能是文件内部使用一个位置指针),这是错误的。
#include<stdio.h>
int main(void)
{
FILE *pf=fopen("test.txt","r");
FILE *pd=fopen("test.txt","r");
//test.txt内容为abcdef
fputc(pf);
//ftell计算偏移量为多少的函数
printf("%d",ftell(pf));//1
printf("%d",ftell(pd));//0
}
从结论可以看出两个指针是各管各的。
有问题可以一起交流哦