该程序要求我从重定向文件 (filetoreadfrom.data) 中查找包含子字符串(在命令行参数中指定)的字符串。该文件包含单词(字符串)列表。如果字符串包含子字符串,则打印字符串。命令行如下:
./program substring < filetoreadfrom.data
我不断收到“Segmentation-fault (Core dumped)”错误消息,我不知道为什么。起初我以为这是因为没有分配我的 char 数组,但现在我已经通过使用#define MAXchar 200修复 char 数组的大小来摆脱它,我真的看不出哪里出了问题。是因为内存空间、我对 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;
}
我希望你们能对此有所了解。谢谢!