在此之前:我搜索了类似的问题,但似乎没有一个解决方案适合我。另外,我是 C 语言的新手,对于我能犯的愚蠢错误深表歉意。谢谢。
我的 C++ 文件有点问题。 我想要的是从系统(“命令”)设置一个变量。我不知道我是否解释得很好,所以我以我的文件为例。 这是我的文件:
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
int kernel = system("uname -a");
//Here It should print the value but instead of that prints a zero :/
printf("%d \n", kernel);
return 0;
}
我正在尝试从 system("uname -a") 命令的输出中定义变量“kernel”,它应该是这样的:
$ uname -a
Linux 5.0.0-27-generic #28~18.04.1-Ubuntu SMP Thu Aug 22 03:00:32 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
但是,当我尝试执行代码时,输出只是:
0
我遗漏了什么或者这不能在 C++ 中完成?抱歉这个菜鸟问题。
最好的问候。
最佳答案
system
返回错误代码,而不是命令输出。 0 表示没有错误。您正在寻找的是 popen
。
#include <stdio.h>
char uname[1024];
FILE* fp = popen("uname -a", "r");
if (!fp)
/* Handle error */;
if (fgets(uname, sizeof(uname), fp) != 0)
std::cout << uname << std::endl;
int status = pclose(fp);
if (status == -1) {
/* Error reported by pclose() */
}
类似的问题演示了读取没有长度限制的输出数据:popen() writes output of command executed to cout
关于c++ - 设置来自系统 ("command"的变量) (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58259121/