#include
#define output(s) fprintf( yyout, "%c", (s))
#define ECHO fwrite( yytext, yyleng, 1, yyout )
int tabcnt;
int TAB;
%}
%%
int i, column = 0, space = 0, tail, start, end;
[ \t]*\n {
output( '\n' );
column = space = 0;
}
[ \t]+ {
for ( i = 0, tail = column; i < yyleng; i++ ) {
if( yytext[i] == ' ' )
tail++;
else /*' \t'*/
tail = ( tail / TAB + 1 ) * TAB;
}
if ( column + 1 == tail ) {
output( ' ' );
column++;
} else {
start = column / TAB;
end = tail / TAB;
if ( start != end ) {
for( i = start; i < end; i++ )
output( '\t' );
tabcnt += end - start;
column = end * TAB;
}
}
space = tail - column;
}
[^ \t\n]+ {
for( i = 0; i < space; i++ )
output( ' ' );
ECHO;
column += space + yyleng;
space = 0;
}
%%
//------------------------------------------------
main( int argc, char **argv ) {
int i, file;
FILE *out_file_open(), *in_file_open();
if( checkArgs( argc, argv, &TAB, &file ) != 0 ) {
fprintf( stderr, "Usage:spc2tab [-4|-8] inp-file out-file\n" );
exit(1);
}
if( in_file_open( argv[file] ) != NULL ) {
if( out_file_open( argv[file+1] ) == NULL )
exit(1);
tabcnt = 0;
fprintf( stderr, "%s : ", argv[file+1]);
yylex();
fclose(yyin);
fclose(yyout);
fprintf( stderr, "%d tabs put.\n", tabcnt );
}
}
//------------------------------------------------
checkArgs( int argc, char **argv, int *TAB, int *file ) {
if( argc != 3 && argc != 4 )
return 1;
if( strncmp( argv[argc-1], "-", 1 ) == 0 )
return 1;
*TAB = 4;
*file = 1;
if( strcmp( argv[1], "-8" ) == 0 ) {
if ( argc != 4 )
return 1;
*TAB = 8;
*file = 2;
} else if( strcmp(argv[1], "-4" ) == 0 ) {
if ( argc != 4 )
return 1;
*TAB = 4;
*file = 2;
} else if ( argc == 4 )
return 1;
return 0;
}
//------------------------------------------------
FILE out_file_open( char *filename ) {
if( ( yyout = fopen( filename, "w" ) ) == NULL )
fprintf( stderr, "%s file system full. \n", getcwd( ( char )NULL, 256 ) );
return( yyout );
}
//------------------------------------------------
FILE *in_file_open( char *filename ) {
if( ( yyin = fopen( filename, "r" ) ) == NULL )
fprintf( stderr, "%s:NO such file or directry. \n", filename );
return( yyin );
}