格式化读写文件

作者在 2010-03-30 21:54:59 发布以下内容
#include<stdio.h>
main()
{
   FILE  *fp;
   int i;
   struct rec{
       char id[10];
       char name[15];
       char department[15];
   }record;
  printf("****************************************\n");
  printf("This program is to show the format file input & output\n");
  printf("************************************************\n");
    if((fp=fopen("f:\\infile.txt","w"))==NULL)
      {
          printf("cannot open file");
          exit (1);    
      }      
     printf("please input data:\n");
     for(i=0;i<2;i++)
     {
        printf("please input id:\n");
        scanf("%s",record.id);
        printf("input name:\n");
        scanf("%s",record.name);
        printf("input department:\n");
        scanf("%s",record.department);
        fprintf(fp,"%s %s %s\n",record.id,record.name,record.department);
     }
     fclose(fp);
     if((fp=fopen("f:\\infile.txt","r"))==NULL)
     {
       printf("cannot open file");
       exit(0);    
     }
     printf("output from file:\n");
     while(fscanf(fp,"%s %s %s\n",record.id,record.name,record.department)!=EOF)
     {
       printf("id:%s  name:%s department:%s\n",record.id,record.name,record.department);    
     }
     fclose(fp);
     scanf("%d",i);
}
 
默认分类 | 阅读 461 次
文章评论,共0条
游客请输入验证码
浏览11146次
文章分类
最新评论