首页 > 试题广场 >

编写一个程序,接受两个命令行参数。第一个参数为一个字符串;第

[问答题]

编写一个程序,接受两个命令行参数。第一个参数为一个字符串;第二个为文件名。程序打印文件中包含该字符串的所有行。因为这一任务是面向行而不是面向字符的,所以要使用fgets()而不是getc()。使用标准C库函数strstr()(在第II章的练习7中简要描述过)在每一行中搜索这一字符串。

推荐
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 201
int main(int argc,char *argv[])
{
 FILE *fp;
 char str[MAX];
 if ( ( fp=fopen(argv[2],"r") ) == NULL )
 {
 printf("Can't open %s",argv[2]);
 exit(1);
 }
 while ( fgets(str,MAX,fp) != NULL )
 if ( strstr(str, argv[1]) != NULL)
 printf(str);
 return 0;
}

发表于 2018-05-05 22:00:11 回复(0)