0

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.

1
  • Do they follow C conventions so a string could be something like: "A string with\" a quote in it"? If so, the job may be a bit more difficult than it would initially appear. Commented Jun 4, 2012 at 6:00

5 Answers 5

2

You could use a regular expresion .

Sign up to request clarification or add additional context in comments.

Comments

1

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 */ 

Comments

0

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.

Comments

0

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.

Comments

0

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.