您的位置:首页 > 其它

将一些格式化的数据写入文本文件,…

2014-01-13 16:09 183 查看
#include<stdio.h>

main()

{

 FILE *fp;

 int i;

 struct
stu      
//定义结构体类型

 {

  char name[15];

  char num[6];

  float score[2];

 }student;                              
//说明结构体变量

 if((fp=fopen("test.txt","w"))==NULL)   
//以文本只写方式打开文件

 {

 printf("can't open file,strike any key
exit!");

 exit(0);

 }

 printf("input data:\n");

 for(i=0;i<2;i++)

 {

  scanf("%s%s%f%f",student.name,student.num,&student.score[0],&student.score[1]);   
//从键盘上输入

  fprintf(fp,"%s%s%7.2f%7.2f",student.name,student.num,student.score[0],student.score[1]);

 }                                                                   
//写入文件

 fclose(fp);                                                         
//关闭文件

 if((fp=fopen("test.txt","r"))==NULL)                                
//以文本只读方式重新打开文件

 {

  printf("cannot open
file");

  exit(0);

 }

 printf("output from file:\n");

 while(fscanf(fp,"%s%s%f%f\n",student.name,student.num,&student.score[0],&student.score[1])!=EOF);//从文件读入

 printf("%s %s %7.2f
%7.2f\n",student.name,student.num,student.score[0],student.score[1]);
//显示到屏幕

 fclose(fp);                   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐