#include<stdio.h> #include<errno.h> #include<unistd.h> #include<stdlib.h> #include<string.h> #include<sys/stat.h> #define LINE_SIZE 256 /********* * 函数名:Subit * 功能:将pathname文件中的字符串s1替换成s2 * 参数: * @s1:被替换字符串 * @s2:替换字符串 * @pathname:文件名 * 返回值: * 无 * *******/ void Subtit(const char*s1,const char *s2,const char *pathname) { int len_s1 = strlen(s1); int len_s2 = strlen(s2); FILE *fileline=fopen(pathname,"r+"); if(fileline==NULL) { printf("Fopen %s error!",pathname); exit(0); } struct stat filestate; stat(pathname,&filestate); char *filebuffer=(char *)malloc(sizeof(char)*(filestate.st_size+1)); for (int i = 0,ch=0;ch!=EOF;i++) { ch = fgetc(fileline); filebuffer[i]=ch; } fseek(fileline,0,SEEK_SET); for (char *index_1 = filebuffer,*index_2 = filebuffer;;) { index_2 = strstr(index_1,s1); if(index_2) { for(int i=0;i<index_2-index_1;i++) { fputc(index_1[i],fileline); } for(int i=0;i<len_s2;i++) { fputc(s2[i],fileline); } index_1=index_2+len_s1; } else { while(*index_1!=EOF) { fputc(*index_1++,fileline); } break; } } free(filebuffer); fclose(fileline); } void usage() { printf("================Usage================\n"); printf("./a.out [string1] [string2] [filename]\n"); printf("Tips:Replace string1 with string2!\n"); printf("=====================================\n"); } int main(int argc,char **argv) { if(argc!=4) { usage(); printf("The parameters are error!\n"); return -1; } Subtit(argv[1],argv[2],argv[3]); printf("Successful replacement\n"); return 0; }