温馨提示×

C++函数CreateFileReadFileWriteFile怎么使用

c++
小亿
104
2023-08-17 21:13:29
栏目: 编程语言

函数CreateFile、ReadFile和WriteFile是Windows平台的API函数,用于创建文件、读取文件和写入文件。下面是使用这些函数的示例代码:

  1. 创建文件(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;
}

上述代码创建了一个名为test.txt的文件。

  1. 读取文件(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;
}

上述代码打开了名为test.txt的文件,并将文件内容读取到一个缓冲区中。

  1. 写入文件(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;
}

上述代码打开了名为test.txt的文件,并将字符串"Hello, World!"写入文件中。

请注意,在使用这些函数之前,需要包含Windows.h头文件,并链接Windows库。此外,还需要处理错误情况,以确保函数调用成功。

0