Skip to content

Instantly share code, notes, and snippets.

@snipsnipsnip
Created September 22, 2012 09:57
Show Gist options
  • Save snipsnipsnip/3765716 to your computer and use it in GitHub Desktop.
Save snipsnipsnip/3765716 to your computer and use it in GitHub Desktop.
batter.cpp
#include <windows.h>
#include <stdio.h>
#include <string>
/*
batter.c from http://mattn.kaoriya.net/software/windows/20120920154016.htm
*/
static int emsg() {
char* p = NULL;
DWORD err = GetLastError();
if (err == 0) { return 0; }
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, err, 0, (LPTSTR)(&p), 0, NULL);
fputs(p, stderr);
LocalFree((LPVOID)p);
return err;
}
int main(int argc, char **argv) {
std::string t(GetCommandLine());
size_t icmd = t.find_first_of(t.at(0) == '"' ? '"' : ' ', 1);
if (icmd == std::string::npos) {
icmd = t.size();
}
if (t.size() > 4 && _strnicmp(t.data() + (icmd - 4), ".exe", 4) == 0) {
t.replace(icmd - 3, 3, "bat");
} else {
char *comspec = getenv("COMSPEC");
std::string b(comspec ? comspec : "CMD");
b.append(" /c call ").append(t, 0, icmd).append(".bat").append(t, icmd, t.size() - icmd).swap(t);
}
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
int r;
si.cb = sizeof(si);
if (!CreateProcess(
NULL, (LPSTR)t.c_str(), NULL, NULL, TRUE,
CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_PROCESS_GROUP,
NULL, NULL, &si, &pi)) {
r = emsg();
} else {
CloseHandle(pi.hThread);
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED) {
r = emsg();
} else {
DWORD code = 0;
if (!GetExitCodeProcess(pi.hProcess, &code)) {
r = emsg();
} else {
r = (int) code;
CloseHandle(pi.hProcess);
}
}
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment