让我们创建一个补充问题,对应于这个。 什么是在C++中获取文件大小的最常见方法? 在回答之前,请确保它是可移植的(可以在Unix、Mac和Windows上执行),可靠、易于理解且没有库依赖(例如,不使用boost或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();
}
请参阅http://www.cplusplus.com/doc/tutorial/files/以获取有关C++文件的更多信息。
编辑:此答案不正确,因为tellg()不一定返回正确的值。 请参阅https://dev59.com/6mAg5IYBdhLWcg3w9e0y#22986486
std::ifstream in(filename, std::ios::binary | std::ios::ate);
为了让大家更轻松一些 ;) - jmpcm使用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";
}
filesystem
已成为ISO C++标准。 - chappjc虽然不一定是最受欢迎的方法,但我听说在某些情况下,使用 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的大文件,您可能想要调用stat64
和fstat64
(如果可用)。
你也可以使用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;
}
<fstream>
和 <iostream>
,但需要使用 <string>
并进行错误检查。(当使用空文件时, fseek
会崩溃,当出错时,ftell
返回 -1) - rve#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);
}
下面的代码片段完全回答了这篇帖子中的问题 :)
///
/// 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;
}
#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;
}
fstat()
在POSIX中标准化,但Windows选择通过调用函数_fstat()
来偏离该标准。fstat()
是 不 可移植的,因为你需要一个#ifdef _WIN32
来使用它。 - Marc Mutz - mmutz