C 如何从某个字符后的字符串中提取子字符串?

C 如何从某个字符后的字符串中提取子字符串?,c,substring,C,Substring,我正在尝试实现重定向。我有一个来自用户的输入,我正试图从中提取输出文件。我正在使用strstr查找第一个出现的'>'。从那里我可以提取字符串的其余部分,但我不确定如何实现这一点 我尝试过将strstr与strcpy一起使用,但没有成功 // char_position is the pointer to the character '>' // output_file is the file that I need to extract // line is the original st

我正在尝试实现重定向。我有一个来自用户的输入,我正试图从中提取输出文件。我正在使用strstr查找第一个出现的'>'。从那里我可以提取字符串的其余部分,但我不确定如何实现这一点

我尝试过将strstr与strcpy一起使用,但没有成功

// char_position is the pointer to the character '>'
// output_file is the file that I need to extract
// line is the original string

// example of input: ls -l > test.txt

char *chr_position = strstr(line, ">");
char *output_file = (char *) malloc(sizeof(char) * (strlen(line) + 1));
strcpy(output_file + (chr_position - line), chr_position // something here?);
printf("The file is %s\n", output_file);
预期结果是从>到行尾生成一个字符串。

执行此操作时:

strcpy(output_file + (chr_position - line), chr_position);
您开始复制到输出_文件,不是在开始位置,而是在开始之后的chr_位置行字节。请从头开始:

strcpy(output_file, chr_position + 1);

还请注意,由于chr_位置指向>字符,因此您希望在该字符之后开始复制至少1个字节。

您可以很容易地使用strstr来完成此操作:

char inarg[] = "ls -l > test.txt";

char  *pos;
pos = strstr(inarg, "> ") + 2;
printf("%s\n", pos);   // Will print out 'test.txt'
这是通过在字符串中查找>组合来实现的。strstr调用后的+2是为了允许strstrstr返回一个指向string'>test.txt'的指针,我们希望跳过带有尾随空格的'>'2字节,因此我们在指针上添加2,以便它最终指向我们希望提取的文本