C++使用ifstream.read()读二进制文件,并返回读取的buf的大小
时间: 2024-05-03 15:18:51 浏览: 150
FileManage.rar
使用`ifstream.read()`读取二进制文件可以按照以下步骤进行:
1. 打开二进制文件并创建`ifstream`对象:
```c++
ifstream file("binary_file.bin", ios::in | ios::binary);
```
2. 检查文件是否打开成功:
```c++
if (!file.is_open()) {
cout << "Failed to open file!" << endl;
return -1;
}
```
3. 定义一个缓冲区并分配内存:
```c++
const int BUF_SIZE = 1024;
char* buf = new char[BUF_SIZE];
```
4. 调用`read()`方法读取二进制文件:
```c++
file.read(buf, BUF_SIZE);
```
5. 检查`read()`方法是否成功读取文件:
```c++
if (!file.good()) {
cout << "Failed to read file!" << endl;
return -1;
}
```
6. 获取读取的`buf`的大小:
```c++
int size = file.gcount();
```
7. 关闭文件并释放内存:
```c++
file.close();
delete[] buf;
```
完整代码示例:
```c++
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("binary_file.bin", ios::in | ios::binary);
if (!file.is_open()) {
cout << "Failed to open file!" << endl;
return -1;
}
const int BUF_SIZE = 1024;
char* buf = new char[BUF_SIZE];
file.read(buf, BUF_SIZE);
if (!file.good()) {
cout << "Failed to read file!" << endl;
return -1;
}
int size = file.gcount();
cout << "Read " << size << " bytes." << endl;
file.close();
delete[] buf;
return 0;
}
```
阅读全文