/* ios_s.c -- I/O service module for a sequence of input files */ #include #include #include #define ERR_OPEN_INPUT 10 #define ERR_OPEN_OUTPUT 10 #define ERR_LINE_SIZE 12 #define ERR_LINE_SYNTAX 13 #define ERR_LINE_MISSING 14 #define ERR_COMMAND_LINE 20 #define LINE_SIZE 102 static char Line_buffer [LINE_SIZE]; static FILE * infile; static FILE * outfile; static int input_files_count = 0; static int output_files_count = 0; static int input_lines_count; static void syntax_error ( void ); FILE * open_input_file ( char filename [] ) { if ( ++input_files_count > 1 ) fclose ( infile ); input_lines_count = 0; infile = fopen ( filename, "rt" ); if ( infile ) return ( infile ); printf ( "error when opening the %d-th input file \"%s\"\n", input_files_count, filename ); exit ( ERR_OPEN_INPUT ); } FILE * open_output_file ( char filename [] ) { if ( ++output_files_count > 1 ) fclose ( outfile ); outfile = fopen ( filename, "wt" ); if ( outfile ) return ( outfile ); printf ( "error when opening the %d-th output file \"%s\"\n", output_files_count, filename ); exit ( ERR_OPEN_OUTPUT ); } int get_line ( char ** start ) { char c; char * left; char * right; ++ input_lines_count; do { if ( NULL == fgets ( Line_buffer, LINE_SIZE, infile ) ) { * start = NULL; return (-1); } c = * ( left = & Line_buffer [0] ); while ( ( c != 0 ) && ( c != '[' ) && ( c != ']' ) ) c = * ++left; if ( c == '[' ) break; if ( c == ']' ) syntax_error (); while ( left > & Line_buffer [0] ) { c = * (left-1); if ( (signed char) c < 0 || ! isascii ( c ) || ! isspace ( c ) ) break; --left; } if ( left > & Line_buffer [0] ) syntax_error (); } while ( 1 ); c = * ( right = ++left ); while ( ( c != 0 ) && ( c != '[' ) && ( c != ']' ) ) c = * ++right; if ( right >= & Line_buffer [ LINE_SIZE - 1 ] ) { printf ( "line %d of the %d-th input file: line length exceeds %d\n", LINE_SIZE - 2 ); exit ( ERR_LINE_SIZE ); } if ( c != ']' ) syntax_error (); * right = 0; * start = left; return ( right - left ); } int get_line_sure ( char ** start ) { int n; n = get_line ( start ); if ( n >= 0 ) return (n); printf ( "missing line %d of the %d-th input file\n", input_lines_count, input_files_count ); exit ( ERR_LINE_MISSING ); } void err_command_line ( char usage [] ) { printf ( "usage: %s\n", usage ); exit ( ERR_COMMAND_LINE ); } static void syntax_error ( void ) { printf ( "line %d of the %d-th input file is not of the form [...]\n", input_lines_count, input_files_count ); exit ( ERR_LINE_SYNTAX ); } /* end of ios_s.c */