C语言文件中字符串的查找与替换

作者&投稿:剧施 (若有异议请与网页底部的电邮联系)
C语言文本文件中字符串的查找与替换。~

#include #include #include int main(){char filename[10],string1[15],string2[15],line[100]; FILE *pfile=NULL;scanf("%s %s %s",filename,string1,string2); pfile=fopen(filename,"r+");if(!pfile){ perror("文件不存在"); return 1; } printf("将把文件%s中字符串%s替换成%s
",filename,string1,string2); while(!feof(pfile)){ char *index=NULL; fgets(line,100,pfile); index=strstr(line,string1); if(index) { int d2=strlen(string2); int d1=strlen(string1); printf("%s 中有%s
",line,string1); if(d1!=d2) { memmove( index+d1+d2-d1, index+d1, strlen(line)); } memcpy(index,string2,strlen(string2)); fseek(pfile,-strlen(line)+d2-d1,SEEK_CUR); fputs(line,pfile); fflush(pfile); }} fclose(pfile); return 0;}

你好,你的代码已经改好了,问题不大,都是一些细节。
已经编译运行确认:)

#include
#include
#include
#include

int Count=0;

int findNum(char *str)
{
int i=0,t1=0;
FILE *p;
char ch;
if((p=fopen("image.gl","rb"))==NULL)
{
printf("
打开文件失败
");
exit(4);
}
while((ch=fgetc(p))!=EOF)
{
if(ch==str[t1])
t1++;
else
t1=0;
if(t1>=strlen(str))
{
printf("找到字符串%s位置为%d
",str,i-strlen(str)+1);
Count = i-strlen(str)+1;
i=1;
break;
}
i++;
}
fclose(p);

if(!i) return 0;
return i;
}

int main(void)
{
FILE *in,*out;
char *str1="1234567";
char *str2="abcdef";
int i=0,j=0,t1=0,t2=0;
char ch;
if((t1=findNum(str1))==0)
{
printf("没有找到字符串%s
请按任意键退出
",str1);
return -1;
}
if((t2=findNum(str2))==0)
{
printf("没有找到字符串%s
请按任意键退出
",str2);
return -2;
}

if((in=fopen("image.gl","rb"))==NULL){
printf("
打开文件失败
");
exit(2);
}
if((out=fopen("image_new.gl","wb"))==NULL){
printf("
创建新文件失败
");
exit(3);
}

i=0;

/* start copy */
while((ch=getc(in))!=EOF)
{
if(t1||t2)
{
if(Count<=80)
{
if(i<=Count) fputc('0',out);
else fputc(ch,out);
}
else
{
if((i>=(Count-80))&&(i<=Count)) fputc('0',out);
else fputc(ch,out);
}
i++;
}
}
fclose(in);
fclose(out);
printf("替换完成!
任意键关闭!
");
getch();
}

如果觉得还行,请加分哦:)

  #include<stdio.h>
  #include<conio.h>
  #include<string.h>
  #include<stdlib.h>
  void Substitute(char *pInput, char *pOutput, char *pSrc, char *pDst)
  {
  char    *pi, *po, *p;
  int     nSrcLen, nDstLen, nLen;
  // 指向输入字符串的游动指针.
  pi = pInput;
  // 指向输出字符串的游动指针.
  po = pOutput;
  // 计算被替换串和替换串的长度.
  nSrcLen = strlen(pSrc);
  nDstLen = strlen(pDst);
  // 查找pi指向字符串中第一次出现替换串的位置,并返回指针(找不到则返回null).
  p = strstr(pi, pSrc);
  if(p)
  {
  // 找到.
  while(p)
  {
  //计算被替换串前边字符串的长度.
  nLen = (int)(p - pi);
  // 复制到输出字符串.
  memcpy(po, pi, nLen);
  memcpy(po + nLen, pDst, nDstLen);
  // 跳过被替换串.
  pi = p + nSrcLen;
  // 调整指向输出串的指针位置.
  po = po + nLen + nDstLen;
  // 继续查找.
  p = strstr(pi, pSrc);
  }
  // 复制剩余字符串.
  strcpy(po, pi);
  }
  else
  {
  // 没有找到则原样复制.
  strcpy(po, pi);
  }
  }
  int main(int ac, char *av[])
  {
  if (ac!=5) {
  printf("程序名 要操作的文件 新文件 查找的字符串 替换的字符串
");
  printf("示例:test.exe 1.txt 2.txt hello love
");
  return 0;
  }
  const int MAXSIZES = 100;
  FILE *fpSrc,*fpDes;
  char filename1[20]="1.txt";
  char filename2[20]="2.txt";
  //要求查找的字符串,替换的字符串;
  char ps[]="hello";
  char pd[]="love";
  //求取所查找和替换的字符串的长度;
  int len_src=strlen(av[3]);
  int len_des=strlen(av[4]);
  //定义存储字符串缓冲区;很奇怪的一点是,fgets函数不能将字符串写入动态分配的内存中
  /*char* Src_buf=(char*)(sizeof(char)*MAXSIZES);
  char* Cpy_buf=(char*)(sizeof(char)*MAXSIZES);
  char* Des_buf=(char*)(sizeof(char)*MAXSIZES);*/
  char Src_buf[MAXSIZES] = {0};
  char Cpy_buf[MAXSIZES] = {0};
  char Des_buf[MAXSIZES] = {0};
  //打开文件
  if((fpSrc=fopen(av[1],"r+"))==NULL)
  {
  printf("fail to open the file1 !
");
  exit(1);
  }
  if((fpDes=fopen(av[2],"a+"))==NULL)
  {
  printf("fail to open the file2 !
");
  exit(1);
  }
  //进行循环读取
  while(!feof(fpSrc))//判断文件是否已结束;!feof(fpSrc)
  {
  fgets(Src_buf,MAXSIZES,fpSrc);
  Substitute(Src_buf,Des_buf,av[3],av[4]);
  fputs(Des_buf,fpDes);
  printf("%s",Des_buf);
  }
  fclose(fpSrc);
  fclose(fpDes);
  system("pause");
  return 0;
  }

说明:使用c标准为中的文件I/O函数一般是不推荐的,做为练习可以学习,真正用的最多的是内存文件映射。那要比用I/O函数读来读取方便的多,限制也会更小。

用"rb" open, 用 fread 读, 用 fwrite 写.
记录地点 用 fgetpos.

下面程序例子是按你的原来题意,找目标字串,输出用替代字.直接用文件操作,不开单元存放文件.

输入文件 a.txt 输出文件 tmp.txt

至于你的新要求,给你提示记录地点的方法.你可以rewind(fin),从头一个字一个字读,读一个输出一个,读到的位置等于POS[i]-80时,读80个字但不输出,这就去掉了80个字.
例如找到的POS[]共NN个。
#define buff_size 1024
long int n,n1,n2,i,j,k;
char *buff;
buff=(char*) malloc(buff_size * sizeof(char));
rewind(fin);
for(k=0;k<NN;k++){
if (k==0) {n=POS[k]-80;} else {n=POS[k]-POS[k-1]-80;};
n1 = n / buff_size; n2 = n % buff_size;
if (n1 >0) for (i=0;i<n1;i++){
fread(buff,sizeof(char),buff_size,fin);
fwrite(buff,sizeof(char),buff_size,fout);
};
if (n2 > 0) {fread(buff,sizeof(char),n2,fin);
fwrite(buff,sizeof(char),n2,fout);
};
fread(buff,sizeof(char),80,fin);
for (i=0;i<80;i++) buff[i]='0'; buff[80]='\0';
fwrite(buff,sizeof(char),80,fout);
} ; end for k
这里请自己写 读最后一段,无需改零,读一个字,输出一个字,直到EOF.
-----------------
#include <stdio.h>
#include <stdlib.h>

void main (int argc, char *argv[])
{
FILE *fin,*fout;
char namein[72]="a.txt";
char nameout[72]="tmp.txt";
char target[120],tidai[120];
char work[120];
int L1,L2,i,k=0;
int numread;
fpos_t pos;
fpos_t POS[100];

printf("Enter target string: ");
scanf("%s",&target[0]);
L1 = strlen(target);
printf("Enter replace string: ");
scanf("%s",&tidai[0]);
L2 = strlen(tidai);

if ( (fin = fopen(namein,"rb") ) == NULL ) {
printf("\007Cann't open input file: %s ", namein);exit(1);
};

if ( (fout = fopen(nameout,"wb") ) == NULL ) {
printf("\007Cann't open temp work file: %s ", nameout);exit(1);
};

Lab1:
numread = fread( work, sizeof( char ), L1, fin );
if (numread < L1) {
// fwrite( work, sizeof( char ), numread, fout );
goto done;
};
if ( strncmp(work,target,L1) == 0 ){
// fwrite( tidai, sizeof( char ), L2, fout );
if( fgetpos( fin, &pos ) != 0 ) perror( "fgetpos error" );
else { POS[k] = pos-L1; k=k+1;};

goto Lab1;
};

Lab2:
// fwrite( &work[0], sizeof( char ), 1, fout );
for (i=0;i<L1-1;i++) work[i]=work[i+1];
fread( &work[L1-1], sizeof( char ), 1, fin );
if (feof(fin)) {
// fwrite( &work[1], sizeof( char ), L1-1, fout );
goto done;
};
if ( strncmp(work,target,L1) == 0 ){
// fwrite( tidai, sizeof( char ), L2, fout );
if( fgetpos( fin, &pos ) != 0 ) perror( "fgetpos error" );
else { POS[k] = pos-L1; k=k+1;};
goto Lab1;
} else {goto Lab2;};

// 新述 rewind(fin); 那部分程序语句插在这里,声明放前面

done: fclose(fin);fclose(fout);
printf("output in %s\n",nameout);
for (i=0;i<k;i++){
printf("%ld \n",(long int) POS[i]);
}
exit(0);
}

你可以这样写,void replace() /*替换单词*/
{
char word[max],reword[max],ch;/*word 为被替换单词,reword为替换单词*/
printf("\n======单词替换======\n");
printf("\n请输入欲被替换的单词:");
scanf("%s",&word);
printf("\n共找到%2d 处 ” %s ” \n",wordfind(word),word);
if (!wordfind(word))
{
printf("\n对不起!不存在该单词!");
getchar();
}
else
{
printf("\n该单词替换为:");
scanf("%s",&reword);
printf("\n确定是否要替换为 “ %s ”?(Y/N) : ",reword);
getchar();
scanf("%c",&ch);
if (ch=='y'||ch=='Y')
if (!revisal(pos,strlen(word),reword))
printf("\n修改成功!");
}
}

int wordfind(char word[]) /*单词匹配*/
{
int i=0,s=0,j,k,len,count=0;
char str[max];
len=strlen(psg);
while (i<len) /*寻找单词*/
{
if ((psg[i]>='a'&&psg[i]<='z')||(psg[i]>='A'&&psg[i]<='Z'))
{
k=0;
for (j=i;j<len;j++)
{
if ((psg[j]>='a'&&psg[j]<='z')||(psg[j]>='A'&&psg[j]<='Z'))
{
str[k]=psg[j]; /*str记录文段中出现的单词*/
k++;
}
else
{
i=j+1;
break;
}
}
if (!strcmp(str,word)) /*对文段中单词和欲替换单词比较*/
{
count++; /*若相同,则统计该单词并记录其起始位置*/
pos[s]=i-k-1;
s++;
}
for (j=0;j<k;j++)
str[j]='\0'; /*初始化字符串str*/
}
else
i++;
}
return count;
}

int revisal(int pos[],int len,char reword[]) /*替换后修改文件*/
{
int i=0,j=0,k;
if ((fp=fopen(filename,"w"))==NULL) /*打开文件*/
{
printf("文件打开失败!");
exit(0);
}
while (i<strlen(psg))
{
if (pos[j]==i) /*在文件中修改替换单词*/
{
for (k=0;k<strlen(reword);k++)
fwrite(&reword[k],sizeof(char),1,fp);
i+=len; /*在psg数组中跳过被替换单词*/
j++;
}
else
{
fwrite(&psg[i],sizeof(char),1,fp);
i++;
}
}
if (fclose(fp)) /*关闭文件*/
{
printf("关闭文件失败");
exit(0);
}
getchar();
return 0;
}

#include<iostream>
#include<conio.h>
#include<string>
#include<stdlib.h>
using namespace std;

int Count=0;

/*
*函数名:findNum
*作者:anglecloudy
*描述:如果存在则返回字符串所在的位置,否则返回0,暂不支持文本中存在多个相同的串
* 先用test.txt文本测试,所有的文本操作都是一样的,不管你怎么命名
*/
int findNum(char *str)
{
FILE *p;
if((p=fopen("test.txt","rb"))==NULL)
{
printf("\n打开文件失败\n");
return 0;
}
char buffer[0x1000]; //保存文件
memset(buffer,0,0x1000); //初始化缓存
size_t fileLen=fread(buffer,sizeof(char),0x1000,p); //得到文件内容,
int readLen=strlen(str);
int IsFind=0;

for(int i=0;i<fileLen;i++)
{
if(strncmp(buffer+i,str,readLen)==0)
{
IsFind=i;
}
}

fclose(p);
return IsFind;
}

int main(void)
{
char *str1="1234567";
int t1=0,t2=0;
if((t1=findNum(str1))==0)
{
printf("没有找到字符串%s\n请按任意键退出\n",str1);
return -1;
}
else
{
printf("字符串%s的位置在%d\n",str1,t1);
}
return 0;
}

我只是简单的改了一下你的字符串查找这个函数,其它的没写。主要是你的思想不对,对文件的操作一般先定义一个数组,把文件保存起来,然后再操作,多去http://community.csdn.net上面问问,高手多,下班了。88

给些建议:
1.你需要替换的文件是否很大,如果不大(不超过10M),一次读完它,别一个字节一个字节读,自己给自己找麻烦。(获取文件大小/c里面可以用fseek+ftell获取,然后malloc对应大小的空间,一次fread读完。)
理由:你这个不是要长时间运行的系统,不用考虑内存占用,因为跑完就结束了。

2.如果都在内存里了,直接可以用库函数strstr来查找,比你自己比较方便许多,代码也没这么复杂。


C语言文件中字符串的查找与替换
pi, nLen);memcpy(po + nLen, pDst, nDstLen);\/\/ 跳过被替换串.pi = p + nSrcLen;\/\/ 调整指向输出串的指针位置.po = po + nLen + nDstLen;\/\/ 继续查找.p = strstr(pi, pSrc);}\/\/ 复制剩余字符串.strcpy(po, pi);}else{\/\/ 没有找到则原样复制.strcpy(po, pi);}}int main...

C语言文本文件中字符串的查找与替换。
pfile){ perror("文件不存在"); return 1; } printf("将把文件%s中字符串%s替换成%s\\n",filename,string1,string2); while(!feof(pfile)){ char *index=NULL; fgets(line,100,pfile); index=strstr(line,string1)

在C语言中,文件的字符串输入\/输出的函数对是什么
test";\/\/11个字符 printf("%d",mystrlen(s));}

c语言编程替换文件中字符串
1、第一步,依次单击visual C ++ 6.0的“文件”-->“新建”-->“文件”-->“C++ Source File”选项,见下图,转到下面的步骤。2、第二步,执行完上面的操作之后,定义变量,代码见下图,转到下面的步骤。3、第三步,执行完上面的操作之后,输入一个字符,使用getche函数接收,代码见下图,转到下...

如何在C语言中输出字符串
1、首先我们新建一个dev C++的项目。2、接下来在项目中新建C语言程序文件。3、然后在C语言文件中声明一个字节数组。4、接下来我们通过printf函数提示用户输入字符串,通过scanf接收用户输入的字符串。5、接着在通过printf函数输出用户输入的内容。6、最后运行C语言程序,就可以知道内容,我们输入内容以后就...

C语言中如何比较字符串的大小?
在C语言中,你可以使用不同的方式来比较字符串的大小。字符串的比较通常依赖于标准库函数和操作符。以下是一些常见的方法:使用strcmp函数:strcmp函数比较两个字符串的内容,返回一个整数值,表示比较结果。通常,如果字符串相等,返回值为0;如果第一个字符串小于第二个字符串,返回值为负数;如果第一...

字符串有哪几种不同的形式?
1、字符串字面量:这是最直接的表现形式,它直接将字符串内容放在一对双引号()或单引号('')中。例如,Hello,World和I am a string。2、字符串变量:这是一种更加动态的方式来表示字符串。你可以将字符串存储在变量中,然后使用这个变量来代表这个字符串。在各种编程语言中,字符串变量通常使用...

C语言中字符串大于字符串吗?
是的,字符串“That”小于字符串“The”。因为是利用ASCII编码逐位按照顺序来比较的:第一位“T”相同,第二位“h”相同,第三位“a”<“e”,所以“That”小于“The”。以compareTo()方法为例,两个字符串比较大小方法:1、如果字符串相等返回值为0,不等返回其他数值。比较方法是先比较对应字符...

C语言中字符串与字符有什么区别?
c语言中的字符串与字符都是两种数据类型,字符串是由字符组成的,两者的区别是字符只能有一个字母,而字符串可以有好多个字母拼成。

在c语言中 字符串如何去定义?有几种定义方法
1、首先,打开C语言编译器,新建一个初始.cpp文件,例如:test.cpp。2、在test.cpp文件中,输入C语言代码:char a[10] = "hello";char b[] = "hello";char *c = "hello";printf("%s%s%s", a, b, c);3、编译器运行test.cpp文件,此时通过所有3种定义字符串的方法成功定义被输出。

景德镇市19680312818: C语言文本中字符串的查找和替换 -
应嘉康得: 这个应该有帮助 #include<iostream> #include<conio.h> #include<string> #include<stdlib.h> using namespace std;int Count=0;/* *函数名:findNum *作者:anglecloudy *描述:如果存在则返回字符串所在的位置,否则返回0,暂不支持文本中...

景德镇市19680312818: C语言文本文件中字符串的查找与替换. -
应嘉康得: #include #include int main(){ char filename[10],string1[15],string2[15],line[100]; FILE *pfile=NULL; scanf(...

景德镇市19680312818: C语言文本文件中字符串的查找与替换. -
应嘉康得: /*功能:查找替换函数返回值:替换后的字符串 strretu*/ char *Replace(char *str, char *str1, char *str2, char *strretu) {char *str_temp = str; //源字符串char *str1_temp = str1; //要求替换的字符串char *str2_temp = str2; //替换成字符串char ...

景德镇市19680312818: C语言如何从字符串数组中找到一个特定的字符串并用一个新的字符串进行替换,要有例程. -
应嘉康得: #include <stdio.h>#include <string.h>//在orginal_str字符串中,找到dest字符串,//然后将它后面的字符串替换为src void replace(char *orig_str, const char *dest, const char*src) { char *right_ptr = NULL ; size_t dest_len = 0 ; size_t src_len = 0 ; if( ...

景德镇市19680312818: C语言中如何在文件内查找关键字并替换? -
应嘉康得: 获取关键字,得到它的长度,然后从操作文件中读取这么长的字符串,进行比较,把文件指针指向下一个字符(注意,要一个字符一个字符的向下进行),这样就可以把需要的关键字找出来,如果想替换的话,把读取出的数组改成想要得再写入,最后别忘记fclose();

景德镇市19680312818: 如何用C语言在文件中查找并替换指定字符串?清高手指点! -
应嘉康得: 编译环境vc2005/dev-c++#include#include#include#define N 10000 /* 设定文件最大字符个数不超过10000,可更改 */ int main() { int i=0,j,k=0,m=0,pos=0,max,len1,len2; char s[N],t[N],a[200],s1[200],s2[200]; FILE *fp; printf("Please input file name:\n...

景德镇市19680312818: c语言从文件中查找字符串 -
应嘉康得: c语言从文件中查找字符串的bai方法.如下参考:1.打开python命令窗口,定义并分配字符串变量s1.2.调用字符串中的count方法dudegree来查找字符#在s1中出zhi现的次数.3.除了第一个参数外,count()方法还可以有第二个参数来指示从dao何处开始搜索.4.在count方法中,还可以在开始位置和结束位置之间添加第三个参数,即结束位置.版5.如果要查找的子字符串不在字符串中,则返回的结果为权0.6.最后,在count()方法中添加所有三个参数来查找对应的字符串.

景德镇市19680312818: C语言查找替换字符 -
应嘉康得: #include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>void Substitute(char *pInput, char *pOutput, char *pSrc, char *pDst){char *pi, *po, *p;int nSrcLen, nDstLen, nLen;// 指向输入字符串的游动指针.pi = pInput;// 指向...

景德镇市19680312818: c语言文件中字符串的查找与替换问题 -
应嘉康得:return -1,都是一些细节;n&quot,out); exit(2);0' #include&lt!i) return 0;没有找到字符串%s\ } i++; else fputc(ch. 已经编译运行确认; / int findNum(char *str) { int i=0; char ch; } } fclose(in); } if((t2=findNum(str2))==0) { printf(":) #include< break,*out...

景德镇市19680312818: 用C语言实现文件的查找与替换 -
应嘉康得: #include"stdio.h" #include"stdlib.h" main() { FILE *fp; char str[80],*p,*head; int n=0; long filelen; loop1: printf("请输入您要用于操作的文件名及其完整路径:\n"); gets(str); fp=fopen(str,"rb+"); if(fp==NULL) { printf("找不到指定文件,...

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网