Core File Operations
These APIs form the foundation for managing files and directories within the Windows operating system.
- CreateFile Creates or opens a file or device.
- ReadFile Reads data from a file or device.
- WriteFile Writes data to a file or device.
- CloseHandle Closes an open object handle.
- DeleteFile Deletes a file.
- MoveFile Moves an existing file or directory.
- CopyFile Copies an existing file to a new location.
Directory Management
Manage directories and their contents effectively with these APIs.
- CreateDirectory Creates a new directory.
- RemoveDirectory Removes an empty directory.
- FindFirstFile Begins the search for files in a specified directory.
- FindNextFile Continues a file search from a previous call to FindFirstFile.
- FindClose Closes a file search handle.
Advanced File Operations
Delve into more specialized functionalities for robust file handling.
- GetFileAttributes Retrieves attributes for a specified file or directory.
- SetFileAttributes Sets the attributes for a specified file or directory.
- GetFileInformationByHandle Retrieves various information about a file or directory specified by a handle.
- SetEndOfFile Sets the high-order word of the file size.
Example: Reading File Content
Here's a simple C++ code snippet demonstrating how to read content from a file using the Windows API:
#include <windows.h>
#include <iostream>
#include <vector>
int main() {
HANDLE hFile = CreateFile(L"example.txt", // File name
GENERIC_READ, // Access mode
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) {
std::cerr << "Error opening file: " << GetLastError() << std::endl;
return 1;
}
DWORD fileSize = GetFileSize(hFile, NULL);
if (fileSize == INVALID_FILE_SIZE) {
std::cerr << "Error getting file size: " << GetLastError() << std::endl;
CloseHandle(hFile);
return 1;
}
if (fileSize == 0) {
std::cout << "File is empty." << std::endl;
CloseHandle(hFile);
return 0;
}
std::vector<char> buffer(fileSize);
DWORD bytesRead;
if (!ReadFile(hFile, buffer.data(), fileSize, &bytesRead, NULL)) {
std::cerr << "Error reading file: " << GetLastError() << std::endl;
CloseHandle(hFile);
return 1;
}
std::cout.write(buffer.data(), bytesRead);
CloseHandle(hFile);
return 0;
}
For more detailed information, parameters, and return values, please refer to the specific API documentation linked above.