我怎么能系统功能的输出存储为一个字符串

我怎么能系统功能的输出存储为一个字符串

问题描述:

虽然我尝试以下方法:我怎么能系统功能的输出存储为一个字符串

system("ifconfig -a | grep inet | " 
      "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' " 
      " > address.txt") ; 

我得到的输出文件。我如何将输出分配给一个变量。

+4

使用'popen',而不是'system',然后从标准输入读取到您的字符串 – 2010-10-22 15:18:51

+1

@保罗的R - 这是比我更好的主意,海事组织 – 2010-10-22 15:41:41

+0

@Steve:感谢 - 我将做它一个答案,但我对Windows不熟悉是否有'popen'。 – 2010-10-22 16:24:58

编辑:在@Paul R的评论中推荐的最佳方法是使用_popen并从stdin中读取命令输出。该MSDN页面上有示例代码。

ORIGINAL省力:

一种选择是创建一个使用tmpnam_s一个临时文件,还有写你的输出,而不是硬编码的文件名,然后读取它从文件恢复到std::string,删除临时一旦你完成文件。根据MSDN的示例代码:

#include <stdio.h> 
#include <stdlib.h> 
#include <fstream> 
#include <sstream> 

int main(void) 
{ 
    char name1[L_tmpnam_s]; 
    errno_t err; 

    err = tmpnam_s(name1, L_tmpnam_s); 
    if (err) 
    { 
     printf("Error occurred creating unique filename.\n"); 
     exit(1); 
    } 
    stringstream command; 
    command << "ifconfig -a | grep inet | " << 
      "sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' " << 
      " > " << (const char*)name1; 
    system(command.str().c_str()); 

    { 
    ifstream resultFile((const char*)name1); 
    string resultStr; 
    resultFile >> resultStr; 

    cout << resultStr; 
    } 
    ::remove(name1); 
} 

该代码使用CRT比我平时会,但你似乎有您希望使用依赖于这一种方法。