c++文件随机读写的方法
时间: 2023-08-07 20:07:56 浏览: 58
C++中可以使用文件流对象来实现文件的随机读写操作。具体步骤如下:
1. 包含头文件:
```cpp
#include <iostream>
#include <fstream>
```
2. 打开文件:
```cpp
std::fstream file("filename.txt", std::ios::in | std::ios::out);
if (!file) {
std::cerr << "Failed to open the file." << std::endl;
return -1;
}
```
3. 定位文件指针:
- 对于读操作,可以使用 `seekg()` 函数来定位读取位置:
```cpp
file.seekg(position, std::ios::beg); // 从文件开头定位到指定位置
file.seekg(position, std::ios::cur); // 从当前位置定位到指定位置
file.seekg(position, std::ios::end); // 从文件末尾定位到指定位置
```
- 对于写操作,可以使用 `seekp()` 函数来定位写入位置,用法与 `seekg()` 相同。
4. 读取数据:
```cpp
char buffer[100];
file.read(buffer, sizeof(buffer));
```
5. 写入数据:
```cpp
char buffer[] = "Hello, world!";
file.write(buffer, sizeof(buffer) - 1);
```
6. 关闭文件:
```cpp
file.close();
```
需要注意的是,文件指针的定位是基于字节的偏移量,可以根据需要选择不同的定位方式。另外,读取和写入操作的数据类型可以根据实际情况进行调整。