Thanks Kerrek SB, I had seen people using popen() in various ways but wasn t sure if that was the route to pursue or not. With the help of the documentation and putting together parts of how other people were using it, I came up with this. This does what the question I wrote asked about specifically: importing the terminal response from the command "ls" into a vector of file names. However, each file name contains a newline character that I implicitly remove pushing back all but the last element of the string file into the 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 );
}
我正试图根据曼卡塞的建议,调整“阿里亚加二号”的阴道,以满足我的需求,这是我迄今为止所做的。 它是否像我这样看待? 我对此有明显错误或误解?
#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 and assignment not implemented; prevent their use by
// declaring private.
TerminalPipe( const file & ) ;
TerminalPipe & operator=( const file & ) ;
};
Then call it with this:
vector<string> dirFiles;
TerminalPipe pipe;
pipe.currentDirFiles( dirFiles );