【发布时间】:2011-01-25 10:54:38
【问题描述】:
我确定我刚刚错过了手册中的这一点,但是如何使用来自 fstream 标头的 C++ 的 istream 类确定文件的大小(以字节为单位)?
【问题讨论】:
-
@NarendraN - 不使用 fstream,因为这个问题明确要求
标签: c++ filesize fstream istream
我确定我刚刚错过了手册中的这一点,但是如何使用来自 fstream 标头的 C++ 的 istream 类确定文件的大小(以字节为单位)?
【问题讨论】:
标签: c++ filesize fstream istream
您可以使用ios::ate 标志(和ios::binary 标志)打开文件,因此tellg() 函数将直接为您提供文件大小:
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
【讨论】:
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?
不要使用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()。
像这样:
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 是不仅仅是一个整数。
begin不就是0吗?
我是新手,但这是我自学的做法:
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.
【讨论】: