将命令行输出重定向到 C 中的变量
有没有办法重定向命令行的输出,将整数作为输出返回到 C 中的变量?
例如,如果命令是“cmd”,那么有没有办法重定向其输出(整数)并将其存储在 C 中的变量中? 我尝试使用 popen 和 fgets 但它似乎只适用于字符。有什么建议吗?
Is there a way to redirect output of a command line which returns integer as an output to a variable in C?
for example, if the command is "cmd", then is there a way to redirect its output (an integer) and store it in variable in C?
I tried using popen and fgets but it seems to be working only with characters. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它与 popen 和 fgets 完美配合:
It works perfectly fine with popen and fgets:
如果你想从标准输入转换字符串,你可以使用 fgets ,然后使用 atoi 将输入转换为整数。
如果您想转换命令的输出,例如
ls
并将命令的输出存储到变量中,您可以了解 fork, dup2< /a>, 管道 和 exec 函数系列。有关此主题的更多信息,请参阅本教程:在 C 中捕获子进程的输出。如果您想保持“高水平”,本教程还提供了一个
popen
示例。If you want to convert a character string from the standard input, you could use fgets and then use atoi to convert the input to an integer.
If you want to convert the output of a command, let's say
ls
and store the output of the command to a variable, you could learn about fork, dup2, pipe, and exec function family.More about this topic on this tutorial : Capture the output of a child in C. This tutorial also provide an example with
popen
if you want to keep things "high level".下面是一个使用
popen()
和fscanf()
的更简单的示例:Here is an even simpler example using
popen()
andfscanf()
: