c - 从文件中搜索字符串并使用 c 将其存储在结构中
问题描述
我有这样的结构:
struct profile {
char firstName[15], lastName[15];
int age, phoneNo;
};
我已经编写了一个代码来将此结构中的文本数据存储到一个文本文件中,如下所示:
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;
}
上面的代码会将输入到结构体的数据存储到一个字符串的文本文件中,每个字符串是一个配置文件,每个值都用'#'分隔,如下所示:
John#Doe#35y#0123456789#
Mary Ann#Brown#20y#034352421#
Nicholas#McDonald#15y#0987654321#
我想知道是否有一种方法可以从文本文件中搜索某个姓名/年龄/电话号码,选择相应配置文件的整个字符串并将每个值放回如上所述的结构中,以便我可以显示它? 我已经用“#”分隔每个值,以便程序在从文件中读取时可以使用 # 来区分每个值,但我不确定在读取数据时如何将其分开。我应该使用fgets
吗?我是 C 的新手,所以如果有人能解释一下,我将不胜感激。
解决方案
这并不完全是您正在寻找的内容,但它可以帮助您开始使用fgets
以及如何搜索条目(现在只有字符串)。
#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;
}
推荐阅读
- asp.net-core - “dotnet new angular”应用程序中的脚手架身份出现错误
- android - 在 API 30 中为 resolveActivity 写入清单的意图操作
- react-native - 如何在本机反应中使用嵌套导航堆栈
- kubernetes - 如何使用 index.html 中的自定义文本在 nginx 上创建部署?
- json - 我如何能够比较两组 JSON 数据并检查一组是否在另一组中
- javascript - Async/Await:推理与实现
- javascript - 如何在javascript中将特定格式的日期转换为yyyy-mm-dd格式
- machine-learning - 使用 ML 识别 windows 计算机名称
- reactjs - 如何让 Accordion 行颜色在两种颜色之间交替?
- npm - 如何使用纱线工作区运行两个开发服务器?