C++ File I/O: CreateFile, ReadFile & WriteFile
In C++, you can use the functions CreateFile, ReadFile, and WriteFile to create, read, and write files.
- Create a file:
HANDLE hFile = CreateFile(TEXT("example.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
// 文件创建失败
// 处理错误
}
- Write to file.
DWORD dwBytesWritten;
char data[] = "Hello, World!";
if (!WriteFile(hFile, data, sizeof(data), &dwBytesWritten, NULL)) {
// 写入文件失败
// 处理错误
}
- Read the file.
DWORD dwBytesRead;
char buffer[100];
if (!ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL)) {
// 读取文件失败
// 处理错误
} else {
// 输出读取的内容
cout << buffer << endl;
}
You need to include the Windows.h header file to use these functions. Also, remember to close the file handle after using the file.
CloseHandle(hFile);