【问题标题】:Output system() in C on one line在 C 语言中输出 system() 一行
【发布时间】:2018-03-13 07:12:21
【问题描述】:

我已经尝试了几个小时来创建一个输出类似command[/home/nerdofcode/]: 的程序,方法是运行以下内容: printf("Command[", system("pwd"),"]: ");...

但我收到的问题是,当我输入输入时,它开始在command[... 输入,然后一旦我点击输入,它最终输出system("pwd");...

技术信息

我正在使用system()函数在Linux上执行系统命令。

【问题讨论】:

  • 您是否仔细阅读了printf() 的规范?您的代码与格式不匹配。
  • 你能澄清一下吗?
  • system() 不会在输出中返回字符串。
  • system() 的返回值是特定于实现的。您首先需要了解如何获得结果输出。让我们知道这一点,以便可能得到您想要的答案。
  • 如果您只想获得结果,但不要坚持使用system(),请查看:stackoverflow.com/questions/16285623/…

标签: c linux gcc


【解决方案1】:

要将 printf 正确用于以空字符结尾的字符串,您需要更改参数:

printf("Command[%s]: ", string_with_result);

为了正确获取string_with_result,您需要研究system() 在您的环境中的工作方式。它的返回值是特定于实现的,因此不允许用你想要的代码来回答。

char * string_with_result; /* pointer to null-terminated sequence of char */

这是上面提出的用于 printf 的字符串结果的声明。

如果您只想获得结果,但不坚持使用system(),请检查此 StackOverflow 问题并接受答案:
'pwd' to get path to the current file

这个问答可能是在“unix-ish”环境中实际使用system() 的方式,它使用popen()
C: Run a System Command and Get Output?

【讨论】:

    【解决方案2】:

    printf 不能作为逗号分隔字符串的“concat”操作。它有一个带有占位符的格式字符串和占位符的参数。

    所以你可以写:

    char *s1 = "hello", *s2 = "world"; 
    printf("%s %s", s1, s2);
    

    但是下面的代码不会连接这两个字符串;它会将s1 视为格式字符串(不带占位符)并忽略该参数:

    char *s1 = "hello", *s2 = "world"; 
    printf(s1, s2);
    

    进一步注意int system(const char* cmd) 不会返回一个字符串,你可以在printf 中使用它。所以我建议写。

    printf("Command[");
    system("pwd");
    printf("]: ");
    

    只要system-command 和您的程序sstdout` 以相同的输出流为目标,这应该可以在控制台上运行。

    【讨论】:

    • 那么你建议我使用strcat之类的东西吗?
    • 不走运...这是我的输出:/home/user/Desktop/directory/SrcCommand[]:
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 2017-09-06
    • 2021-06-21
    • 2012-09-07
    相关资源
    最近更新 更多