[英]can run C++ code from command line but not from debug mode in visual studio
[英]Launch command line window in hidden mode from a C++ code and read output log file
在 windows 機器上,我的代碼運行 ShellExecute 以啟動 abc.exe,並使用 SW_HIDE 作為最后一個參數來隱藏啟動的命令行 window。 這可以根據需要運行良好。
std::string torun = "/c abc.exe >abc.log";
HINSTANCE retVal = ShellExecute(NULL, _T("open"), _T("cmd"), std::wstring(torun.begin(), torun.end()).c_str(), NULL, SW_HIDE);
我的問題是即使寫入成功,也無法訪問捕獲 abc.exe 的 output 的 abc.log。 下面的代碼返回“文件不存在”。
std::string filename = "abc.log";
if (_access(filename.c_str(), 0) == -1)
std::cout<<"file does not exist";
else
std::cout<<"file exists";
在檢查它是否存在后,我需要閱讀此日志文件的內容。 下面的代碼還返回“文件不存在”。
ifstream fin;
fin.open("abc.log");
if(fin)
std::cout<<"file exists";
else
std::cout<<"file does not exist";
有一些權限問題嗎? 我有兩個需求 - 在命令行 window 上啟動 abc.exe,它隱藏或在所有打開的 windows 后面運行,並且還能夠讀取 abc.log。 感謝幫助。
您需要等待子進程完成:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
#include <shellapi.h>
...
SHELLEXECUTEINFO sei = { sizeof(sei), SEE_MASK_NOCLOSEPROCESS|SEE_MASK_FLAG_NO_UI };
sei.lpFile = TEXT("cmd.exe");
sei.lpParameters = TEXT("/C ping localhost > abc.log"); // Command that takes a while to complete
sei.nShow = SW_HIDE;
if (ShellExecuteEx(&sei))
{
if (sei.hProcess)
{
WaitForSingleObject(sei.hProcess, INFINITE);
CloseHandle(sei.hProcess);
FILE*file = fopen("abc.log", "r");
if (file)
{
char buf[1337];
size_t cb = fread(buf, 1, sizeof(buf), file);
if (cb)
{
buf[min(cb, sizeof(buf)-1)] = '\0';
MessageBoxA(NULL, buf, "stdout started with", 0);
}
fclose(file);
}
}
}
這仍然有點懶惰,從子進程讀取標准輸出的最佳方法是使用管道調用CreateProcess
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.