Re: Parsing a File in C
Posted: Fri Jul 25, 2008 1:58 am
Hi Omega,
I'll skip on the "close to final, allowed to be obscure" part.
Your description sheds some light on your code. So, your algorithm is:
Here's my replacement suggestion.
As an alternative (and if your code needn't be reentrant), you might want to look into strtok() which can give you real tokenizing of an input string. The code above is still awfully sensitive to user typos (i.e., when a user types a space too much and the -s value doesn't fit the 7 bytes you reserved for that).
I'll skip on the "close to final, allowed to be obscure" part.
Your description sheds some light on your code. So, your algorithm is:
- For each character in the input buffer:
- if that character is a newline:
- read into 'line' the next complete line from input buffer
- read into uninitialized buffer 'file' from line[0] to three characters beyond the first ".", or the first two characters if no "." is found.
- read into uninitialized buffer 'pada' the first seven characters beyond the first "-s", or line[1] to line[8] if no "-s" is found.
- read into uninitialized buffer 'padb' the first seven characters beyond the first "-e", or line[1] to line[8] if no "-e" is found.
- print results.
- if that character is a newline:
Here's my replacement suggestion.
Code: Select all
size_t const MAXLINELENGTH = 256;
char line[MAXLINELENGTH];
char file[4]; // "\.(...)"
char pada[8]; // "-s(.......)"
char padb[8]; // "-e(.......)"
char * ptr;
// parse line-wise
while ( ( ptr = strchr( buf, '\n' ) ) != NULL )
{
line[0] = '\0'; // Input line
file[0] = '\0'; // What follows after '.'
pada[0] = '\0'; // What follows after "-s"
padb[0] = '\0'; // What follows after "-e"
// get the current input line
assert( ( ptr - buf ) < MAXLINELENGTH ); // handle too-long input lines here
strncat( line, buf, ptr - buf );
// move buf to after newline so we can "recycle" ptr...
buf = ptr + 1;
if ( ( ptr = strchr( line, '.' ) ) != NULL )
{
strncat( file, ptr, 3 );
}
if ( ( ptr = strstr( line, '-s' ) ) != NULL )
{
strncat( pada, ptr, 7 );
}
if ( ( ptr = strstr( line, '-e' ) ) != NULL )
{
strncat( padb, ptr, 7 );
}
// print result
}