Reading terminal response to bash commands into c++ variable -


does know of way read in terminal output bash commands c++? example, entering "ls" terminal returns file names in current directory, there way perhaps import these names string or char array or something? have been looking @ fork(), exec(), , pipe(). attempting open pipe communication between child (system commands entered here) , parent (output read in here) have been thoroughly unsuccessful. ideas?

thanks kerrek sb, had seen people using popen() in various ways wasn't sure if route pursue or not. of documentation , putting parts of how other people using it, came this. question wrote asked specifically: importing terminal response command "ls" vector of file names. however, each file name contains newline character implicitly remove pushing last element of string file vector.

void currentdirfiles( vector<string> & filesaddress ) {      file * pipe = popen( "ls", "r" );     char buffer[1000];     string file;     vector<string> files;     while ( fgets( buffer, sizeof( buffer ), pipe ) != null )     {         file = buffer;         files.push_back( file.substr( 0, file.size() - 1 ) );     }     pclose( pipe );     filesaddress.swap( files ); } 

i trying adapt wikipedia raii example fit needs per recommendations of mankarse, , have far. on right track? obvious mistakes or misunderstandings have on this?

 #include <cstdio>  // exceptions class file_error { } ; class open_error : public file_error { } ; class close_error : public file_error { } ; class read_error : public file_error { } ;  class terminalpipe {    public:        terminalpipe():            pipehandle(std::popen("ls", "r"))            {                if( pipehandle == null )                    throw open_error() ;            }      ~terminalpipe()     {         std::pclose(pipehandle) ;     }      void currentdirfiles( vector<string> & filesaddress )     {        char buffer[1000];        string file;        vector<string> files;        while ( fgets( buffer, sizeof( buffer ), pipehandle ) != null )        {            if( std::ferror( pipehandle ) )                 throw read_error();            else            {                file = buffer;                files.push_back( file.substr( 0, file.size() - 1 ) );            }        }     }     private:         std::file* pipehandle ;         // copy , assignment not implemented; prevent use         // declaring private.         terminalpipe( const file & ) ;         terminalpipe & operator=( const file & ) ; }; 

then call this:

vector<string> dirfiles; terminalpipe pipe;     pipe.currentdirfiles( dirfiles ); 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -