创建一个文件并写入它

此示例创建一个名为“NewFile.txt”的新文件,然后写入 Hello World! 它的身体。如果文件已存在,则 CreateFile 将失败,并且不会写入任何数据。如果你不希望该函数在文件已存在时失败,请参阅 CreateFile 文档中dwCreationDisposition 参数。

#include <Windows.h>
#include <string>

int main()
{
   // Open a handle to the file
   HANDLE hFile = CreateFile(
      L"C:\\NewFile.txt",     // Filename
      GENERIC_WRITE,          // Desired access
      FILE_SHARE_READ,        // Share mode
      NULL,                   // Security attributes
      CREATE_NEW,             // Creates a new file, only if it doesn't already exist
      FILE_ATTRIBUTE_NORMAL,  // Flags and attributes
      NULL);                  // Template file handle

   if (hFile == INVALID_HANDLE_VALUE)
   {
      // Failed to open/create file
      return 2;
   }

   // Write data to the file
   std::string strText = "Hello World!"; // For C use LPSTR (char*) or LPWSTR (wchar_t*)
   DWORD bytesWritten;
   WriteFile(
      hFile,            // Handle to the file
      strText.c_str(),  // Buffer to write
      strText.size(),   // Buffer size
      &bytesWritten,    // Bytes written
      nullptr);         // Overlapped

   // Close the handle once we don't need it.
   CloseHandle(hFile);
}

API 参考: