/* Compile with: gcc -o commenteraser main.c if you want to use the debug mode, compile with -D_DEBUG */ #include #include #include void printHelp( char* prog ); void checkFile( FILE* fStream, char* filename ); void eraseComment( char* filename, size_t uiCommentBytes, size_t ulCommentOffset ); int main( int argc, char *argv[] ) { FILE* fsCurFile = NULL; if( argc < 2 ) { printHelp( *argv ); } while( *(++argv) ) { fsCurFile = fopen( *argv, "r+" ); if( fsCurFile == NULL ) { printf( "[ERROR] %s: file not found\n", *argv ); continue; } else { printf( "File %s opened..\n", *argv ); checkFile( fsCurFile, *argv ); fclose( fsCurFile ); printf( "File %s cleared of comments..\n", *argv ); } } return EXIT_SUCCESS; } void printHelp( char* prog ) { printf( "usage: %s ,..", prog ); return; } void checkFile( FILE* fStream, char* filename ) { char curChar = 0; char lastChar = 0; int commentStarted = 0; int iCnt = 0; size_t uiCommentBytes = 1; size_t ulCommentOffset = 0; while( ( curChar = fgetc( fStream ) ) != EOF ) { if( lastChar == '/' && curChar == '/' ) { # if defined _DEBUG printf( "\nComment found at byte %d\n", ulCommentOffset ); # endif commentStarted = 1; } if( lastChar == '\n' && commentStarted == 1 ) { commentStarted = 0; printf("erasing content from %d to %d\n", ulCommentOffset, ulCommentOffset+uiCommentBytes ); eraseComment( filename, uiCommentBytes, ulCommentOffset ); // We couldn't continue count, because we had lost the comment beginning //ulCommentOffset += uiCommentBytes; fseek( fStream, ulCommentOffset, SEEK_SET ); uiCommentBytes = 1; } if( commentStarted == 0 && curChar != '/' ) { # if defined _DEBUG printf("Offset: %x(%c)\n", curChar, curChar ); # endif ++ulCommentOffset; } else if( commentStarted == 1 ) { # if defined _DEBUG printf("Byte: %x(%c)\n", curChar, curChar ); # endif ++uiCommentBytes; } lastChar = curChar; } return; } void eraseComment( char* filename, size_t uiCommentBytes, size_t ulCommentOffset ) { int iVal = 0x90; size_t iCnt = 0; FILE* fStream = fopen( filename, "r+" ); # if defined _DEBUG printf( "deleting %d bytes\n", uiCommentBytes ); # endif for( iCnt = 0; iCnt != uiCommentBytes; iCnt++ ) { fseek( fStream, ulCommentOffset+iCnt, SEEK_SET ); fwrite( &iVal, 1, 1, fStream ); } iVal = 0x0D; fwrite( &iVal, 1, 1, fStream ); fclose( fStream ); return; }