【问题标题】:How to get the return value between two different c++ program using Visual Studio 2005如何使用 Visual Studio 2005 在两个不同的 c++ 程序之间获取返回值
【发布时间】:2015-05-01 07:13:01
【问题描述】:

现在,我有两个程序 A 和 B。程序 A 使用system() 执行程序 B。

但是,程序B使用写文件的方式返回它的执行结果。

程序A是否有更好的方法来获取程序B的返回值?

例如

在程序 A 中

int main(){
    system("B.exe");
    readFile(finePath);
    //do something
    return 0;
}

在程序 B 中

int main(){
    char temp[1024];
    //do something
    writeFile(temp);
    return 0;
}

【问题讨论】:

  • 向我们展示您的尝试(简约代码)。
  • stackoverflow.com/questions/3470215/… - 也许你会在那里找到一些有用的信息
  • “返回值”这个词对我来说有点混乱,所以只是为了确定。您不是在询问程序 B 中的“状态代码”,对吧?问题是关于获得 B 产生的各种结果/输出,对吗?因为“状态码”通常由 system() 直接返回。见cplusplus.com/reference/cstdlib/system
  • 我更新了一个例子。请帮帮我。

标签: c++ c visual-studio


【解决方案1】:

管道是一种相对简单的跨平台方法,无需在各处创建临时文件,也无需处理这样做可能产生的其他问题。

static string pcommand(const string& cmd) 
{
    FILE* stream = _popen(cmd.c_str(), "r");
    string data;
    if (stream) 
    {
        while (!feof(stream))
        {
            const int buffer_size = 256;
            char buffer[buffer_size];
            if (fgets(buffer, buffer_size, stream))
                data.append(buffer);
        }
        _pclose(stream);
    }
    return data;
}

int main()
{
    string 'str' = pcommand("dir");
    // 'str' now contains the results sent to stdout
}

【讨论】:

【解决方案2】:

方法一。

尝试使用ERRORLEVEL 系统变量来检查任何正在运行的程序的返回值。

注意:
ERRORLEVEL 是一个系统变量,所以将其用作such... ;)

方法二。

您可以使用Process.ExitCode 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多