我已经尝试了几个小时来创建一个程序,通过运行以下内容来输出类似 command[/home/nerdofcode/]:
的内容:
printf("Command[", system("pwd"),"]: ");
...
但是我收到的问题是,当我输入输入时,它开始在 command[...
处输入,然后一旦我单击 Enter,它最终会输出 system( “密码”);
...
技术信息
我正在使用 system()
函数在 Linux 上执行系统命令。
最佳答案
要正确使用 printf 来处理以 null 结尾的字符串,您需要更改参数:
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?
关于c - 在一行中输出 C 语言中的 system(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49250233/