开发者

How to store the system command output in a variable?

I am executing a system() function which returns me a file name. Now I dont want to display the output on the screen(ie the fil开发者_如何学Goename) or pipe to a newfile. I just want to store it in a variable. is that possible? if so, how? thanks


A single filename? Yes. That is certainly possible, but not using system().

Use popen(). This is available in c and c++, you've tagged your question with both but are probably going to code in one or the other.

Here's an example in C:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    FILE *fpipe;
    char *command = "ls";
    char c = 0;

    if (0 == (fpipe = (FILE*)popen(command, "r")))
    {
        perror("popen() failed.");
        exit(EXIT_FAILURE);
    }

    while (fread(&c, sizeof c, 1, fpipe))
    {
        printf("%c", c);
    }

    pclose(fpipe);

    return EXIT_SUCCESS;
}


Well,There is one more easy way by which you can store command output in a file which is called redirection method. I think redirection is quite easy and It will be useful in your case.

so For Example this is my code in c++

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int main(){
   system("ls -l >> a.text");
  return 0;
}

Here redirection sign easily redirect all output of that command into a.text file.


You can use popen(3) and read from that file.

FILE *popen(const char *command, const char *type);

So basically you run your command and then read from the FILE returned. popen(3) works just like system (invokes the shell) so you should be able to run anything with it.


Here is my C++ implementation, which redirects system() stdout to a logging system. It uses GNU libc's getline(). It will throw an exception if it can't run the command, but will not throw if the command runs with non-zero status.

void infoLogger(const std::string& line); // DIY logger.


int LoggedSystem(const string& prefix, const string& cmd)
{
    infoLogger(cmd);
    FILE* fpipe = popen(cmd.c_str(), "r");
    if (fpipe == NULL)
        throw std::runtime_error(string("Can't run ") + cmd);
    char* lineptr;
    size_t n;
    ssize_t s;
    do {
        lineptr = NULL;
        s = getline(&lineptr, &n, fpipe);
        if (s > 0 && lineptr != NULL) {
            if (lineptr[s - 1] == '\n')
                lineptr[--s  ] = 0;
            if (lineptr[s - 1] == '\r')
                lineptr[--s  ] = 0;
            infoLogger(prefix + lineptr);
        }
        if (lineptr != NULL)
            free(lineptr);
    } while (s > 0);
    int status = pclose(fpipe);
    infoLogger(String::Format("Status:%d", status));
    return status;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜