建立一個檔案並寫入它

此示例建立一個名為“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 參考: