[ale] Stupid C Question
Tom Wiencko
tew at wiencko.com
Wed Mar 21 23:09:57 EST 2001
What a fun little problem. Least effort is to find the fields in
the buffer, and build pointers to them. This is C after all, and C
is a pointer hacker's heaven. Here's one way to do it:
#include <stdio.h>
#define INFILE "test.cfg"
#define MAXBUF 1024 /* max buffer length */
#define MAXFIELDS 1024 /* memory is cheap */
#define DELIMETER ':'
parse (char delim, char *in, char ** ptrs)
{
register char *inptr=in;
register delimfound=1; /* beginning of line is always a delimeter */
register count=0;
while (*in != '\0') {
if (*in == delim) {
*in='\0';
delimfound=1;
} else
if (delimfound) {
/* current char is good, last was delimeter */
*ptrs++ = in;
delimfound=0;
count++;
}
in++;
}
return (count);
}
int main(char *ac, char ** av) {
char buffer[MAXBUF];
char *pointers[MAXFIELDS];
FILE * f;
int i, count;
if (NULL != ( f=fopen(INFILE, "r") ) ) {
while (EOF != (fscanf(f, "%s", buffer) ) ) {
count=parse(DELIMETER, buffer, pointers);
/* array "pointers" is now an array of pointers to the fields */
/* let's print 'em out and make sure it works */
printf ("%d fields found\n",count);
for (i=0; i<count; i++) {
printf("field is |%s|\n", pointers[i]);
}
printf ("new line\n");
}
} else {
printf ("cannot open file!\n");
}
}
Of course, since this is C, there are billions of other ways to do it
as well.
Tom
Chris Fowler wrote:
>
> I have a file that looks like this
>
> DATA:DATA:DATA
> DATA:DATA:DATA
>
> Each line is a new record and the DATA of each one can be of variable
> length. I have tried to read the whole file in buffer and use sscanf
> to parse but that seems to yield no results. I want to place each
> piece of DATA into character arrays. The number of records in the
> file could be variable as well. Any help on this would be greatly
> appreciate. If you could point me to good documentation on reading,
> writing, parsing, and changing of disks files using C, I would
> appreciate that to. I have many books on C but non really explain how
> to work with files. Most of my files are config files that I am
> trying to create an interface to change them.
>
> Thanks,
> Chris
--
------------------------------------------------------------------------
Tom Wiencko tew at wiencko.com
President - Wiencko & Associates, Inc. (404) 255-2330
Telecom Consulting & Project Development -- Wireline, Wireless, Internet
--
To unsubscribe: mail majordomo at ale.org with "unsubscribe ale" in message body.
More information about the Ale
mailing list