鱼C论坛

 找回密码
 立即注册
查看: 1449|回复: 1

在命令行中识别分离>与<

[复制链接]
发表于 2023-9-26 17:04:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
用C语言写shell时,想要实现bash style的重定向功能,但是不知道当语句间没有空格时,怎么分离出<与>。       
        fgets(command, sizeof(command), stdin);
        token=strtok(command," ");

        int i=0;

        while( token != NULL ) {
            printf( "%s\n", token );
            i++;
            token = strtok(NULL, " ");
        }
但这只能按照空格将command中各部分分开,识别不了>或<
假如command为cat<1.txt>2.txt,如何能分成以下5个部分呢?
cat < 1.txt > 2.txt
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-9-26 17:05:08 | 显示全部楼层
可以使用strchr函数来查找字符串中的特定字符,然后将字符串分成相应的部分。以下是一个可能的实现:

  1. fgets(command, sizeof(command), stdin);

  2. char *input_redirect = strchr(command, '<');
  3. char *output_redirect = strchr(command, '>');
  4. char *command_name = strtok(command, " \n");

  5. if (input_redirect) {
  6.     *input_redirect++ = '\0';
  7.     char *input_file = strtok(input_redirect, " \n");
  8.     // do something with input_file
  9. }

  10. if (output_redirect) {
  11.     *output_redirect++ = '\0';
  12.     char *output_file = strtok(output_redirect, " \n");
  13.     // do something with output_file
  14. }

  15. // do something with command_name
复制代码


这个实现首先使用strchr函数查找输入重定向符号“<”和输出重定向符号“>”。然后,它将命令字符串分成三个部分:命令名称、输入重定向文件名和输出重定向文件名。对于每个重定向文件名,它使用strtok函数将其分离出来。最后,您可以在代码中使用这些部分来执行相应的操作。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 09:36

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表