/* * manipulate_hosts.c * * author: Patrick Neumann * version: 1.0 (02.11.2010) * * compile under (with): * - linux (http://gcc.gnu.org/) * - windows (http://www.mingw.org/) * - mac os x (work-in-progress) * * quick start guide: * 1. ping "www.microsoft.com" before * 2. run program * 3. ping "www.microsoft.com" afterwards * 4. compare outputs * 5. execute the program again * 6. now everything should be the same as before * * HINT: is not working on windows anymore because * the anti virus tools from today detect that kind of modification! * */ #include #include #include // needed for the functions "strcpy", "strcat" und "strstr" #define LINELENGTH 80 #ifdef __unix__ #include // needed for the function "access" #define WRITE W_OK #else #include // needed for the function "access" #define WRITE 02 #endif int main(void) { #ifdef __unix__ char oldfile[50] = "/etc/"; #else char oldfile[50] = "C:\\WINDOWS\\system32\\drivers\\etc\\"; #endif char newfile[50]; strcpy( newfile, oldfile ); strcat( oldfile, "hosts" ); strcat( newfile, "newhosts" ); char newline[50] = "149.20.20.133 www.microsoft.com"; FILE *quelle, *ziel; char puffer[ LINELENGTH ]; int counter = 0; // check if the source could be opened and be written (for the later "delete before rename") if( access( oldfile, WRITE ) == -1 ) { fprintf( stderr, "Will not be able to delete %s later.\n", oldfile ); return EXIT_FAILURE; } // open source if( ( quelle=fopen( oldfile, "r" ) ) == NULL ) { fprintf( stderr, "Can not open %s.\n", oldfile ); return EXIT_FAILURE; } // open target if( ( ziel=fopen( newfile, "w" ) ) == NULL ) { fprintf( stderr, "Can not open %s.\n", newfile ); return EXIT_FAILURE; } while( fgets( puffer, LINELENGTH, quelle ) ) { // if text is not found, then ... if( strstr( puffer, newline ) == 0 ) { fputs( puffer, ziel ); } // if text is found, then ... else { counter++; } } // if counter unchanged, then ... if( counter == 0 ) { fputs( newline, ziel ); fputs( "\n", ziel ); printf( "The line \"%s\" was added to %s.\n", newline, oldfile ); } else { printf( "The line \"%s\" has been removed from %s.\n", newline, oldfile ); } // close both files before deleting / renaming fclose(quelle); fclose(ziel); // delete original if( ( remove( oldfile ) ) == -1 ) { fprintf( stderr, "Error while deleting %s.\n", oldfile ); return EXIT_FAILURE; } // rename manupulated copy to original if( ( rename( newfile, oldfile ) ) == -1 ) { fprintf( stderr, "Error while renaming %s.\n", newfile ); return EXIT_FAILURE; } // so that the console esp. under windows does not disappear with "speed of light" again ... printf( "EXIT WITH RETURN..." ); getchar(); return EXIT_SUCCESS; }