Ⅰ C语言怎么从文件中查找字符串并打印
#include <stdio.h>
#include <stdlib.h>
void File()
{
FILE *in, *out;
char ch ;
if ((in = fopen("d:\\wenjian\\in.txt","r")) == NULL) //in.txt 和out.txt 都在当前工作目录下存放
{
printf("canot find the file!\n");
exit(0);
}
if ((out = fopen("d:\\wenjian\\out.txt","w"))==NULL) // 写入数据的文件
{
printf("canot find the out.txt file !\n");
exit(0);
}
ch = fgetc(in);
while (ch!=EOF)
{
fputc(ch,out);
putchar(ch); //是in.txt 的内容显示在dos窗口 下
ch = fgetc(in);
}
fclose(in); // 关闭文件
fclose(out);
}
int main()
{
File() ;
puts("");
return 0;
}
我写的代码参考下。
Ⅱ c语言从文件中查找字符串
不用宽丛袭自己写,有一个函数叫strstr,郑祥原型是
char
*strstr(char
*str1,
char
*str2),功慎兄能是找出str2字符串在str1字符串中第一次出现的位置。
可以这样写:
char
*p=strstr(a,b);
if(null
!=
p)
{
//a中不存在b,添加相应代码
}
else
{
//a中存在b,添加相应代码
}
返回值p为a中第一次出现b的位置
这个函数要包含头文件string.h
Ⅲ c语言在文本中查找字符串
第一空填:argv[1] //文件名以字符指针的形式存在argv[1]中
第二空填:fscanf(fp,"%s\n",str); //读取版一行的字符串,存到str这个字符数组中权去
第三空填:fclose(fp); //关闭文件
Ⅳ C语言中如何查找字符串
用strstr这个函数
包含文件:string.h
函数名: strstr
函数原型:extern char *strstr(char *str1, char *str2);
功能:找出str2字符串在str1字符串中第一次出现的位置(不包括str2的串结束符)。
返回值:返回该位置的指针,如找不到,返唤塌迹回空指针。
源代码:
#include
Ⅳ C语言文件中字符串的查找与替换
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
voidSubstitute(char*pInput,char*pOutput,char*pSrc,char*pDst)
{
char*pi,*po,*p;
intnSrcLen,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);
}
}
intmain(intac,char*av[])
{
if(ac!=5){
printf("程序名要操作的文件新文件查找的字符串替换的字符串 ");
printf("示例:test.exe1.txt2.txthellolove ");
return0;
}
constintMAXSIZES=100;
FILE*fpSrc,*fpDes;
charfilename1[20]="1.txt";
charfilename2[20]="2.txt";
//要求查找的字符串,替换的字符串;
charps[]="hello";
charpd[]="love";
//求取所查找和替换的字符串的长度;
intlen_src=strlen(av[3]);
intlen_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);*/
charSrc_buf[MAXSIZES]={0};
charCpy_buf[MAXSIZES]={0};
charDes_buf[MAXSIZES]={0};
//打开文件
if((fpSrc=fopen(av[1],"r+"))==NULL)
{
printf("failtoopenthefile1! ");
exit(1);
}
if((fpDes=fopen(av[2],"a+"))==NULL)
{
printf("failtoopenthefile2! ");
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");
return0;
}
Ⅵ c语言从文件中查找字符串
c语言从文件中查找字符串的方法。
如下参考:
1.打开python命令窗口,定义并分配回字符串变量答s1。