How do I read the results of a system() call in C++?

后端 未结 9 923
醉梦人生
醉梦人生 2020-12-17 06:44

I\'m using the following code to try to read the results of a df command in Linux using popen.

#include  // file an         


        
9条回答
  •  独厮守ぢ
    2020-12-17 07:26

    You're making this all too hard. popen(3) returns a regular old FILE * for a standard pipe file, which is to say, newline terminated records. You can read it with very high efficiency by using fgets(3) like so in C:

    #include 
    char bfr[BUFSIZ] ;
    FILE * fp;
    // ...
    if((fp=popen("/bin/df", "r")) ==NULL) {
       // error processing and return
    }
    // ...
    while(fgets(bfr,BUFSIZ,fp) != NULL){
       // process a line
    }
    

    In C++ it's even easier --

    #include 
    #include 
    #include 
    
    FILE * fp ;
    
    if((fp= popen("/bin/df","r")) == NULL) {
        // error processing and exit
    }
    
    ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
    
    string s;
    while (! ins.eof()){
        getline(ins,s);
        // do something
    }
    

    There's some more error handling there, but that's the idea. The point is that you treat the FILE * from popen just like any FILE *, and read it line by line.

提交回复
热议问题