我正在尝试实现重定向。我有来自用户的输入,我正在尝试从中提取输出文件。我正在使用 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);
您开始复制到output_file
,而不是在开头,而是在之后复制到chr_position - line
字节。从头开始:
strcpy(output_file, chr_position + 1);
另请注意,由于 chr_position
指向 >
字符,因此您希望在该字符之后开始复制至少 1 个字节。
关于c - 如何从字符串中提取某个字符后的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697445/