【发布时间】:2019-01-13 06:29:47
【问题描述】:
我试图在控制台中显示正在运行的进程列表和当前时间,并使用 WriteFile 和 windows.h 函数将它们保存到文本文件中。如何在不使用 C++ 中的“freopen”的情况下有效地将输出流和“我的数据...”重定向到文本文件?
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
char temp;
HANDLE h = CreateFile("process.txt", // name of the file
GENERIC_WRITE, // open for writing
0, // sharing mode, none in this case
0, // use default security descriptor
CREATE_ALWAYS, // overwrite if exists
FILE_ATTRIBUTE_NORMAL,
0);
if (h)
{
std::cout << "CreateFile() succeeded\n";
CloseHandle(h);
}
else
{
std::cerr << "CreateFile() failed:" << GetLastError() << "\n";
}
time_t actualTime = chrono::system_clock::to_time_t(chrono::system_clock::now());
cout << ctime(&actualTime);
cout << "My data..." << endl;
PROCESSENTRY32 proc32;
HANDLE hSnapshot;
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
proc32.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnapshot, &proc32))
{
cout << proc32.szExeFile << endl;
while(Process32Next(hSnapshot, &proc32))
cout << proc32.szExeFile << endl;
}
WriteFile(HANDLE hFile,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED lpOverlapped
);
CloseHandle(hSnapshot);
system ("pause >nul");
return 0;
}
【问题讨论】:
-
为什么不使用
std::ofstream? -
所有进程枚举的东西与将输出重定向到文件有什么关系?它只是分散了手头的问题。请将代码缩减为minimal reproducible example。