0

I have a dynamically updated text file with names of people, I want to parse the file to extract "Caleb" and the string that follows his name. However, his name may not always be in the list and I want to account for that.

I could do it in Java, but not even sure what to do in C. I could start by reading in the text file line by line, but then how would I check if "Caleb" is a substring of the string I just read in and handle the case when he isn't? I want to do this without using external libraries - what would be the best method?

Barnabas: Followed by a string
Bart: Followed by a string
Becky: Followed by a string
Bellatrix: Followed by a string
Belle: Followed by a string
Caleb: I want this string
Benjamin: Followed by a string
Beowul: Followed by a string
Brady: Followed by a string
Brick: Followed by a string

returns: "Caleb: I want this string" or "Name not found"
CISSflow
  • 89
  • 5

2 Answers2

1

but then how would I check if "Caleb" is a substring of the string

The heart of the question as I read it. strstr does the job.

char *matchloc;
if ((matchloc = strstr(line, "Caleb:")) {
    // You have a match. Code here.
}

However in this particular case you really want starts with Caleb, so we do better with strncmp:

if (!strncmp(line, "Caleb:", 6)) {
    // You have a match. Code here.
}
Joshua
  • 40,822
  • 8
  • 72
  • 132
0

So if you want to check if the user caleb exists, you can simple made a strstr, with your array of strings, and if exists you can make a strtok, to get only the string!

I dont know how you are opening the file, but you can use getline to get line by line!

You can do something like this:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(){

FILE *file;
char *fich="FILE.TXT";
char *line = NULL;
char *StringFile[100];
size_t len = 0;
ssize_t stringLength;
const char s[2] = ":"; //Divide string for this
char *token;
int check =0;
char *matchloc;


file=fopen(fich, "r"); 
    if(file==NULL){
        fprintf(stderr, "[ERROR]: cannot open file <%s> ", fich);
        perror("");
        exit(1);
    }

while((stringLength = getline(&line, &len, file)) != -1){
    if(line[strlen(line)-1] == '\n'){
        line[strlen(line)-1] = '\0';  //Removing \n if exists
    }   

    if((matchloc = strstr(line, "Caleb:"))){
        check = 1;
        strcpy(*StringFile, line);
        token = strtok(*StringFile, s);

        while( token != NULL ) {
            token = strtok(NULL, s);
            printf("%s\n", token);
            break;
        }
        break;
    }
}

if(check==0){
       printf("Name not found\n");
} 

    return 0;
}

The code, can have some errors, but the idead is that! when founds the name, copy the line to array and the splits it.

Gonçalo Bastos
  • 376
  • 3
  • 16