windows下执行exe ,获得cmd中输出内容

本文介绍了一种通过创建管道并利用ffmpeg工具获取文件时长的方法。具体实现中,使用了C++语言,并通过创建子进程运行命令行工具,将标准输出重定向到管道中读取,最终解析出文件的时长。

主要原理是:利用管道重定向输出到buffer中


BOOL CRecording::GetFileDuration(wstring strFilePath,wstring strDuration)
{
wchar_t exeFullPath[MAX_PATH]={0}; 
GetModuleFileName(NULL,exeFullPath,MAX_PATH);  
wstring strExeFullPath = exeFullPath;
int exePos = strExeFullPath.find_last_of(L"\\");
strExeFullPath = strExeFullPath.substr(0,exePos)+L"\\jyt_ffmpeg.exe";


SECURITY_ATTRIBUTES sa;
HANDLE hRead,hWrite;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0)) 
{
return FALSE;



wchar_t command[1024];  
swprintf_s(command,1024,L"%s%s%s%s",L"Cmd.exe /C ",strExeFullPath.c_str(),L" -i ",strFilePath.c_str());


STARTUPINFO si;
PROCESS_INFORMATION pi; 
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si); 
si.hStdError = hWrite;            //把创建进程的标准错误输出重定向到管道输入
si.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
//关键步骤,CreateProcess函数参数意义请查阅MSDN
if (!CreateProcess(NULL, command,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) 
{
CloseHandle(hWrite);
CloseHandle(hRead);
return FALSE;
}
CloseHandle(hWrite);
char buffer[4095] = {0};       //用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
DWORD bytesRead; 
//FILE* pfile = fopen("c:/00.txt","w+");
while (true) 
{
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
break;
//fwrite(buffer,1,strlen(buffer),pfile);
string str = buffer;
CCommonInterface comm;
wstring strW = comm.AnsiToU((char*)str.c_str());
wstring durStr = L"Duration: ";
int pos = strW.find(durStr.c_str());
if (pos>0){
pos += durStr.length();
strW = strW.substr(pos,8);
string strAnsi = comm.UtoAnsi(strW.c_str());
//fwrite(strAnsi.c_str(),1,strlen(strAnsi.c_str()),pfile);
}
}
//fclose(pfile);
CloseHandle(hRead); 
return TRUE;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值