输出含for的行: 将文本文件test.txt中所有包含字符串“for”的行输出。试编写相应程序。
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
bool has_for(char ch[]);
int main(void)
{
FILE *fp = fopen("test5.txt","r");
char ch;
/**之所以按字符逐一进行,是为了防止一行字符中含有空格从而提前终止*/
while((ch = fgetc(fp))!=EOF){
char str[100]={' '}; //每次使用完字符数组都应将其清空,否则会影响后续结果
int i=0;
while(ch!='\n'){ //将文本中的一行字符 放进str[]
str[i] = ch;
i++;
ch = fgetc(fp);
}
if(has_for(str)) //若一行字符中有for,输出
printf("%s\n",str);
}
if(fclose(fp)){
printf("# file close error\n");
exit(0);
}
return 0;
}
/**判断此行字符是否含有for;输入:文本中的一行字符;返回bool*/
bool has_for(char ch[])
{
int i=0;
bool ret;
while(ch[i] != '\n'){
if(ch[i]=='f'&&ch[i+1]=='o'&&ch[i+2]=='r'){ //若连续三个字符构成for,终止循环
ret = true;
break;
}
i++;
}
if(ch[i] == '\n') //循环正常结束,表明字符串中不含for
ret = false;
return ret;
}