CreateFileA function

The CreateFileA function (and the wide-character version, CreateFileW) creates or opens a file or I/O device.

Syntax

HANDLE CreateFileA(
  LPCSTR lpFileName,
  DWORD dwDesiredAccess,
  DWORD dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD dwCreationDisposition,
  DWORD dwFlagsAndAttributes,
  HANDLE hTemplateFile
);

Parameters

Return Value

If the function succeeds, the return value is an open handle to the specified file or device. If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

Remarks

The CreateFile function can return a handle to a regular file, a named pipe, a mail slot, a communications resource, a disk, or a console buffer.

To create or open a file, specify a file name for the lpFileName parameter. The file must be located on the file system specified by the path.

If the lpFileName parameter specifies a file that does not exist, and dwCreationDisposition is set to CREATE_ALWAYS or OPEN_ALWAYS, the function creates the file. If the file exists, and dwCreationDisposition is set to CREATE_ALWAYS or OPEN_ALWAYS, the function overwrites the existing file.

When opening a file, the dwShareMode parameter determines whether another thread can access the file while it is being opened.

Example

#include <windows.h> #include <iostream> int main() { HANDLE hFile; const char* filename = "my_test_file.txt"; hFile = CreateFileA( filename, // File name GENERIC_WRITE, // Desired access 0, // Share mode NULL, // Security attributes CREATE_ALWAYS, // Creation disposition FILE_ATTRIBUTE_NORMAL, // Flags and attributes NULL); // Template file if (hFile == INVALID_HANDLE_VALUE) { std::cerr << "Failed to create or open file. Error: " << GetLastError() << std::endl; return 1; } // Write to the file (example) char data[] = "Hello, Windows API!"; DWORD bytesWritten; if (!WriteFile(hFile, data, sizeof(data) - 1, &bytesWritten, NULL)) { std::cerr << "Failed to write to file. Error: " << GetLastError() << std::endl; } else { std::cout << "Successfully wrote " << bytesWritten << " bytes to " << filename << std::endl; } CloseHandle(hFile); return 0; }