文件先写入部分数据,然后再读取输出在屏幕上,所以,在打开文件时必须以可读写方式"+"打开文件。(r+ w+ a+均可)
写完后,再读。因此,要把文件指针前移才可以,否则当前位置处在已写完的数据位置,无法读到数据。
参考代码:
#include
int main()
{
FILE *fp;
char read[1000];
char *p="hello";
char s='\n';
if((fp=fopen("data.txt","a+"))==NULL) //追加方式,可读可写
{
printf("\nOpen file error!press any key exit!");
return -1;
}
fputs(p,fp); //写一个串hello
fputc(s,fp); //写一个回车符
fputs(p,fp); //再写一个串hello
fseek(fp, -5, SEEK_CUR ); //从当前位置,向前移动5个字节文件指针
fgets(read,1000,fp); //读取数据
printf("%s",read); //得到hello
fclose(fp);
return 0;
}
fopen() 改为: if((fp=fopen("1s.txt","w+"))==NULL)
fputc(p,fp); 改为:fprintf(fp,"%d",p);
读语句前,加一句文件回绕到文件头: rewind(fp);
----------------
int main(){
FILE *fp;
char read[1000];
char s;
long p;
if((fp=fopen("1s.txt","w+"))==NULL)
{
printf("\nOpen file error!press any key exit!");
getchar();
exit(0); }
p=123456;
s='\n';
fprintf(fp,"%d",p);
fputc(s,fp);
fprintf(fp,"%d",p);
rewind(fp);
fgets(read,1000,fp);
printf("%s",read);
system("pause");
return 0;}
在你fputc之后文件的当前指针停留在文件末尾,这样你fgets什么都不会读到。
建议将文件指针设置返回文件头,即在fgets语句前面加:fseek(fp,0L,SEEK_SET);