三亚海棠湾度假区:c语言程序设计 单词替换

来源:百度文库 编辑:高考问答 时间:2024/04/28 14:59:01
1,输入文本文件名,替换前的单词和替换后的单词。读入该文本文件,对指定的单词进行替换,把替换后的内容保存到另一个文件中,并输去替换单词的次数。
2采用模块化思想设计程序,合理定义函数。

请高手指点一下,闲人勿扰,由于程序小,急用请尽快。谢谢!

//查找并替换指定文件所包含的字符串,保存于另一个文件中

#include "stdio.h"
#include "iostream.h"
#include "string.h"

void main()
{
FILE *fp1,*fp2;
char path[128],path_new[128],search[128],replace[128];

cout<<"input the file path and name."<<endl;//输入原文件的路径和文件名
gets(path);
//puts(path);
cout<<"input the new file path and name."<<endl;//输入新文件的路径和文件名
gets(path_new);
cout<<"input the words you want to search."<<endl;//输入所查找的字符串
gets(search);
cout<<"input the words you want to replace."<<endl;//输入要替换的字符串
gets(replace);

int len;//所查找的字符串的长度
len=strlen(search);
//cout<<len<<endl;
int len_replace;//要替换的字符串的长度
len_replace=strlen(replace);

if((fp1=fopen(path,"r+"))==NULL)//打开原文件
{
cout<<"Can not open this file."<<endl;
//exit();
}

if((fp2=fopen(path_new,"w+"))==NULL)//创建新文件
{
cout<<"Can not open this file."<<endl;
//exit();
}

while(feof(fp1)==0)
{
char ch=fgetc(fp1);
long num=1;//匹配字符计数器

if(ch==search[0])//发现与查找的字符串匹配的第一个字符
{
int err=0;
for(int i=1;i<len;i++)//确定字符串是否完全匹配
{
ch=fgetc(fp1);
num++;
if(ch!=search[i])
{
err=1;
break;
}
}

if(err==0) //完全匹配
{
for(i=0;i<len_replace;i++)//插入要替换的字符串
fputc(replace[i],fp2);
}

else//未完全匹配,返回指针至与查找的字符串匹配的第一个字符
{
fseek(fp1,-num,1);
ch=fgetc(fp1);
fputc(ch,fp2);
}

}

else fputc(ch,fp2);//复制其他字符串

}

fclose(fp1);//关闭原文件
fclose(fp2);//关闭新文件

}

-------------------
C++的程序可以吗?已经通过调试,希望对你有帮助。

 
 
 
以下是我写的代码,你可以参考。
代码里只有简单的错误处理(好让程序的简单运作显见)。
要合理定义函数的话,可以把
(1)计算文件字符个数和
(2)读取文件、替换单词然后保存内容
的代码写成个别的函数。

有问题尽管问。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define SSIZE 99

void main() {
    char ifname[SSIZE], ofname[SSIZE] = "modified_", old[SSIZE], new[SSIZE];
    FILE *ifp, *ofp;

    puts("请输入文本文件名、替换前的单词和替换后的单词(用回车把每一项输入隔开):");
    strcat(ofname, gets(ifname));    gets(old);    gets(new);

    if ((ifp = fopen(ifname, "r")) && (ofp = fopen(ofname, "w"))) {
        size_t ifsize = 0, count = 0;
        char *text, *found;

        /* 计算输入文件的大小,然后把全部内容读入动态内存,即得一个字符串 */
        for ( ; getc(ifp) && ! feof(ifp); ++ifsize);
        rewind(ifp);
        fscanf(ifp, "%[^\0]", text = malloc(ifsize * sizeof(char) + 1));

        if (found = strlen(old) ? strstr(text, old) : NULL) {
            for ( ; found = strstr(text, old); text = found + strlen(old), ++count) {
                fprintf(ofp, "%.*s", found - text, text);
                fputs(new, ofp);
            }
            fputs(text, ofp);
        }
        else
            fputs(text, ofp);

        printf("替换的个数是 %d。\n替换后的内容保存在 %s 里。\n", count, ofname);
    }
    else
        printf("什么也没做成,因为打不开这个文件:%s\n", ifp ? ofname : ifname);
}