天天看点

C++程序调用cmd命令行 执行bat等应用(XP,WIN7差别)

调用bat文件或者exe 或者可执行的cmd命令。可以使用CreateProcess,WinExec。这里推荐使用CreateProcess。

因为官方文档说:Note  This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function.

具体代码:

头文件

#pragma once

class CRunBatXp

{

public:

CRunBatXp(void);

~CRunBatXp(void);

void RunBat();

bool TPFExcute(const char *cmd);

};

源文件:

#include "StdAfx.h"

#include "RunBatXp.h"

CRunBatXp::CRunBatXp(void)

{

}

CRunBatXp::~CRunBatXp(void)

{

}

void CRunBatXp::RunBat()

{

bool bret=false;

char szFilePath[_MAX_PATH]={0};

::GetModuleFileName(NULL, szFilePath, _MAX_PATH);

char *pStr=strrchr(szFilePath,'\\');

if (pStr)

{

*(pStr+1)=0x00;

}

std::string strpath=szFilePath;

strpath+="ISetup.bat";

//XP系统特别处理

strpath.insert(strpath.begin(),1,'\"');

strpath.append("\"");

//XP系统特别处理 end

UINT uret=0;

TPFExcute(strpath.c_str());

DEBUG_LOG("WinExec返回值:%d,error:%d",uret,GetLastError());

}

bool CRunBatXp::TPFExcute(const char *cmd)

{

STARTUPINFO s;

GetStartupInfo(&s);

s.cb = sizeof(s);

s.dwFlags =STARTF_USESHOWWINDOW; 

s.wShowWindow =SW_HIDE;

PROCESS_INFORMATION pi;

memset(&pi,0x00,sizeof(PROCESS_INFORMATION));

DWORD dwCreationFlags=0;

char szcmd[1024]={0};

strlcpy(szcmd,cmd,1024);

if(CreateProcess(NULL,szcmd,NULL,NULL,TRUE,dwCreationFlags,NULL,NULL,&s,&pi))

WaitForSingleObject(pi.hProcess ,INFINITE); 

return true;

}

else

{

DEBUG_LOG("执行%s命令失败",szcmd);

return false;

}

}

注意事项:

win7下的执行命令直接输入字符创串即可,c:\xx.bat

winxp下字符串需要被双引号包围,"c:\xx.bat"

这也是windows的坑吧