c++ - 设置来自系统 ("command"的变量) (C++)

标签 c++

在此之前:我搜索了类似的问题,但似乎没有一个解决方案适合我。另外,我是 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/

相关文章:

c++ - C++ 中的对象分配

c++ - 通过 OpenSSL (c++) 以 XML (w3c) 格式保存 RSA 公钥和私钥

c++ - 如何从十六进制值缓冲区渲染矩形 SDL2 纹理?

C++ 捕获所有异常

C++:ptr_container 比较

c++ - 实现nd数组时如何处理C++中的 "out of range"异常

c++ - 以 QMap 和 QDateTime 为键的问题

c++ - 在 MessageBoxW c++ 中显示一个变量

c++ - 当我们在两个结构上使用 = 运算符时,它会做什么?

c++ - 如何减少 C++ 中多重集中元素的数量?