user1430471
user1430471

Reputation: 9

How can I read a full string between a two double quote mark from a file in C

I need a C program to read a string within double quotes from a file and store them. File is not fixed, means it may be changing, but would be having data like:

MY_NAME( tra_ctrl_1, "T_aa1")
MY_NAME( tra_ctrl_2, "A_bb1")
MY_NAME( tra_ctrl_3, "C_x")
MY_NAME( tra_ctrl_4, "M_cc1")
MY_NAME( tra_ctrl_5, "xx")
MY_NAME( tra_ctrl_6, "yy")
............ and so on..

I want to store T_aa1, A_bb1, C_x, M_cc1, xx and yy after reading lines of file.

Upvotes: 0

Views: 2348

Answers (5)

BLUEPIXY
BLUEPIXY

Reputation: 40145

Only a simple method by strchr

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


int main() {
    FILE *fp;
    char buff[1024];
    char str[128];

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

    while (NULL!=fgets(buff, sizeof(buff), fp)){
        char *pf,*pb;
        int len;
        pf=strchr(buff, '\"');
        pb=strchr(pf+1, '\"');
        len = pb - pf - 1;
        memcpy(str, pf + 1, len);
        str[len]='\0';
        printf("%s\n", str);
    }
    fclose(fp);
    return 0;
}

Upvotes: 0

BLUEPIXY
BLUEPIXY

Reputation: 40145

Only a simple method by scanf

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


int main() {
    FILE *fp;
    char buff[1024];
    char str[128];

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

    while (NULL!=fgets(buff, sizeof(buff), fp)){
        sscanf(buff, "%*[^\"]%*c%[^\"]%*c%*[^\n]%*c", str);
        printf("%s\n", str);
    }
    fclose(fp);
    return 0;
}
/*
T_aa1
A_bb1
C_x
M_cc1
xx
yy
*/

Upvotes: 1

Anshul
Anshul

Reputation: 776

You could use it using the strtok() function by converting the " " into keys and making a conditional code to use the expression inside it (strings) for further purpose.

Upvotes: 0

selbie
selbie

Reputation: 104559

1) Manually write a parser. I'm assuming you'll either have the entire file in memory or at least and entire line. In which case, strtok() is good enough for simple parsing operations. Should be easy enough.

2) Use lex and yacc (or flex and bison) to generate a parser for you. You likely only need (f)lex.

Upvotes: 0

aleroot
aleroot

Reputation: 72646

You could use a regular expresion .

Upvotes: 2

Related Questions