gpt4 book ai didi

c - 从重定向文件中查找包含子字符串的字符串,但一直出现段错误?

转载 作者:行者123 更新时间:2023-12-04 04:43:45 24 4
gpt4 key购买 nike

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

./program substring < filetoreadfrom.data



我不断收到“Segmentation-fault (Core dumped)”错误消息,我不知道为什么。起初我以为是因为没有对我的 char 数组进行 m​​alloc'ing,但现在我已经通过使用 固定 char 数组的大小来摆脱它。 #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;

}

我希望你们能对此有所了解。谢谢!

最佳答案

当您检查 argv[2] 时它会崩溃.没有argv[2] ,作为 <是一个控制台/shell 特定的命令,它不会传递给您的程序。在您检查 argv[2] 时,它是一个 NULL 指针,您无权在那里写/读。这就是段错误发生的原因。

例如

#include <stdio.h>
int main(int argc, char** argv)
{
printf("%d\n", argc);
return 0;
}

输出:
$ ./test < test.c
1
$

关于c - 从重定向文件中查找包含子字符串的字符串,但一直出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com