agupta2
September 26, 2011, 1:37pm
1
I was trying to parse the text file, which will looks like this
###XYZABC ####
############
int = 4
char = 1
float = 1
.
.
############
like this my text file will contains lots of entries and I need to store these entries in the map eg. map.first = int and map.second = 4 same way I will keep on inserting other elements into this
Anybody can help me on this.
Thanks in advance!!!
Why C++ when this can be done using awk or perl...much simpler especially if this is a one off thing.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char buf[512];
FILE *fp=fopen("file.txt", "r");
if(fp == NULL)
{
fprintf(stderr, "Couldn't open file.txt\n");
return(1);
}
while(fgets(buf, 512, fp))
{
char *str=buf;
char name[512], val[512];
// Ignore whitespace at the beginning
while(isspace(*str)) str++;
// Ignore blank lines, comments
if(((*str) == '\0') || ((*str) == '#') continue;
// %[^= ] means string with no spaces or = chars.
// then scanf expects a literal " = ", spaces optional.
// lastly, %[^ \n] is a string with no spaces or newlines.
// It returns '2' when it has found both strings and the = between.
if(sscanf(str, "%[^= ] = %[^ \n]", name, val) == 2)
{
printf("Found value line, %s = %s\n", name, val);
}
}
fclose(fp);
}
NH2
September 26, 2011, 4:29pm
4
If you really want to learn how write parser in C++ efficiently, then spend time with boost::spirit . The learning curve is steep at the beginning, but then the ROI is great
/Lew
"Boost" is overkill for something that's accomplished with 3 libc calls, 5 if you count fopen/fclose...