Ⅰ 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。