How can I run an external program from C and parse its output?

后端 未结 8 964
死守一世寂寞
死守一世寂寞 2020-11-22 04:18

I\'ve got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same pr

相关标签:
8条回答
  • 2020-11-22 04:45
    //execute external process and read exactly binary or text output
    //can read image from Zip file for example
    string run(const char* cmd){
        FILE* pipe = popen(cmd, "r");
        if (!pipe) return "ERROR";
        char buffer[262144];
        string data;
        string result;
        int dist=0;
        int size;
        //TIME_START
        while(!feof(pipe)) {
            size=(int)fread(buffer,1,262144, pipe); //cout<<buffer<<" size="<<size<<endl;
            data.resize(data.size()+size);
            memcpy(&data[dist],buffer,size);
            dist+=size;
        }
        //TIME_PRINT_
        pclose(pipe);
        return data;
    }
    
    0 讨论(0)
  • 2020-11-22 04:47

    You can use system() as in:

    system("ls song > song.txt");
    

    where ls is the command name for listing the contents of the folder song and song is a folder in the current directory. Resulting file song.txt will be created in the current directory.

    0 讨论(0)
提交回复
热议问题