Home > Enterprise >  How do I get specific names from a text file with a location as condition?
How do I get specific names from a text file with a location as condition?

Time:10-07

Please help me. I'm new to programming. I've been trying and searching for days to answer this.

I need a C program that will open a text file named users.txt

In that text file there are names then comma and their schools.

John Paul, Legit Univ
Paul John, Yo Univ
Lebron James, School Univ
James Lebron, Legit Univ

All I managed so far is to display them all. The output should be all the users that are from "Legit Univ".

Sample output:

Found 2 users from Legit Univ

John Paul
James Lebron

CodePudding user response:

Use fgets() to read a line from file into a string, then strchr() to to find the position of the comma ',' field separator in the string (or strstr() if the field separator is comma space ", "). Now you can check the part of the string after the field separator for a match on your query with strcmp(). Instead of parsing the file, you could also use a regex and match against the string.

CodePudding user response:

Another approach would be to load one line at a time (as you are doing). Then, search the buffer for the target string (like "Legit Univ") using strstr(). If found, then go about trimming at the comma (perhaps strtok() and outputting the name ( puts() ). If not found, move on to the next record (input line).

Don't do more processing than you have to.

The "Found 2 users at Legit Univ" is a bit of a problem, though. Either you can buffer up the names in a linked-list while counting 'hits', OR you could change the output to print the count of 'hits' AFTER the report of the names. (Or, worse, you could process the file once to count, rewind, then output the count AHEAD of the 'user' names...) How stringent are the requirements of the output?

  • Related