我怎样才能获得在C + +文件的大小?

我们来创build一个补充的问题。 在C ++中获取文件大小的最常见方法是什么? 在回答之前,确保它是可移植的(可以在Unix,Mac和Windows上执行),可靠,易于理解,并且没有库依赖性(没有提升或者qt,但是例如glib是可以的,因为它是可移植的库)。

#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/

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

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

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

在某些系统上还有一个stat64 / fstat64。 所以,如果你需要这个非常大的文件,你可能想看看使用这些。

使用fopen(),fseek()和ftell()函数也可以find。

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

使用C ++文件系统TS:

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

在c ++中你可以使用下面的函数,它会以字节的forms返回你的文件的大小。

 #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; } 
 #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("%ld\n",len); fclose(f); } 

下面的代码片段正好解决了这个post中的问题:)

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