用popen读取命令行输出不返回数据

时间:2019-05-19 13:47:46

标签: c++ command-line popen

我正在运行ImageMagick命令,将图像转换为PPM格式。然后,我想从命令行读取输出,看看是否成功。

我查找了popen命令,并尝试用我的代码实现它:

std::string Image::loadImage(std::string baseFileAddress) {

struct stat statBuffer;                                     //check if file exists
if (stat (baseFileAddress.c_str(), &statBuffer) == 0) {
    std::cout << "File found.\n";
} else {
    std::cout << "Error! File for processing not found.\n";
    exit;
}

std::string data;
FILE * stream;
const int max_buffer = 256;
char buffer[max_buffer];
std::string cmd = "convert -compress none " + baseFileAddress + " " + baseFileAddress + "_new.ppm";

stream = popen(cmd.c_str(), "r");
if (stream) {
    while (!feof(stream)) {
        if (fgets(buffer, max_buffer, stream) != NULL) {
            data.append(buffer);
        }
    }
    pclose(stream);
}
std::cout << data;
return data;
}

运行命令后,输出将打印到命令行,但是,数据不打印任何内容,当我希望它包含命令的输出时,结果为空字符串。

0 个答案:

没有答案