Reading from console output in C++ [duplicate]

折月煮酒 提交于 2020-12-13 07:13:13

问题


I am trying to make a software in "C++" for linux that reads the console output of the ldd console application. I would like to know if there is any '.so' library in the shared files of the system or another way of purely read the output of this command in console. Here is an example of the output of the command:

ldd ./echo
    linux-vdso.so.1 =>  (0x00007fffdd8da000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe95daf4000)
    /lib64/ld-linux-x86-64.so.2 (0x000055a6179a6000)

This command print a list of the dependencies and the locations that has a binary file. I want to save this output in a variable or something else for being formatted later.


回答1:


For that, usually one has to run the program we want to get output from with a pipe function: popen().

string data;
FILE * stream;
const int max_buffer = 256;
char buffer[max_buffer];

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

This way you can get the output of ldd and do whatever you like with it.

There is other question you may find useful:

popen() writes output of command executed to cout



来源:https://stackoverflow.com/questions/49430983/reading-from-console-output-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!