I am trying to parse a txt file which contains names in the format:
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH",...
This is the code I wrote:
#include <stdio.h>
// Names scores
int problem22() {
FILE *f = fopen("names.txt", "r");
char name[100];
fscanf(f, "\"%[^\"]s", name);
printf("%s\n", name); // MARY
fscanf(f, "\"%[^\"]s", name);
printf("%s\n", name); // ,
fscanf(f, "\"%[^\"]s", name);
printf("%s\n", name); // PATRICIA
return 0;
}
int main() {
problem22();
return 0;
}
Each alternate call to fscanf
gives me a name, while the other is wasted in fetching a comma. I've tried several formats, but I can't figure out how to do it.
Can anyone help me with the correct format?
[Google Dictionary]File parsing in computer language means to give a meaning to the characters of a text file as per the formal grammar.
How to open a TXT file. You can open a TXT file with any text editor and most popular web browsers. In Windows, you can open a TXT file with Microsoft Notepad or Microsoft WordPad, both of which come included with Windows.
Changing the input format string to "%*[,\"]%[^\"]"
would do what you want:
fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // MARY
fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // PATRICIA
fscanf(f, "%*[,\"]%[^\"]", name);
printf("%s\n", name); // LINDA
The %*
just skips the matching input.
I always like to use strtok()
or strtok_r()
function to parse a file. (either prefer to use some csv library).
But just for fun I written a code may be you like it, I am not posting code in my answer but check @codepad for output, Works for specific format only.
The correct approach looks to me is something like below:
int main(){
// while(fp, csv, sizeof(csv)){
// First read into a part of file into buffer
char csv[] = "\"MARY\",\"PATRICIA\",\"LINDA\",\"BARBARA\",\"ELIZABETH\"";
char *name = "",
*parse = csv;
while(name = strtok(parse, "\",")){
printf(" %s\n", name);
parse = NULL;
}
return 0;
} // end while
Check codepade for output:
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
What I suggest in second code draw a outer loop to read lines from file to a temporary buffer then apply strtok() code like above something like: while(fgets(fp, csv, sizeof(csv))){ use strtok code}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With