问题描述
虽然我尝试了以下操作:
While I try the following:
system( "ifconfig -a | grep inet | "
"sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
" > address.txt" ) ;
我正在获取文件中的输出.如何将输出分配给变量.
I am getting the output in a file. How can I assign the out put to a variable.
推荐答案
按照@Paul R 的评论中的建议执行此操作的最佳方法是使用 _popen 并读取 stdin
的命令输出.该 MSDN 页面上有示例代码.
the best way to do this as recommended in @Paul R's comment, is to use _popen and read in the command output from stdin
. There is sample code at that MSDN page.
最初的努力:
一种选择是使用 tmpnam_s
创建一个临时文件,在那里写入输出而不是硬编码文件名,然后从文件中将其读回 std::字符串
,完成后删除临时文件.基于 MSDN 示例代码:
One option would be to create a temp file using tmpnam_s
, write your output there instead of hard-coding the filename, and then read it back from the file into a std::string
,deleting the temp file once you are done. Based on the MSDN sample code:
#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 的次数比我平时多,但您似乎希望使用依赖于此的方法.
This code uses the CRT more than I would usually, but you seem to have a methodology you wish to use that relies on this.
这篇关于如何将系统函数的输出存储到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!