【发布时间】:2009-10-28 10:14:57
【问题描述】:
我想做一些 C++ 程序,我在这里使用函数 popen 将命令发送到 Unix 的命令行。它工作正常,但是当我调用cd directory 时,目录不会改变。在完成脚本目录路径更改后,当我尝试在某些脚本中运行 cd directory 时,我认为它是相同的。所以,我必须像 . ./script.sh 而不是 ./sript.sh 那样运行脚本,但是如何使用 popen 函数来做到这一点?我试图在popen 的第一个参数之前添加". ",但运行". ls" 会出错。
代码:
cout << "@ Command from " << session->target().full() << ": " << message.body() << endl;
//cout << "Prisla zprava" << endl;
//m_session->send( "Hello World", "No Subject" );
//system( message.body().c_str() );
//if ( message.body() == "" )
FILE* outp;
char buffer[100];
string outps = "";
outp = popen( message.body().c_str(), "r" );
while ( !feof(outp) )
{
fgets( buffer, 100, outp );
outps = outps + buffer;
}
pclose(outp);
cout << "& Output from command: " << outps << endl;
m_session->send( outps.c_str(), "Output" );
在message.body(); 中是string,我想运行它(我从XMPP 收到这个)。当string 是例如"ls" 时,它返回string 以及实际目录中的文件列表。但是当消息是"cd directory" 时,什么都不会发生,比如尝试在脚本中更改目录。
【问题讨论】:
-
你如何更改目录? (代码示例可能很有用)
-
程序中如何更改目录?
-
我正在使用它的示例代码。在这里我尝试添加“.”,就像在运行脚本时一样,但是“.ls”会出错。没有“.”,目录不会改变。