如题,怎么用C语言来实现从已有的文件中根据输入一个关键字就会显示出与其相关的信息并输出。比如文件中的信息是 学号:1 姓名:小明 性别:男然后输入关键字,比如“小明”,就会出现有关他的信息,并输出,大概是不是也会用到file相关的函数和结构体之类的
希望能有具体的代码,能够运行,随便弄个事例就行。
用C语言实现根据关键字在文件中查找相关信息并输出
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- 广大菜鸟 2021-12-10 02:05关注
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAXSIZE 1024 struct student { char sno[20]; char sname[20]; char sex[10]; }; char*getInfo(char*source,char split){ char*p=source; while(p!=NULL&&*p!='\0' &&*p!=split){ p=p+1; } return p; } struct student* classroom_student[MAXSIZE]; void browseFile(const char* fileName) { FILE*fp =fopen(fileName, "r+"); char in_no[MAXSIZE]="\0", in_name[MAXSIZE] = "\0", in_sex[MAXSIZE] = "\0"; char*tmp; int i=0; while (!feof(fp)) { //获取一行 fscanf(fp,"%s",in_no); fscanf(fp,"%s",in_name); fscanf(fp,"%s",in_sex); //printf("%s %s %s\n",in_no,in_name,in_sex); classroom_student[i] = (struct student*)malloc(sizeof(struct student)); tmp=getInfo(in_no,':'); strcpy(classroom_student[i]->sno,tmp+1); tmp=getInfo(in_name,':'); strcpy(classroom_student[i]->sname,tmp+1); tmp=getInfo(in_sex,':'); strcpy(classroom_student[i]->sex,tmp+1); i+=1; } fclose(fp); } int main() { browseFile("C:\\Users\\Lenovo\\Desktop\\students.txt"); char name[20]="小明"; struct student*p=classroom_student[0]; int i=0; while(p!=NULL&&strcmp(p->sname,name)!=0){ p=classroom_student[i++]; } if(p!=NULL){ printf("名字:%s 编号:%s 性别:%s\n",p->sname,p->sno,p->sex); }else{ printf("查无此人\n"); } system("pause"); }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 2无用 1
悬赏问题
- ¥15 教务系统账号被盗号如何追溯设备
- ¥20 delta降尺度方法,未来数据怎么降尺度
- ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
- ¥15 再不同版本的系统上,TCP传输速度不一致
- ¥15 高德地图点聚合中Marker的位置无法实时更新
- ¥15 DIFY API Endpoint 问题。
- ¥20 sub地址DHCP问题
- ¥15 delta降尺度计算的一些细节,有偿
- ¥15 Arduino红外遥控代码有问题
- ¥15 数值计算离散正交多项式