Nimit
Nimit

Reputation: 1712

Parsing specific formatted files in C

I want to parse a text file in a C program. The file contains data that is likely to be:

block1=
{
    a="some text with space and double quota"    
    b=random text    
    c=random text    
    d=random text    
    e=random text    
    f="number"    
    g=number    
}

block2=
    {
        a="some text with space and double quota"    
        b=random text    
        c=random text    
        d=random text    
        e=random text    
        f="number"    
        g=number    
    }

There may be n number of blocks, I want to create list of elements ("a" elements of each block) , for that what should I do? Is there any parsing API for text file in C?

Upvotes: 2

Views: 456

Answers (2)

theB
theB

Reputation: 2228

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

typedef struct block {
    char head[8];
    char braze[2];
    char a[46];
    char b[18];
    char c[18];
    char d[18];
    char e[18];
    char f[15];
    char g[13];
    char close_braze[2];
} block;

int main () {
    int i, ret;
    char a_elm[10][50];
    FILE *fp;
    block blk[10]; //use a specific number if you know. or go for linked list

    fp = fopen ("one.txt","r");

    for (i = 0; i < 11; i++) {
        ret = fread ((void *) &blk[i], sizeof (block), 1, fp);
        if (!ret)
            break;
    }
    fclose (fp);    

    for (ret = i, i = 0; i < ret; i++) {
        strncpy (a_elm[i], blk[i].a, 46);
        a_elm[i][46] = '\0';
        printf ("%s\n", a_elm[i]);
    }

    return 0;
}

For fixed format code, fread can be used as above or you have to use fscanf with some string functions.

Upvotes: 0

theB
theB

Reputation: 2228

I don't know whether there is such an API or not in C. But I think you can do it yourself with little code.

create a struct having elements as a block (having a, b, c, d, e, f, as string and g as int). Have an array of that struct. And have a string array. Read the file using fread till end of file. After store all the "a" element of each element of the struct array in the string array.

If you want specific code, give me a sample text file you described. I'll write the code and post for you.

Upvotes: 1

Related Questions