gpt4 book ai didi

C++ windows.h WriteFile 函数

转载 作者:行者123 更新时间:2023-11-28 01:25:16 25 4
gpt4 key购买 nike

我试图在控制台中显示正在运行的进程列表和当前时间,并使用 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++ windows.h WriteFile 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54166597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com