C 从重定向文件中查找包含子字符串的字符串,但是否继续获取Seg fault?
程序要求我从重定向文件(filetoreadfrom.data)中查找包含子字符串(在命令行参数中指定)的字符串。该文件包含一个单词(字符串)列表。如果字符串包含子字符串,则打印字符串。命令行如下所示: ./程序子字符串C 从重定向文件中查找包含子字符串的字符串,但是否继续获取Seg fault?,c,segmentation-fault,malloc,substring,strstr,C,Segmentation Fault,Malloc,Substring,Strstr,程序要求我从重定向文件(filetoreadfrom.data)中查找包含子字符串(在命令行参数中指定)的字符串。该文件包含一个单词(字符串)列表。如果字符串包含子字符串,则打印字符串。命令行如下所示: ./程序子字符串
char line[MAXchar]; //MAXchar = 200
int count=0;
//check usage
if ((strcmp("<", argv[2]))!=0){
fprintf(stderr,"Usage: ./program substring\n");
return 1;
}
//read lines from redirected file
while (fgets(line,MAXchar,stdin)!=NULL){
//find substring in each line
//if substring is present in the line
if (strstr(line,argv[1])!=NULL){
//print the line
fprintf(stdout, "%s\n", line);
count=1;
}
}
//if none of the line contains the substring
if (count==0){
fprintf(stdout, "No match found\n");
}
return 0;
char行[MAXchar]//MAXchar=200
整数计数=0;
//检查使用情况
如果((strcmp(“)与该命令行argv[2]
将NULL
,那么该行
if ((strcmp("<", argv[2]))!=0){
if((strcmp)(当您检查argv[2]
时,它会崩溃。没有argv[2]
,因为的
意味着使用filetoreadfrom.data作为stdin
所以你的程序只有两个参数:/program substring
在您的代码中,删除此部分:
if ((strcmp("<", argv[2]))!=0){
fprintf(stderr,"Usage: ./program substring\n");
return 1;
}
if((strcmp(“我认为可能有很多问题..您没有检查参数的数量,'实际上argv[]
是NULL
终止的,因此它是NULL
指针解引用。当然,这也很糟糕。:)
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%d\n", argc);
return 0;
}
$ ./test < test.c
1
$
if ((strcmp("<", argv[2]))!=0){
fprintf(stderr,"Usage: ./program substring\n");
return 1;
}