2010-03-09 330 views

回答

75

您可以打开使用ios::ate标志(和ios::binary标志)的文件,所以tellg()功能会直接给你文件大小:

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

@Dominik Honnef:在VS 2013 Update5 64位这种方法,与_ios:ate_标志和没有_seekg(0,ios:结束)_可能不适用于大型文件。有关更多信息,请参阅http://stackoverflow.com/questions/32057750/how-to-get-the-filesize-for-large-files-in-c。 –

+2

这似乎不是一个好方法。 [tellg不会报告文件的大小,也不会以字节开头的偏移量](http://stackoverflow.com/a/22986486/1835769)。 – displayName

+0

@displayName [cplusplus.com](http://www.cplusplus.com/reference/istream/istream/seekg/)有一种不同意这种说法:它确实使用'tellg()'来检测文件大小。 –

49

您可以寻求到年底,然后计算的区别:

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

真棒!谢谢=) – warren

+0

已将size_t更改为streampos。 – AraK

+7

出于兴趣,是第一次调用'tellg'不保证返回0吗? –

8

像这样:

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; 
+9

您可能希望使用更合适的'std :: streampos'而不是'long',因为后者可能不支持像前者那么大的范围 - 并且'streampos' *不仅仅是一个整数。 –

-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. 
+5

时,它在大量情况下返回0,所有这些决定是否存在第一个字符。这有什么帮助? – warren

10

不要使用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);