gpt4 book ai didi

c - 如何从数据数组的结构中搜索特定结构并使用 fread 读取?

转载 作者:太空宇宙 更新时间:2023-11-04 03:38:23 26 4
gpt4 key购买 nike

我的文本文件是这样的,

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

我做了 2 次 fread,一次是搜索字符串,另一次是获取结构。这是正确的做法还是其他更好的方法?

最佳答案

该示例似乎是一个文本文件,可以使用 fgets()sscanf() 读取。读取文件以查找匹配名称不需要该结构,因此将其省略。一旦读取了值,调用函数就可以将它们放入结构中。

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

int check_person_data(char *name, int *age, char *sex)
{
char buffer[50] = {0};
FILE *fp;

if ( ( fp = fopen ( "person.txt", "r")) == NULL) {
printf ( "file reading error\n");
return 2;
}

while ( fgets ( buffer, sizeof ( buffer), fp)) {
if ( buffer[0] == '\n') {
continue;//blank line
}
if ( buffer[strlen(buffer)-1] == '\n') {
buffer[strlen(buffer)-1] = '\0';//remove trailing newline
}
if ( strcmp ( buffer, name) == 0) {//found match
while ( fgets ( buffer, sizeof ( buffer), fp)) {
if ( strstr ( buffer, "sex")) {//does the line contain sex
if ( ( sscanf ( buffer, " %*[^\"\n]\"%6[^;\"\n]", sex)) != 1) {//scan and discard up to a ", scan " and scan up to six characters to next "
return 1;//bad record
}
}
if ( strstr ( buffer, "age")) {//does the line contain age
if ( ( sscanf ( buffer, " %*[^=\n]=%d", age)) != 1) {// scan and discard up to an =, scan = and scan an integer
return 1;//bad record
}
}
if ( strstr ( buffer, "};")) {//does the line contain };
break;//found end of record
}
}
return 0;//found the matching name
}
else {//did not match. read the remaining lines of record
while ( fgets ( buffer, sizeof ( buffer), fp)) {
if ( strstr ( buffer, "};")) {//does the line contain };
break;//found end of record
}
}
}
}
fclose ( fp);
return 1;//match not found
}

int main()
{
char name[30] = {0};
char sex[7] = {0};
int age = 0;

strcpy ( name, "stephan");
if ( ( check_person_data ( name, &age, sex)) == 0) {
printf ( "name %s age %d sex %s\n", name, age, sex);
}
else {
printf ( "%s not found\n", name);
}
return 0;
}

关于c - 如何从数据数组的结构中搜索特定结构并使用 fread 读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30462559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com