Peter said:
Sorry about that.
Maybe I should clarify it a bit. I'm trying to read a frequency table
in the format:
character space number newline
Unfortunatly the characters may be of the form "a", "\\n" or "\\x20"
The backslash is a backslash character and that's what makes it so
annoying.
Remarks: - It would have been nice to repeat your original request
which was "Is there a more elegant way to do it than the following?"
- It is considered better to post code without tabs.
Just replace the tabs by a decent (>=2) number of white spaces
before pasting it.
while (!feof(filePointer))
{
fgets(buffer, BUFFER_LENGTH, filePointer);
sscanf(buffer, "%s %s\n", smallbuffer, buffer);
if (smallbuffer[0] != '\\')
c = smallbuffer[0];
else
switch(smallbuffer[1])
{
case 'n':
c = '\n';
break;
case 't':
c = '\t';
break;
case 'v':
c = '\v';
break;
case 'b':
c = '\b';
break;
case 'r':
c = '\r';
break;
case 'f':
c = '\f';
break;
case 'a':
c = '\a';
break;
default:
/* Hex left out*/
break;
make this case 'x' and give an error as default.
}
addEntry(table, c, buffer, &pos, &size);
}
Leave the code as blunt as it is. Everything more elegant
probably gives you just a headache or is harder to maintain.
I would write a function with the prototype
int GetType(char *smallbuffer)
which essentially does what you want and hides the ugliness.
C99 gives you a nice alternative due to designated
initializers:
-----
#include <limits.h>
const char ctable[UCHAR_MAX] = {
['n'] = '\n';
['t'] = '\t';
.....
['a'] = '\a';
['x'] = 'x';
};
.....
if (smallbuffer[0] != '\\')
c = smallbuffer[0];
else {
if ( !(c = ctable[(unsigned char)smallbuffer[1]]) ) {
/* c==0: same as default above; error treatment */
} else if (c=='x') {
/* hex treatment */
}
}
-----
(untested but hopefully illustrates the point)
In C89, building the table leads effectively to the same
code you already have, so you gain not much in clarity
and pay with memory.
Note: I do not know how you do your hex treatment but
wanted to make you aware of strtoul() (unsigned long
instead of long in order to be on the safe side) called
with base 16.
Cheers
Michael