C ++ Windows.h WriteFile函数

时间:2019-01-13 06:29:48

标签: c++ winapi writefile

我试图在控制台中显示正在运行的进程和当前时间的列表,并使用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;
}

1 个答案:

答案 0 :(得分:2)

使用OPEN_ALWAYS代替CREATE_ALWAYS,然后使用SetFilePointer将文件指针移到文件末尾。