/* Author: bhw * EMail: bhwshx@163.com * Date: 2009.03.04 22:22*/ /* *Function: Replace old_word in Src file with new_word,and save it as Des file */ #include<stdio.h> #include<string.h> #define SIZE 256 //define buf size, 256 is big enough for common files void freplace(char *p, FILE *fpDes, char *pargv3, char *pargv4); int main(int argc, char *argv[]) { FILE *fpSrc, //src file *fpDes; //des file static char buf[SIZE]; if(argc != 5) { printf("Usage:%s [src file name] [des file name] [old word] [new word]/n", argv[0]); return 0; } //Make sure the src file and des file are legal to deal with. fpSrc = fopen(argv[1], "r"); if(fpSrc == NULL) { perror("Open src file"); return 0; } fpDes = fopen(argv[2], "w"); if(fpDes == NULL) { perror("Open des file"); return 0; } while(fgets(buf, SIZE, fpSrc) != NULL) //get a line(ended with '/n') at one time and move it into buf { freplace(buf, fpDes, argv[3], argv[4]); //deal with buf } fclose(fpSrc); fclose(fpDes); return 0; } void freplace(char *p, FILE *fpDes, char *pargv3, char *pargv4) { char word[SIZE], *pword; while((*p != '/n') && (*p != '/0')) //in buf,it seems like this:" abc def ghi;/n/0", { //there is a '/n' because fgets() could accept '/n'.fgets() adds a '/0' in the end. while((*p == ' ') || (*p == '/t')) //at first deal with the spaces in buf { fputc(*p, fpDes); //output the spaces into des file ++p; } for(pword=word; *p != ' ' && *p != '/t' && *p != '/n'; )//start record non-space characters { *pword++ = *p++; } *pword = '/0'; //a complete word string has been recorded. if(strcmp(word, pargv3) == 0) //compare word with old_word,if equal,output new_word into des file fprintf(fpDes, "%s", pargv4); else fprintf(fpDes, "%s", word);//otherwise,output word into des file. } if(*p == '/n') //output the '/n' to end a line fputc('/n', fpDes); }