Re: Reading a table



On Tue, 27 Nov 2007 02:19:55 GMT, "Bill Reid" wrote:
Anyway...

#include <stdio.h>
#include <stdlib.h>

#define LINEMAX 512

extern unsigned
assign_text_file_line_fields
(char *,unsigned (*)(unsigned,char *,void *),void *);

static FILE *text_file;

static char text_line[LINEMAX];

/* assigns field values from text file lines using callback function */
unsigned assign_text_file_line_fields
(char *text_file_path,
unsigned assign_func(unsigned,char *,void *),void *assign_ptr) {
unsigned line_num=0;
ret_val=FALSE;

/* try to open text file, return if failure */
if((text_file=fopen(text_file_path,"rt"))==NULL) {
printf("\nERROR: Could not open text file\n%s",
text_file_path);
goto EXIT_FUNCTION;
}

/* get every line in file, pass to callback function */
while((fgets(text_line,LINEMAX,text_file))!=NULL) {

if(!assign_func(line_num,text_line,assign_ptr)) {
printf("ERROR: Could not assign line %d fields);
goto CLOSE_TEXT_FILE;
}

line_num++;
}

/* OK, looks like we've succeeded */
ret_val=TRUE;

/* try to close file, warn if failure */
CLOSE_TEXT_FILE :
if((fclose(db_init_file))==EOF)
printf("\nWARNING: Problem closing text file\n%s",
text_file_path);

/* buh-bye */
EXIT_FUNCTION :
return ret_val;
}

Your callback solution has its merits. But you could have done it

- without gotos
- whithout static FILE
- for arbitrary long lines (no hard-coded maximum line lenght)
- with a typedef for the callback function for better readability
- with an explanation for "rt" instead of "r"
- returning error codes instead of using printfs
- with self-explanatory names e.g. process_file_by_line (insted of
assign_text_file_line_fields), process_line (instead of assign_func),
data or context (instead of assign_ptr)



--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
.