c语言文件打开方式:
"r",以只读方式打开,文件必须存在。
"w",以只写方式打开,若文件不存在则新建一个;若文件存在则清除原有的所有数据,重新写入
所以我们可以先读取文件数据(文件打开方式"r")存入到结构体数组中,
再修改结构体数组中要修改的数据,
再将修改后的结构体数组中的数据,写入(文件打开方式"w")到文件中
结构体
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
#define OK 1
#define ERROR 0
typedef struct {
char name[10];//姓名
char id[20];//学号
char sex[10];//性别
char province[10];//省
char city[10];//市
char state[10];//学生状态
char year[10];//入学年份
}Student;
读取
int read(Student List[])//读取文件
{
int i;
FILE *fp;
fp=fopen("data.txt","r");
if(fp==NULL)
{
printf("文件打开失败!");
exit(0);
}
while(!feof(fp))
{
fscanf(fp,"%s\t%s\t%s\t%s\t%s\t%s\t%s\n",List[i].name,List[i].id,List[i].sex,List[i].province,List[i].city,List[i].state,List[i].year);
i++;
}
fclose(fp);
return i;
}
修改前的文件
修改
void modify(Student List[],int n)//修改
{
int i;
char xh[20],zt[10];
printf("请输入要修改的学生学号(1001001000到1001001029):\n");
scanf("%s",xh);
for(i=0;i<n;i++)
if(!strcmp(xh,List[i].id))
break;
if(i==n)
{
printf("没有该学号的学生!");
return ;
}
printf("修改前:\n姓名:%-8s入学年份:%-5s\t当前状态:%s\n",List[i].name,List[i].year,List[i].state);
printf("请输入要更改的状态(在籍、休学、结业、毕业):");
scanf("%s",zt);
strcpy(List[i].state,zt);
printf("修改后:\n姓名:%-8s入学年份:%-5s\t当前状态:%s\n",List[i].name,List[i].year,List[i].state);
}
更新
void updata(Student List[],int n)//更新文件
{
int i;
FILE *fp;
fp=fopen("data.txt","w");
if(fp==NULL)
{
printf("文件打开失败!");
exit(0);
}
for(i=0;i<n;i++)
fprintf(fp,"%s\t%s\t%s\t%s\t%s\t%s\t%s\n",List[i].name,List[i].id,List[i].sex,List[i].province,List[i].city,List[i].state,List[i].year);
fclose(fp);
}
运行
修改后的文件