我正在尝试通过命令行将多个参数传入我的Linux终端上的C程序,但是我收到了分段错误。
这是我的输出:
$ ./a.out bar a a
you made it past opening and reading file
your file size is 7
Your count is:2
Segmentation fault (core dumped)
这是我应该得到的:
$ ./a.out bar a a
you made it past opening and reading file
your file size is 7
Your count is:2
Your count is:2
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[] )
{
/******* Open, Read, Close file**********************************/
FILE *ReadFile;
ReadFile = fopen(argv[1], "r");
if(NULL == ReadFile)
{
printf("\n file did not open \n");
return 1;
}
fseek(ReadFile, 0 , SEEK_END);
int size = ftell(ReadFile);
rewind(ReadFile);
char *content = calloc( size +1, 1);
fread(content,1,size,ReadFile);
/*fclose(ReadFile); */
printf("you made it past opening and reading file\n");
printf("your file size is %i\n",size);
/******************************************************************/
/*********************String compare and print*********************/
int count =0;
int inputs;
for( inputs = 2; inputs < argc ; inputs++)
{
char *input = argv[inputs];
while (content = strstr(content,"a"))
{
count++;
content++;
}
printf("Your count is:%i\n",count);
}
/*****************************************************************/
return 0;
}
好吧所以我将比较部分从“a”改为输入,因为我希望能够比较我输入终端的任何数字字符子串:
/*********************String compare and print*********************/
int count =0;
int inputs;
for( inputs = 2; inputs <= argc ; inputs++)
{
char *input = argv[inputs];
content = input;
while (content = strstr(content,input))
{
count++;
content++;
}
printf("Your count is:%i\n",count);
}
/*****************************************************************/
但现在我的输出是: (我的条形文本文件中有'aabbcc')
$ gcc strstrTest.c
$ ./a.out bar a a
you made it past opening and reading file
your file size is 7
Your count is:1
Your count is:2
Segmentation fault (core dumped)
答案 0 :(得分:2)
最有可能的是,strstr
会返回NULL
,因为它不再找到a
。当你再尝试strstr
时,它会尝试搜索NULL,这会产生分段错误。
也许你想做
content = strstr(input, "a");
或
content = input;
在while循环之前的或类似的东西。
更新
不知何故,我完全错过了,bar
是一个文件名。因此,如果要在此文件中搜索多个字符串,则必须单独使用content
,使用其他变量进行搜索,并在每次搜索其他字符串时重置该字符串
for (inputs = 2; inputs < argc; inputs++) {
char *input = argv[inputs];
char *search = content;
while (search = strstr(search, input)) {
count++;
search++;
}
printf("Your count is:%i\n", count);
}