文件的操作

一直以来对文件的操作过程并不是特别熟悉,贴出以下代码来提醒自己,也从实际的例子中感受文件的操作运用

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Students
{
char Id[10];
char name[20];
double score;
}Student;
void main()
{
Student stu;//定义学生结构变量
readText("./tmp/computer.txt");
printf("-------------------------------------\n");
strcpy(stu.Id,"B10003");
strcpy(stu.name,"隔壁老王");
stu.score=99;
writeText("./tmp/computer.txt",stu);
readText("./tmp/computer.txt");
}
void writeText(char *filename,Student stu)
{
FILE *fp;
fp=fopen(filename,"a+");//
// a+ 打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。
// 读取会从文件的开头开始,写入则只能是追加模式。
// a 打开一个文本文件,以追加模式写入文件。如果文件不存在,则会创建一个新文件。
// 程序会在已有的文件内容中追加内容。
if(!fp)
{
printf("文件不存在!\n");
exit(1);
}
fprintf(fp,"%s %s %lf\n",stu.Id,stu.name,stu.score);
fclose(fp);
}
void readText(char *filename)
{
Student stu;//定义学生结构变量
FILE *fp;
fp=fopen(filename,"r");//
// a+ 打开一个文本文件,允许读写文件。如果文件不存在,则会创建一个新文件。
// 读取会从文件的开头开始,写入则只能是追加模式。
if(!fp)
{
printf("文件不存在!\n");
exit(1);
}
fscanf(fp,"%s%s%lf",stu.Id,stu.name,&stu.score);//读入一条记录
while(!feof(fp))//如果位置指针不在文件末尾,即没有读到文件末尾
{
// fprintf(stdout,"%-8s%-8s%3.2lf\n",stu.Id,stu.name,stu.score);//输出到标准输出stdout(屏幕)
//等价于:
printf("%-8s%-8s%3.2lf\n",stu.Id,stu.name,stu.score);
//%3.2lf 表示小数点前面有三位,小数点后面有两位
// %-8d表示显示长度最小为8个字符,不足的话右边补空格,比如 123456,显示的是“123456空格空格”
fscanf(fp,"%s%s%lf",stu.Id,stu.name,&stu.score);//读入下一条记录
//stu.Id这里是数组名,本质上是地址所有不用再加取地址符&
//stu.score是double类型变量,
// 要加上取地址符“&”,让扫描函数知道把扫描到的第三数据放到的内存空间的地址
}
fclose(fp);
}

posted @ 2020-02-29 10:47  AUwegst  阅读(125)  评论(0编辑  收藏  举报