c语言更改文件中的数据

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);
}

运行

修改后的文件

  • 10
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值