cerca una stringa dal file e memorizzala in struct usando c

Oct 18 2020

ho una struttura così:

struct profile {
    char firstName[15], lastName[15];
    int age, phoneNo;
};

e ho scritto un codice per memorizzare i dati di testo da questa struttura in un file di testo, in questo modo:

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

il codice sopra memorizzerà l'input dei dati nella struttura in un file di testo di stringhe, ogni stringa è un profilo e ogni valore è separato da un '#', come di seguito:

John#Doe#35y#0123456789#
Mary Ann#Brown#20y#034352421#
Nicholas#McDonald#15y#0987654321#

mi piacerebbe sapere se c'è un modo per cercare un certo nome / età / telefonoNo dal file di testo, selezionare l'intera stringa del profilo corrispondente e rimettere ogni valore in una struttura come sopra in modo da poterlo visualizzare ? Ho separato ogni valore con un "#" in modo che il programma possa utilizzare # per differenziare ogni valore quando legge dal file, ma non sono sicuro di come separarlo quando leggo i dati. dovrei usare fgets? sono nuovo in C quindi apprezzerei se qualcuno mi spiegasse come.

Risposte

1 IrAM Oct 19 2020 at 06:51

Questo non è esattamente quello che stai cercando, ma ti aiuta a iniziare a usare fgetse come cercare le voci (solo stringhe ora).

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