Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从重定向文件中查找包含子字符串的字符串,但是否继续获取Seg fault?_C_Segmentation Fault_Malloc_Substring_Strstr - Fatal编程技术网

C 从重定向文件中查找包含子字符串的字符串,但是否继续获取Seg fault?

C 从重定向文件中查找包含子字符串的字符串,但是否继续获取Seg fault?,c,segmentation-fault,malloc,substring,strstr,C,Segmentation Fault,Malloc,Substring,Strstr,程序要求我从重定向文件(filetoreadfrom.data)中查找包含子字符串(在命令行参数中指定)的字符串。该文件包含一个单词(字符串)列表。如果字符串包含子字符串,则打印字符串。命令行如下所示: ./程序子字符串

程序要求我从重定向文件(filetoreadfrom.data)中查找包含子字符串(在命令行参数中指定)的字符串。该文件包含一个单词(字符串)列表。如果字符串包含子字符串,则打印字符串。命令行如下所示:

./程序子字符串 我一直收到“分段错误(核心转储)”错误消息,我不知道为什么。起初我认为这是因为我的字符数组没有malloc'ing,但现在我已经通过使用#define MAXchar 200固定字符数组的大小来摆脱它,我真的看不出哪里出了问题。是因为内存空间,我使用fgets或strstr,还是我重定向文件的方式有问题

这是我的密码:

    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;
    }