#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
温馨提示:答案为网友推荐,仅供参考