我试图在控制台中显示正在运行的进程和当前时间的列表,并使用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;
}
最佳答案
使用OPEN_ALWAYS而不是CREATE_ALWAYS,然后使用SetFilePointer将文件指针移动到文件末尾。
关于c++ - C++ Windows.h WriteFile函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54166597/