popen函数我用到这样一个函数来在c中调用cmd命令int execmd(char* cmd,char* result) {char buffer[128]/
popen函数
我用到这样一个函数来在c中调用cmd命令
int execmd(char* cmd,char* result) {
char buffer[128]; //定义缓冲区
FILE* pipe = _popen(cmd, "r"); //打开管道,并执行命令
if (!pipe)
return 0; //返回0表示运行失败
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe)){ //将管道输出到result中
strcat(result,buffer);
}
}
_pclose(pipe); //关闭管道
return 1; //返回1表示运行成功
}
这个函数在控制台应用程序中成功执行,在MFC中FILE* pipe = _popen(cmd, "r"); 的pipe返回为NULL请问为啥?不能在MFC中使用?
[解决办法]
用GetLastError()查看返回码是啥
[解决办法]
可以先试试以下的例子,不行的话用_wpopen函数替换试试看:
// crt_popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char psBuffer[128];
FILE *pPipe;
/* Run DIR so that it writes its output to a pipe. Open this
* pipe with read text attribute so that we can read it
* like a text file.
*/
if( (pPipe = _popen( "dir *.c /on /p", "rt" )) == NULL )
exit( 1 );
/* Read pipe until end of file, or an error occurs. */
while(fgets(psBuffer, 128, pPipe))
{
printf(psBuffer);
}
/* Close pipe and print return value of pPipe. */
if (feof( pPipe))
{
printf( "\nProcess returned %d\n", _pclose( pPipe ) );
}
else
{
printf( "Error: Failed to read the pipe to the end.\n");
}
}
[解决办法]
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe)){ //将管道输出到result中
strcat(result,buffer);
}
}
典型编码错误。
