我的文字文件如下所示,
Person.txt
John
{
sex = "Male";
age = 23;
};
Sara
{
sex = "Female";
age = 23;
};
stephan
{
sex = "Male";
age = 25;
};
我想根据请求获取特定人员的数据。对于Instance,我收到了获取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);
}
我做了两次,一次搜索字符串,另一次搜索结构。这是正确的做法还是其他更好的方式?
答案 0 :(得分:1)
该示例似乎是一个可以使用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;
}
答案 1 :(得分:0)
fread(&person, sizeof(struct personS), 1, fp);
此人现在是您文件中的数据副本,当您需要更改文件数据时,您只能更改副本,您需要fwrite(..)
您已更改的新数据