sandpaperman335
sandpaperman335

Reputation: 21

How do I return a whole line from a .txt by searching for a string contained in that same line?

So i have to write a function that reads a file (.txt) and searches for a specific string, and then make it return the whole line that the string was on.

For example, one line is composed by student number, name, date of birth, address and course. I need to search for a name, and i need it to return the whole line, containing number, name, etc.

Ex :

Input : Search for student name : HUGO

Output :

61892 HUGOABC 12-02-2001 Address123 ETD

81029 HUGOBCA 09-09-2000 Address123 EAC

Here's my code :

fp = fopen("database_Alunos.txt", "r+");

if (fp == NULL) {
    printf("Error! File is NULL...");
    system("pause");

    main();
}
else {
    char nome[50];

    printf("Choose name to search : ");
    scanf("%[^\n]s", &nome);

    /* ??? */

    fclose(fp);
    system("pause");
    main();

fp is a FILE *fp, declared on top of main();

I need to know what kind of functions I can use in the space in the code with the question marks to make it scan for 'nome' and return the whole line

Upvotes: 0

Views: 280

Answers (2)

snaipeberry
snaipeberry

Reputation: 1059

You'll need to loop through a getline using your fp, then you can use for example strstr to check if the name is present in this string. Note that you'll have to handle the case when the name is present in the address.

char *line = NULL;
size_t len = 0;
ssize_t read;

while ((read = getline(&line, &len, fp)) != -1) {
    if (strstr(line, nome) != NULL) {
        printf("%s\n", line);
    }
}

Upvotes: 2

Hugo Cardoso Bessa
Hugo Cardoso Bessa

Reputation: 11

Ok i figured it out, this is a function to read the line

int readline(char *buff, int len, FILE *fp) {
buff[0] = '\0';
buff[len - 1] = '\0';
char *tmp;

if (fgets(buff, len, fp) == NULL) {
    *buff = '\0';
    return 0;
}
else {
    if ((tmp = strrchr(buff, '\n')) != NULL) {
        *tmp = '\0';
    }
}
return 1;

}

Func to read name and return lines :

scanf("%[^\n]s", fgets(nome, sizeof(nome), stdin));

        char line[1024];

        while (readline(line, 1024, fp)) {
            char *aux = strdup(line);

            char *numero = strtok(aux, "\t");
            char *nomeAluno = strtok(NULL, "\t");

            if (strstr(nomeAluno, nome) != NULL) {
                printf("%s\n", line);
            }
        }

    }

Upvotes: 1

Related Questions