我相信我在手册中漏掉了这一点,但是如何使用C++ fstream
头文件中的istream
类确定文件的大小(以字节为单位)?
你可以使用 ios::ate
标志(和 ios::binary
标志)打开文件,这样 tellg()
函数将直接给你文件大小:
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
std::streampos fileSize( const char* filePath ){
std::streampos fsize = 0;
std::ifstream file( filePath, std::ios::binary );
fsize = file.tellg();
file.seekg( 0, std::ios::end );
fsize = file.tellg() - fsize;
file.close();
return fsize;
}
tellg
返回0是否有保证? - Steve Jessop不要使用 tellg
函数确定文件的准确大小。由 tellg
确定的长度将大于可以从文件中读取的字符数。
来自 stackoverflow 问题 tellg() function give wrong size of file?,tellg
不报告文件的大小,也不报告以字节为单位的偏移量。它报告一个令牌值,稍后可以用它来寻找相同的位置,没有其他更多信息(甚至不能保证可以将该类型转换为整数类型)。对于 Windows (和大多数非 Unix 系统),在文本模式下,tellg 返回的值与必须读取的字节数之间没有直接的立即映射关系。
如果重要的是要知道可以确切地读取多少字节,则唯一可靠的方法是通过读取来实现。您应该能够使用类似以下内容的代码来实现:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
stat()
。 - Alexis Wilke就像这样:
long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;
std::streampos
而非 long
,因为后者可能不支持前者那么大的范围。而且,streampos
并不只是一个整数。 - Raphaël Saint-Pierrebegin
不是只有0吗? - ghchoi从C++17开始,我们拥有了std::filesystem::file_size
。这并不是严格意义上使用istream
或fstream
的方法,但它是在标准C++中读取文件大小最简明和正确的方式。
#include <filesystem>
...
auto size = std::filesystem::file_size("example.txt");
我是一个新手,但这是我自学的方法:
ifstream input_file("example.txt", ios::in | ios::binary)
streambuf* buf_ptr = input_file.rdbuf(); //pointer to the stream buffer
input.get(); //extract one char from the stream, to activate the buffer
input.unget(); //put the character back to undo the get()
size_t file_size = buf_ptr->in_avail();
//a value of 0 will be returned if the stream was not activated, per line 3.