Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a txt file

Tags:

c

parsing

scanf

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?

like image 541
xylon97 Avatar asked Oct 11 '13 06:10

xylon97


People also ask

What is parsing a text file?

[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 do I read a .TXT file?

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.


2 Answers

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.

like image 199
3 revs Avatar answered Oct 04 '22 13:10

3 revs


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.

Using strtok()

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}

like image 40
Grijesh Chauhan Avatar answered Oct 04 '22 14:10

Grijesh Chauhan