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的坑吧


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值