#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long GetFileSize(FILE *fp){
long fsize = 0;
fseek(fp,0,SEEK_END);
fsize = ftell(fp);
fseek(fp,0,SEEK_SET);//reset stream position!!
return fsize;
}
int main(int argc, char **argv){
char *file, *sword, *rword, *buff, *wp,*bp;
int len;
long fsize;
FILE *inpFile;
if(argc != 4){
fprintf(stderr, "Usage:rep filePath originalWord replaceWord\n");
exit(EXIT_FAILURE);
}
file = argv[1];
sword = argv[2];
rword = argv[3];
if(NULL==(inpFile=fopen(file, "rb"))){
perror("Can't open file");
exit(EXIT_FAILURE);
}
fsize = GetFileSize(inpFile);
buff=(char*)malloc(sizeof(char)*fsize+1);
fread(buff, sizeof(char), fsize, inpFile);//file all read into buff
fclose(inpFile);
buff[fsize]='\0';
bp=buff;
len = strlen(sword);
while(NULL!=(wp=strstr(bp, sword))){
while(bp != wp)
putchar(*bp++);
printf("%s",rword);
bp+=len;
}
if(bp) printf("%s", bp);
free(buff);
return 0;
}
全部讀取,然後輸出替換,然後 – BLUEPIXY 2012-04-13 12:03:13