如何用c语言实现文件先写入部分数据,然后再读取输出在屏幕上

#include<stdio.h>
int main()
{
FILE *fp;
char read[1000];
char s;
long p;

if((fp=fopen("1s.txt","a"))==NULL)
{
printf("\nOpen file error!press any key exit!");
getchar();
exit(0);
}

p=123456;
s='\n';

fputc(p,fp);
fputc(s,fp);
fputc(p,fp);

fgets(read,1000,fp);
printf("%s",read);

system("pause");
return 0;
}

这个输出没结果,直接就是"按任意键退出“

    文件先写入部分数据,然后再读取输出在屏幕上,所以,在打开文件时必须以可读写方式"+"打开文件。(r+ w+ a+均可)

    写完后,再读。因此,要把文件指针前移才可以,否则当前位置处在已写完的数据位置,无法读到数据。
    参考代码:

#include<stdio.h>
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;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-09
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;}追问

这个运行结果是123456\n而不是
123456\n
123456啊?是什么原因呢

追答

因为 fgets 只读1行,含 \n.

写数据时,两个 123456 之间,fputc(s,fp); 写了一个 \n, 这个 \n 不只是 一个字符,而且是功能键,使文件里文字换了行。文件成为2行:
123456
123456
----------------------
而不是
123456 无功能字符 123456

追问

它只有一行123456啊

追答

不明白 “追问它只有一行123456啊” 是什么意思,你的 1s.txt 里只有 1行?
fprintf(fp,"%d",p); // 写出 123456
fputc(s,fp); // 换行
fprintf(fp,"%d",p); // 写出 123456
写成的文件内容是两行,第一行123456,第二行123456。
在DOS 窗,打 more 1s.txt 你可以看到文件内容
123456
123456
不会只有1行。
----
fgets(read,1000,fp); fgets的功能就是 只 读入一行。
printf("%s",read); 在屏幕上打出
123456

本回答被提问者采纳
第2个回答  2013-03-09
在你fputc之后文件的当前指针停留在文件末尾,这样你fgets什么都不会读到。
建议将文件指针设置返回文件头,即在fgets语句前面加:fseek(fp,0L,SEEK_SET);
相似回答