【发布时间】:2015-05-26 15:17:09
【问题描述】:
我的文本文件是这样的,
Person.txt
John
{
sex = "Male";
age = 23;
};
Sara
{
sex = "Female";
age = 23;
};
stephan
{
sex = "Male";
age = 25;
};
我想根据请求获取特定人员的数据。例如,我收到了获取 Stephan 数据的请求。我想,首先我需要阅读 person.txt 来搜索 Stephan,然后获取他的信息。我有点困惑使用 fread 以正确的方式做到这一点。这是我的代码,
struct personS
{
int age;
char sex[7];
} personS;
FILE *fp;
void check_person_data(const char *name, int *age, const char *sex)
{
PersonS *person;
if((fp=fopen("Person.txt", "r")) == NULL)
printf("File reading error\n");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char buffer[size];
while(fread(buffer, size, 1, fp) != NULL)
{
if((strstr(buffer, name)) != NULL)
{
printf("Match found \n");
fread(&person, sizeof(struct personS), 1, fp);
*age = person->age;
*sex = person->sex;
}
else
printf("Match not found \n");
}
fclose(fp);
}
我做了两次 fread,一次是搜索字符串,另一次是获取结构。这是正确的做法还是其他更好的方法?
【问题讨论】:
-
我建议您使用
fgets读取行数未知的文本文件。它将数据读取到(并包括)下一个换行符,因此尽管您需要足够的空间来读取该行,但您不需要知道它在 读取它之前有多长时间。另一方面,fread通常用于已知大小的二进制信息。
标签: c struct fread fseek strstr