函数CreateFile、ReadFile和WriteFile是windows平台的api函数,用于创建文件、读取文件和写入文件。下
函数CreateFile、ReadFile和WriteFile是windows平台的api函数,用于创建文件、读取文件和写入文件。下面是使用这些函数的示例代码:
1. 创建文件(CreateFile):
```cpp
#include
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的文件。
2. 读取文件(ReadFile):
```cpp
#include
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的文件,并将文件内容读取到一个缓冲区中。
3. 写入文件(WriteFile):
```cpp
#include
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库。此外,还需要处理错误情况,以确保函数调用成功。
--结束END--
本文标题: C++函数CreateFileReadFileWriteFile怎么使用
本文链接: https://www.lsjlt.com/news/373454.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0