如何以C++为单位获取文件的大小?

How can I get a file's size in C++?

本文关键字:文件 获取 C++ 为单位      更新时间:2023-10-16

让我们创建一个与这个问题互补的问题。在c++中获取文件大小最常见的方法是什么?在回答之前,确保它是可移植的(可以在Unix, Mac和Windows上执行),可靠,易于理解,没有库依赖(没有boost或qt,但例如glib是ok的,因为它是可移植库)。

#include <fstream>
std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg(); 
}

有关c++文件的更多信息请参见http://www.cplusplus.com/doc/tutorial/files/。

编辑:这个答案是不正确的,因为tellg()不一定返回正确的值。见http://stackoverflow.com/a/22986486/1835769

虽然不一定是最流行的方法,但我听说ftell, fseek方法在某些情况下可能并不总是给出准确的结果。具体来说,如果使用了一个已经打开的文件,并且需要计算其大小,而它恰好是作为文本文件打开的,那么它将给出错误的答案。

下面的方法应该总是工作,因为stat是Windows, Mac和Linux上c运行时库的一部分。

#include <sys/stat.h>
long GetFileSize(std::string filename)
{
    struct stat stat_buf;
    int rc = stat(filename.c_str(), &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}
or 
long FdGetFileSize(int fd)
{
    struct stat stat_buf;
    int rc = fstat(fd, &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

如果你需要这个非常大的文件(>2GB),你可能想看看调用stat64fstat64(如果可用)

使用c++文件系统库:

#include <filesystem>
int main(int argc, char *argv[]) {
  std::filesystem::path p{argv[1]};
  std::cout << "The size of " << p.u8string() << " is " <<
      std::filesystem::file_size(p) << " bytes.n";
}

也可以使用fopen(),fseek()和ftell()函数来查找。

int get_file_size(std::string filename) // path to file
{
    FILE *p_file = NULL;
    p_file = fopen(filename.c_str(),"rb");
    fseek(p_file,0,SEEK_END);
    int size = ftell(p_file);
    fclose(p_file);
    return size;
}
#include <stdio.h>
int main()
{
    FILE *f;
    f = fopen("mainfinal.c" , "r");
    fseek(f, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(f);
    printf("%ldn", len);
    fclose(f);
}

在c++中你可以使用下面的函数,它将以字节为单位返回你的文件大小

#include <fstream>
int fileSize(const char *add){
    ifstream mySource;
    mySource.open(add, ios_base::binary);
    mySource.seekg(0,ios_base::end);
    int size = mySource.tellg();
    mySource.close();
    return size;
}

下面的代码片段准确地解决了这个问题职位:)

///
/// Get me my file size in bytes (long long to support any file size supported by your OS.
///
long long Logger::getFileSize()
{
    std::streampos fsize = 0;
    std::ifstream myfile ("myfile.txt", ios::in);  // File is of type const char*
    fsize = myfile.tellg();         // The file pointer is currently at the beginning
    myfile.seekg(0, ios::end);      // Place the file pointer at the end of file
    fsize = myfile.tellg() - fsize;
    myfile.close();
    static_assert(sizeof(fsize) >= sizeof(long long), "Oops.");
    cout << "size is: " << fsize << " bytes.n";
    return fsize;
}