C语言中怎么把文件中的数据赋到结构体的成员中?

姓名:犀利哥
性别:男
年龄:十二岁
这是我在D盘中建立的 简历。txt文件
我想用文件函数打开简历.txt文件,再定义一个结构体,结构体的格式也像简历中的格式。
struct student
{
char name;
char sex;
char age;
}stu;
怎么把文件里面的数据按顺序赋值到结构体的成员中?
我想要的结果是最后结构体中 char name=犀利哥,char sex=男,char age=十二岁;
求高手给我详细代码,要注释,最好你编译下,不然我又白忙了。很急哈,马上答辩了:
跪谢!!!!!!!!!!!!!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 100 //宏定义SIZE

struct student
{
char name[SIZE];
char sex[10];
char age[10];
}stu;

int fread_line_txt(FILE *fp, char *buf) // 读取文件中的一行
{
int i = 0;
while ((buf[i] = fgetc(fp)) != '\n')
{
i++;
if (i >= 99)
{
printf("SIZE lower! please alter SIZE\n");
return -1;
}
}
return i;
}

int cp_content (FILE *fp, char *buf, const char *name, char *dst) // 拷贝文件中指定内容 到字符串指针dst中
{
int i = 0;
char *p;
i = fread_line_txt(fp, buf);
buf[i] = 0;
if (p = strstr(buf, name))
{
memcpy(dst, p + strlen(name), strlen(p) - strlen(name));
}
return 0;
}

int main(void)
{
FILE *fp;
char buf[SIZE] = {0};
fp = fopen("1.txt", "r");
if (NULL == fp)
{
printf("fopen failed\n");
return -1;
}

memset((void *)&stu, 0, sizeof(struct student));

cp_content(fp, buf, "姓名:", stu.name);
memset(buf, 0, SIZE);

cp_content(fp, buf, "性别:", stu.sex);
memset(buf, 0, SIZE);

cp_content(fp, buf, "年龄:", stu.age);

printf("stu.name = %s, stu.sex = %s, stu.age = %s\n", stu.name, stu.sex, stu.age);
return 0;
}

//1.txt 应写成这样 要区分拼音和英文大小写
#if 0
姓名:犀利哥
性别:男
年龄:十二岁
#endif
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-01-03
stu A={"犀利哥","男","十二岁"};
第2个回答  2019-01-14
运行结果:
文本中的内容:
姓名:犀利哥
性别:男
年龄:十二岁
程序:
#include
<stdio.h>
#include
<stdlib.h>
struct
student
{

char
name[30];

char
sex[10];

char
age[30];
}stu;
void
main(void)
{

FILE*
pFile
=
NULL;

pFile
=
fopen("D:\\简历.txt",
"r");

fscanf(pFile,
"姓名:%s\n",
&stu.name);

fscanf(pFile,
"性别:%s\n",
&stu.sex);

fscanf(pFile,
"年龄:%s\n",
&stu.age);

fclose(pFile);
}
相似回答