c - 在一行中输出 C 语言中的 system()

标签 c linux gcc

我已经尝试了几个小时来创建一个程序,通过运行以下内容来输出类似 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/

相关文章:

c - 在 for 循环中使用结构的问题

linux - 在bash中重命名大量文件

GCC 内联汇编副作用

mysql - 在 Lustre 文件系统上启动 Mysqld 的持续时间太长(InnoDB : Unable to lock ./ibdata1,错误:38)

linux - Qt在Qt gridLayout中启动一个外部程序

基于 ARM 的 mySQL C 连接器

macos - 无法在 Mac 上升级 gcc

c - 使用递归关系证明函数具有指数运行时间?

c - 如何确定缓冲区的大小

c - 打印整数和 float 的运算结果