从文件中搜索字符串,并使用c将其存储在struct中 [英] search string from file and store it in struct using c
问题描述
我的结构如下:
struct profile {
char firstName[15], lastName[15];
int age, phoneNo;
};
并且我已经编写了一个代码来将来自此结构的文本数据存储到文本文件中,就像这样:
and i've written a code to store the text data from this structure into a text file, like so:
int main()
{
FILE* fPtr;
fPtr = fopen("profile.txt", "a");
printf("\n\nPlease enter your details:");
struct profile c;
printf("\n\nEnter your first name: ");
gets(c.firstName);
printf("\nEnter your last name: ");
gets(c.lastName);
printf("\nEnter your age: ");
scanf("%d", &c.age);
printf("Enter your phone number: ");
scanf("%d", &c.phoneNo);
fprintf(fPtr, "%s#%s#%dy#%d#\n", c.firstName, c.lastName, c.age, c.phoneNo);
fclose(fPtr);
return 0;
}
上面的代码会将输入到结构中的数据存储到一个字符串文本文件中,每个字符串是一个配置文件,并且每个值都由一个'#'分隔,如下所示:
the code above will store the data input into the struct into a text file of strings, each string is one profile, and each value is separated by a '#', like below:
John#Doe#35y#0123456789#
Mary Ann#Brown#20y#034352421#
Nicholas#McDonald#15y#0987654321#
我想知道是否可以通过某种方式从文本文件中搜索特定的姓名/年龄/电话号码,选择相应配置文件的整个字符串,然后将每个值放回上述结构中,以便我可以显示吗?我已经用'#'分隔了每个值,以便程序从文件读取时可以使用#区分每个值,但是我不确定在读取数据时如何分隔它.我应该使用 fgets
吗?我是C的新手,所以如果有人可以向我解释它,我将不胜感激.
i'd like to know if there's a way i can search for a certain name/age/phoneNo from the text file, select the entire string of the corresponding profile and put each value back into a structure as above so that i can display it? i've separate each value with a '#' so that the program can use the # to differentiate between each value when it reads from the file but i'm not sure how i can separate it when i read the data. should i use fgets
? i'm new to C so i'd appreciate it if someone could explain it me how.
推荐答案
这并不是您要查找的内容,但是它可以帮助您开始使用 fgets
以及如何搜索条目(仅字符串)现在).
This is not exactly what you are looking for , but it helps you start using fgets
and how to search for entries(only strings now).
#include <stdio.h>
#include <string.h>
#define MYFILE "profile.txt"
#define BUFFER_SIZE 50
int main()
{
char nametoSearch[BUFFER_SIZE];
char Names[BUFFER_SIZE];
FILE* fPtr;
if (fPtr = fopen(MYFILE, "r"))
{
// flag to check whether record found or not
int fountRecord = 0;
printf("Enter name to search : ");
//use fgets if you are reading input with spaces like John Doe
fgets(nametoSearch, BUFFER_SIZE, stdin);
//remove the '\n' at the end of string
nametoSearch[strlen(nametoSearch)-1] = '\0';
while (fgets(Names, BUFFER_SIZE, fPtr))
{
// strstr returns start address of substring in case if present
if(strstr(Names,nametoSearch))
{
printf("%s\n", Names);
fountRecord = 1;
}
}
if ( !fountRecord )
printf("%s cannot be found\n",nametoSearch);
fclose(fPtr);
}
else
{
printf("file %s cannot be opened\n", MYFILE );
}
return 0;
}
这篇关于从文件中搜索字符串,并使用c将其存储在struct中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!