使用C ++文件流(fstream),如何确定文件的大小?

时间:2010-03-09 14:01:00

标签: c++ filesize fstream istream

我确定我在手册中错过了这个,但是如何使用来自istream标题的C ++的fstream类来确定文件的大小(以字节为单位)?

5 个答案:

答案 0 :(得分:85)

您可以使用ios::ate标志(和ios::binary标志)打开文件,因此tellg()功能将直接为您提供文件大小:

ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();

答案 1 :(得分:55)

你可以寻找到最后,然后计算差异:

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;
}

答案 2 :(得分:23)

请勿使用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 );

答案 3 :(得分:9)

像这样:

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;

答案 4 :(得分:-2)

我是新手,但这是我自学成才的方式:

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.