gpt4 book ai didi

c - 在 Linux 上的 C 命令行中遇到多个搜索字符串的问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:03 25 4
gpt4 key购买 nike

我试图通过命令行将多个参数传递到我的 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)

最佳答案

很有可能,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);
}

关于c - 在 Linux 上的 C 命令行中遇到多个搜索字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651810/

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