我将在资源项目中嵌入批处理文件,我希望在控制台中运行批处理脚本。
如何运行嵌入脚本
#include "stdafx.h"
#include "iostream"
#include "conio.h"
#define WINDOWS_LEAN_AND_MEAN
#include <Windows.h>
std::wstring GetEnvString()
{
wchar_t* env = GetEnvironmentStrings();
if (!env)
abort();
const wchar_t* var = env;
size_t totallen = 0;
size_t len;
while ((len = wcslen(var)) > 0)
{
totallen += len + 1;
var += len + 1;
}
std::wstring result(env, totallen);
FreeEnvironmentStrings(env);
return result;
}
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
std::wstring env = GetEnvString();
env += L"myvar=boo";
env.push_back('\0'); // somewhat awkward way to embed a null-terminator
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
wchar_t cmdline[] = L"cmd.exe /C f.bat";
if (!CreateProcess(NULL, cmdline, NULL, NULL, false, CREATE_UNICODE_ENVIRONMENT,
(LPVOID)env.c_str(), NULL, &si, &pi))
{
std::cout << GetLastError();
abort();
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
getch();
}
embed batch script file in c++ console
这是我想从资源项目运行的位置批处理文件
wchar_t cmdline[] = L"cmd.exe /C f.bat";
答案 0 :(得分:0)
您可以使用std::system:
#include <fstream>
#include <cstdlib>
int main()
{
std::ofstream fl("test.bat");
fl << "@echo off\n"
"echo testing batch.\n"
"cd c:\\windows\n"
"dir";
fl.close();
system("test.bat");
}
使用系统,您只需执行命令,就无法获得输出。要获得输出,您可以将输出从.bat重定向到文件,或者您可以使用popen并且可以像常规文件一样读取输出。请注意,popen仅为stdout提供stdout,但您可以将stderr重定向到stdout:
#include <cstdlib>
#include <cstdio>
int main()
{
FILE *p = _popen("missing_executable.exe 2>&1", "r");
if (p)
{
char data[1024];
int n = 0;
while (fgets(data, 1024, p))
printf("%02d: %s", ++n, data);
int ret = _pclose(p);
printf("process return: %d\n", ret);
}
else
{
printf("failed to popen\n");
}
}
这是输出:
01: 'missing_executable.exe' is not recognized as an internal or external command,
02: operable program or batch file.
process return: 1
Press any key to continue . . .
如果要将.bat文件存储为Windows可执行文件中的资源,可以使用FindResource / LoadResource / LockResource从可执行文件中获取实际的bat文件。像这样:
HMODULE module = GetModuleHandle(NULL);
// update with your RESOURCE_ID and RESOURCE_TYPE.
HRSRC res = FindResource(module, MAKEINTRESOURCE(RESOURCE_ID), RESOURCE_TYPE);
HGLOBAL resMem = LoadResource(module, res);
DWORD resSize = SizeofResource(module, res);
LPVOID resPtr = LockResource(resMem);
char *bytes = new char[resSize];
memcpy(bytes, resPtr, resSize);
现在您可以将字节保存到文件并使用std::system或popen
执行