首页 > 解决方案 > 从文件中搜索字符串并使用 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 的新手,所以如果有人能解释一下,我将不胜感激。

标签: cstructtext-filesstructurefgets

解决方案


这并不完全是您正在寻找的内容,但它可以帮助您开始使用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;
}

推荐阅读