#include <stdio.h> #include <stdlib.h> staticvoid usage(void); int main(int argc, char*argv[]) ...{ int i, c[3]; /**//* two swtiches flag */ int backupfile =0, question =0; FILE *sourcefile, *objfile; char tmpname[256]; char bakname[256]; /**//* peocess the switches '/', stop when the first charecter is not '/' */ i =1; while(i < argc) ...{ if(argv[i][0] =='/') ...{ switch(argv[i][1]) ...{ case'b': backupfile =1; break; case'?': question =1; break; default: break; } } else break; i++; } /**//* ask usage or the arguments's number is not correct */ if(question ==1) ...{ usage(); getch(); exit(0); } elseif( argc - i !=3 ) ...{ puts("bad arguments, please type /? for help"); getch(); exit(1); } /**//* we know, the impotant three arguments's positions as follow: argc-3 is the position of filename; argc-2 is the position of charecter which will be replace; argc-1 is the position of new charecter; */ sourcefile = fopen(argv[argc-3], "r"); if(sourcefile == NULL) ...{ printf("can not open file %s", argv[argc-3]); getch(); exit(1); } /**//* get a file name randomly */ tmpnam(tmpname); objfile = fopen(tmpname, "w"); /**//* get the replace charecters */ c[1] = argv[argc-2][0]; c[2] = argv[argc-1][0]; /**//* process the speacial charecter */ i =1; while(i <3) ...{ if(c[i] =='^') ...{ switch(argv[argc-3+i][1]) ...{ case'n': c[i] =''; break; case't': c[i] =''; break; case'^': c[i] ='^'; break; case'*': c[i] ='*'; break; default : break; } } i++; } /**//* replace the charecter */ while( (c[0] = fgetc(sourcefile)) != EOF ) c[0] == c[1] ? fputc(c[2], objfile):fputc(c[0], objfile); fclose(sourcefile); fclose(objfile); /**//* change the file name */ if(backupfile ==1) rename(argv[argc-3], strcat(strcpy(bakname, argv[argc-3]), ".bak")); else remove(argv[argc-3]); rename(tmpname, argv[argc-3]); return0; } staticvoid usage(void) ...{ puts("sreplace /b filename char1 char2 "); puts("use char2 to replace with char1 in filename."); puts("/b: tell program to backup the file."); puts("special characters are supported by char1 and char2,"); puts("and they begin with ^, as follows:"); puts("^n: CR/LF, ^t: table, ^*: *, ^^: ^."); }