std::ofstream文件大小
时间: 2024-03-08 21:44:22 浏览: 412
std::ofstream是C++标准库中用于写入文件的输出流类。它并没有直接提供获取文件大小的方法。要获取文件大小,可以使用以下步骤:
1. 打开文件:使用std::ifstream类打开文件,并将文件关联到输入流对象。
2. 定位到文件末尾:使用seekg()函数将文件指针定位到文件末尾。
3. 获取文件指针位置:使用tellg()函数获取文件指针的位置,即文件大小。
4. 关闭文件:使用close()函数关闭文件。
下面是一个示例代码:
```cpp
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt", std::ios::binary); // 打开文件
if (!file) {
std::cout << "无法打开文件" << std::endl;
return 0;
}
file.seekg(0, std::ios::end); // 定位到文件末尾
std::streampos fileSize = file.tellg(); // 获取文件指针位置,即文件大小
std::cout << "文件大小为:" << fileSize << " 字节" << std::endl;
file.close(); // 关闭文件
return 0;
}
```
请注意,上述代码中的"example.txt"是要获取大小的文件名,你可以根据实际情况修改。另外,需要包含头文件<fstream>和<iostream>来使用相关的类和函数。
阅读全文
相关推荐



















