函數(shù)CreateFile、ReadFile和WriteFile是Windows平臺(tái)的API函數(shù),用于創(chuàng)建文件、讀取文件和寫(xiě)入文件。下面是使用這些函數(shù)的示例代碼:
- 創(chuàng)建文件(CreateFile):
#include <Windows.h>
int main() {
HANDLE hFile = CreateFile("test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return GetLastError();
}
CloseHandle(hFile);
return 0;
}
上述代碼創(chuàng)建了一個(gè)名為test.txt的文件。
- 讀取文件(ReadFile):
#include <Windows.h>
int main() {
HANDLE hFile = CreateFile("test.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return GetLastError();
}
char buffer[100];
DWORD bytesRead;
if (ReadFile(hFile, buffer, sizeof(buffer), &bytesRead, NULL)) {
buffer[bytesRead] = '\0';
printf("%s", buffer);
} else {
printf("ReadFile failed with error %d\n", GetLastError());
}
CloseHandle(hFile);
return 0;
}
上述代碼打開(kāi)了名為test.txt的文件,并將文件內(nèi)容讀取到一個(gè)緩沖區(qū)中。
- 寫(xiě)入文件(WriteFile):
#include <Windows.h>
int main() {
HANDLE hFile = CreateFile("test.txt", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return GetLastError();
}
char buffer[] = "Hello, World!";
DWORD bytesWritten;
if (WriteFile(hFile, buffer, sizeof(buffer) - 1, &bytesWritten, NULL)) {
printf("WriteFile wrote %d bytes\n", bytesWritten);
} else {
printf("WriteFile failed with error %d\n", GetLastError());
}
CloseHandle(hFile);
return 0;
}
上述代碼打開(kāi)了名為test.txt的文件,并將字符串"Hello, World!"寫(xiě)入文件中。
請(qǐng)注意,在使用這些函數(shù)之前,需要包含Windows.h頭文件,并鏈接Windows庫(kù)。此外,還需要處理錯(cuò)誤情況,以確保函數(shù)調(diào)用成功。