【设计要求】打开指定的文本文件inpaper.data,输入查找串t1和替换串t2,然后把inpaper.data文本文件中所有的t1串替换为t2串,并输出。
【代码实现】

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SOURCEFILE "inpaper.data"
#define MaxSize 100000
char inpaper[MaxSize];
char outpaper[MaxSize];
char t1[MaxSize]; //查找串
char t2[MaxSize]; //替换串
int Getdata(char paper[]);
void Replace(char Nstr[], char Cstr[], char t1[], char t2[]);
int Outputdata(char paper[]);
int main()
{
         char *current;
         int i = 0;
         int j = 0;
         Getdata(inpaper);
         printf("%s", inpaper);
         printf("请输入你要查找的串:\n");
         gets(t1);
         printf("请输入你替换后的串:\n");
         gets(t2);
         Replace(outpaper, inpaper, t1, t2);
         Outputdata(outpaper);
         printf("%s", outpaper);
}

int Getdata(char paper[])
{
         FILE *fp;
         if ((fp = fopen(SOURCEFILE, "rb")) == NULL) /* 以读方式打开文本文件 */
         {
                   printf("Failure to open score.txt!\n");
                   return 0;//读数据失败
         }
         int i = 0;
         while (!feof(fp))
         {
                   fscanf(fp, "%c", &paper[i]);
                   i++;
         }
         fclose(fp);
         return 1;  //成功读数据                         
}

int Outputdata(char paper[])
{
         FILE *fp;
         if ((fp = fopen("out.data", "wb")) == NULL) /* 以写方式打开文本文件 */
         {
                   printf("Failure to open score.txt!\n");
                   return 0;//写数据失败
         }
         for (int i = 0; paper[i] != '\n'; i++)
                   fprintf(fp, "%c", paper[i]);

         fclose(fp);
         return 1;
}

void Replace(char Nstr[], char Cstr[], char t1[], char t2[])
{
         char *p = NULL;
         char *pos = NULL;
         pos = Cstr;
         int len = strlen(t1);
         while ((p = strstr(pos, t1)) != NULL)
         {
                   strncpy(Nstr, pos, p - pos);
                   Nstr[p - pos] = '\0';
                   strcat(Nstr, t2);
                   strcat(Nstr, p + len);
                   strcpy(pos, Nstr);
         }
         strcpy(Nstr, pos);
}

【运行结果】
实现对指定文本文件进行查找与替换