一个c语言写的小程序读取某文本文件两个特定字符串之间的字符

一个c语言写的小程序读取某文本文件两个特定字符串之间的字符,嗯写到另一个文件里。
前几天弄得好像没这样的函数,写的不好,就是玩玩。

#include "stdafx.h"
#include "stdio.h"
#include "windows.h"

int main(int argc, char* argv[])
{
FILE *fp,*fpout;
char ch; //读取字符
char infile[256];
char find[20]={'\0'};
char stop[20]={'\0'};
int flag=0;
int sflag=0;

/*
flag 状态
0 初始状态
1 查找开始状态
2 开始状态
sflag 状态
1 查找结束状态
2 结束状态

*/

int i=0;
int k=0;
memset(infile,0,201); //文件路径
memset(find,0,20);
memset(stop,0,20);

if(argc==1)
{
printf("Plz input the full file path...\n");
return 0;
}
if(strlen(argv[1])>255)
{
printf("The file path too long...\n");
return 0;
}
strcpy(infile,argv[1]);

fp=fopen(infile,"r");
if(NULL==fp)
{
printf("Open file failed!\n");
return 0;
}
fpout=fopen("D:\\test.txt","w+");
if(NULL==fpout)
{
printf("Open file failed!\n");
return 0;
}

ch=fgetc(fp);
while(ch!=EOF)
{
if(flag!=2&&ch=='1')
{
//printf("Find 1\n");
flag=1;
i=0;
}
///*给程序增加结束标志
if(flag==2&&ch=='C')
{
sflag=1;
k=0;
putchar(ch);
}
if(sflag==1)
{
if(k<18)
{
stop[k]=ch;
stop[k+1]='\0';
k++;
//printf("%s\n",stop);
if(!strncmp(stop,"stopflag",8))
{
sflag=2;
fclose(fp);
fclose(fpout);
return 0;
}
}
}
//*/
if(flag==1&&i<18)
{
//putchar(ch);
find[i]=ch;
find[i+1]='\0';
i++;
if(!strncmp(find,"startflag",9))
{
flag=2;
}
//else flag=0;
}
if(flag==2)
{
putchar(ch);
fputc(ch,fpout);
}
ch=fgetc(fp);
}
fclose(fp);
fclose(fpout);
return 0;
}

0 评论: