c++的fstream的大小
时间: 2023-08-13 12:05:59 浏览: 65
要获取 `fstream` 所打开文件的大小,可以使用 `seekg()` 函数将文件指针定位到文件末尾,然后再使用 `tellg()` 函数获取文件指针的位置,即文件大小。
示例代码如下:
```c++
#include <iostream>
#include <fstream>
int main() {
std::ifstream ifs("example.txt", std::ios::binary);
if (!ifs) {
std::cerr << "Failed to open file!" << std::endl;
return -1;
}
ifs.seekg(0, std::ios::end);
std::streampos size = ifs.tellg();
std::cout << "File size: " << size << " bytes" << std::endl;
ifs.close();
return 0;
}
```
在这个例子中,我们首先通过 `std::ios::binary` 标志打开二进制文件,然后使用 `seekg()` 函数将文件指针定位到文件末尾,再使用 `tellg()` 函数获取文件指针的位置,即文件大小。最后,我们输出文件大小并关闭文件流。
相关问题
c++ fstream定位和读取指定大小
在++ 中,可以使用 `seekg()` 函数来定位文件读取指针的位置,使用 `read()` 函数来读取指定大小的数据。下面是一个例子:
```c++
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream infile("example.bin", ios::in | ios::binary); // 打开二进制文件
if (!infile) {
cerr << "Error: Cannot open file example.bin!" << endl;
exit(1);
}
int offset = 10; // 定位到第10个字节处
infile.seekg(offset, ios::beg); // 设置读取指针位置
int size = 5; // 读取5个字节
char* buffer = new char[size]; // 创建缓冲区
infile.read(buffer, size); // 读取数据到缓冲区
// 输出读取的数据
for (int i = 0; i < size; i++) {
cout << buffer[i] << " ";
}
cout << endl;
infile.close(); // 关闭文件
delete[] buffer; // 释放缓冲区内存
return 0;
}
```
在上面的代码中,首先使用 `ifstream` 打开一个二进制文件,然后使用 `seekg()` 函数将读取指针定位到第10个字节处,接着使用 `read()` 函数读取5个字节的数据到缓冲区中。最后输出读取的数据,关闭文件,并释放缓冲区内存。
注意,如果文件打开失败,需要使用 `cerr` 输出错误信息,并调用 `exit()` 函数退出程序。此外,如果不再需要使用缓冲区,需要使用 `delete[]` 运算符释放缓冲区内存,以避免内存泄漏。
c++获取文件大小fstream
你可以使用 `std::fstream` 类来获取文件大小。具体的代码如下所示:
```c++
#include <fstream>
long getFileSize(const std::string& filename) {
std::ifstream file(filename, std::ios::binary | std::ios::ate);
if (file.fail()) {
return -1; // 出错返回-1
}
return static_cast<long>(file.tellg()); // 返回文件大小
}
int main() {
std::string filename = "example.txt";
long size = getFileSize(filename);
if (size < 0) {
std::cout << "Failed to open file." << std::endl;
return 1;
}
std::cout << "File size: " << size << " bytes." << std::endl;
return 0;
}
```
上述代码中的 `getFileSize` 函数接收一个文件名作为参数,然后使用 `std::ifstream` 类打开文件,并将文件指针移动到文件末尾。接着,函数使用 `tellg` 函数获取文件指针的当前位置,这个位置也就是文件大小。最后,函数将文件大小返回给调用者。
在 `main` 函数中,我们调用 `getFileSize` 函数来获取 `example.txt` 文件的大小。如果文件打开失败,函数将返回 `-1`。最后,我们输出文件大小并返回0。