H
Hugh
Hello,
I am having some problems understanding (most likely), parsing a text
file. I would like to parse a file like:
block1 {
stuff;
...
stuffN;
};
Just like in BIND config. (Silly project but important to me)
I would not like to use string.h functions such as strstr(), strtok()
(maybe make use of strncpy, strncat if I have to though..).
You will all probably balk at my general logic when looking at the
code, so perhaps someone might suggest a better methodology for parsing
files? (apart from lex/yacc).
I have the following code, but it doesn't seem to get out of the first
block. Would anyone mind sifting through the rubbish code and helping
me out? (i'll post at bottom of this post).
Thanks a million, 2 virtual pints of guinness for you all!
Hugh.
------ begin code -------
#include <stdio.h>
#define MAX 512
int main(int argc, char **argv)
{
int i,j,ctr,in_block=0;
char line[MAX];
FILE *fp;
if((fp=fopen(argv[1],"r+")) == NULL) {
fprintf(stderr,"Unable to open %s\n",argv[1]);
exit(-1);
}
while(fgets(line,MAX,fp) != NULL) {
for(i=0;i<=MAX;i++) {
if(line == '\0' || line == '#') {
i++;
continue;
}
if(line == '{') {
in_block=1;
printf("Entering block\n");
j=i;
ctr++;
while(line[j] != '}') {
if(line[j] == '\0' || line[j] =='#')
continue;
printf("--> within block\n");
j++;
} in_block=0;
i += (j-i);
printf("Leaving block\n\n");
}
}
}
return 0;
}
------- end code --------
I am having some problems understanding (most likely), parsing a text
file. I would like to parse a file like:
block1 {
stuff;
...
stuffN;
};
Just like in BIND config. (Silly project but important to me)
I would not like to use string.h functions such as strstr(), strtok()
(maybe make use of strncpy, strncat if I have to though..).
You will all probably balk at my general logic when looking at the
code, so perhaps someone might suggest a better methodology for parsing
files? (apart from lex/yacc).
I have the following code, but it doesn't seem to get out of the first
block. Would anyone mind sifting through the rubbish code and helping
me out? (i'll post at bottom of this post).
Thanks a million, 2 virtual pints of guinness for you all!
Hugh.
------ begin code -------
#include <stdio.h>
#define MAX 512
int main(int argc, char **argv)
{
int i,j,ctr,in_block=0;
char line[MAX];
FILE *fp;
if((fp=fopen(argv[1],"r+")) == NULL) {
fprintf(stderr,"Unable to open %s\n",argv[1]);
exit(-1);
}
while(fgets(line,MAX,fp) != NULL) {
for(i=0;i<=MAX;i++) {
if(line == '\0' || line == '#') {
i++;
continue;
}
if(line == '{') {
in_block=1;
printf("Entering block\n");
j=i;
ctr++;
while(line[j] != '}') {
if(line[j] == '\0' || line[j] =='#')
continue;
printf("--> within block\n");
j++;
} in_block=0;
i += (j-i);
printf("Leaving block\n\n");
}
}
}
return 0;
}
------- end code --------