这个问题在这里已经有答案了:

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

有帮助吗?

解决方案

您可以使用以下命令打开该文件 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 以确定文件的确切大小。长度由下式确定 tellg 将大于可以从文件中读取的字符数。

来自 stackoverflow 问题 tellg() 函数给出的文件大小错误? 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 );

像这样:

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;

我是新手,但这是我自学的方法:

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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top