代码之家  ›  专栏  ›  技术社区  ›  warren

使用C++ FielestRAMS(FSUSTER),您如何确定文件的大小?[副本]

  •  69
  • warren  · 技术社区  · 16 年前

    istream fstream 标题?

    5 回复  |  直到 16 年前
        1
  •  96
  •   Dominik Honnef CEN    13 年前

    您可以使用 ios::ate ios::binary 旗帜),所以 tellg() 函数将直接提供文件大小:

    ifstream file( "example.txt", ios::binary | ios::ate);
    return file.tellg();
    
        2
  •  65
  •   Khaled Alshaya    16 年前

    您可以一直搜索到最后,然后计算差值:

    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;
    }
    
        3
  •  36
  •   Community Mohan Dere    9 年前

    tellg 以确定文件的确切大小。长度由 泰尔格 将大于可以从文件中读取的字符数。

    从stackoverflow问题 tellg() function give wrong size of file? 泰尔格 不报告文件的大小,也不报告从字节开始的偏移量。它报告了一个令牌值,该值稍后可用于查找同一个位置,仅此而已(甚至不能保证您可以将类型转换为整数类型)。对于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 );
    
        4
  •  10
  •   Tim Cooper    14 年前

    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;
    
        5
  •  -5
  •   Radim Köhler user2134822    13 年前

    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.