Hi,
I am writing a simple file parser for use in another project (for config file). The trickiest thing seems to be skipping unwanted characters (comments, spaces). It works partly, but after the second line of an inputed file processes only the first three characters.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEXT_FILE "data.txt"
int check_char(char *str, int *pos);
int main()
{
char buffer[1000];
char buffer2[1000];
int position = 0;
int base = 0;
FILE *file_ptr = fopen(TEXT_FILE, "r");
if( file_ptr == NULL ) {
perror(TEXT_FILE);
exit(1);
}
memset(buffer, '\0', sizeof(buffer));
memset(buffer2, '\0', sizeof(buffer2));
while( fgets(buffer, sizeof(buffer), file_ptr) ) {
base = 0;
position = 0;
printf("Data read: %s\n", buffer);
while( check_char(&buffer[position], &position) ) {
buffer2[base] = buffer[position];
position++;
base++;
}
buffer2[position] = 0;
printf("Contents: %s\n", buffer2);
memset(buffer, '\0', sizeof(buffer));
memset(buffer2, '\0', sizeof(buffer2));
}
fclose(file_ptr);
return 0;
}
int check_char(char *str, int *pos)
{
char ch = str[*pos];
switch( ch ) {
case '#':
while( ch != '\n' )
{
*pos = *pos + 1;
ch = str[*pos];
if( ch == '\0' || ch == EOF )
return 0;
printf("%c\n", str[*pos]);
}
return 1;
break;
case ' ':
printf("Space\n");
*pos = *pos + 1;
return 1;
break;
case '\0':
case EOF:
printf("NULL or EOF\n");
return 0;
break;
default:
printf("OK\n");
return 1;
}
}
NOTE: Currently I am just trying to process and remove unwanted data, the actual processing of extracted data should be much simpler.