Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
The CreateFile
function is a critical part of the Windows API, providing a versatile way to create or open files, directories, physical disks, volumes, consoles, and even communication resources such as pipes and mailslots. This function is essential for developers working with file I/O operations in Windows environments.
The CreateFile
function is used to create or open a file or I/O device. It returns a handle that can be used to access the object for various operations such as reading, writing, or configuring device settings.
HANDLE CreateFile(
LPCWSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile
);
GENERIC_READ
, GENERIC_WRITE
).FILE_SHARE_READ
).SECURITY_ATTRIBUTES
structure.CREATE_NEW
, OPEN_EXISTING
).FILE_ATTRIBUTE_NORMAL
).GENERIC_READ
access right.Here is a simple example of using CreateFile
to create a new file:
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hFile = CreateFile(
L"example.txt", // File name
GENERIC_WRITE, // Desired access
0, // Share mode
NULL, // Security attributes
CREATE_NEW, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL // Template file
);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Could not create file (error %d)\n", GetLastError());
return 1;
}
printf("File created successfully\n");
CloseHandle(hFile);
return 0;
}
#include <windows.h>
#include <stdio.h>
int main() {
HANDLE hFile = CreateFile(
L"example.txt", // File name
GENERIC_READ, // Desired access
FILE_SHARE_READ, // Share mode
NULL, // Security attributes
OPEN_EXISTING, // Creation disposition
FILE_ATTRIBUTE_NORMAL, // Flags and attributes
NULL // Template file
);
if (hFile == INVALID_HANDLE_VALUE) {
printf("Could not open file (error %d)\n", GetLastError());
return 1;
}
printf("File opened successfully\n");
CloseHandle(hFile);
return 0;
}
CreateFile
. If it returns INVALID_HANDLE_VALUE
, use GetLastError
to obtain more information about the failure.dwCreationDisposition
parameter to avoid unintentional data loss.CloseHandle
to free system resources.