c语言从文件查找字符串,C语言文件中字符串的查找与替换?

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

#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("\n打开文件失败\n");

exit(4);

}

while((ch=fgetc(p))!=EOF)

{

if(ch==str[t1])

t1++;

else

t1=0;

if(t1>=strlen(str))

{

printf("找到字符串%s位置为%d\n",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\n请按任意键退出\n",str1);

return -1;

}

if((t2=findNum(str2))==0)

{

printf("没有找到字符串%s\n请按任意键退出\n",str2);

return -2;

}

if((in=fopen("image.gl","rb"))==NULL){

printf("\n打开文件失败\n");

exit(2);

}

if((out=fopen("image_new.gl","wb"))==NULL){

printf("\n创建新文件失败\n");

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("替换完成!\n任意键关闭!\n");

getch();

}

问题:目前无法确定是否找到了字符串并且替换,而且生成出的文件始终为381KB,请高手予以调试修改!感谢!

雷老虎66

发布

1个回答

67b0a70febe552c922c54bb8560d6ef6.png

e3aaa8a6393334998f7e60b47e230792.png

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);

}

}

◆◆

评论读取中....

请登录后再发表评论!

◆◆

修改失败,请稍后尝试

精华知识

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值