如何以C++为单位获取文件的大小?
How can I get a file's size in C++?
让我们创建一个与这个问题互补的问题。在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),你可能想看看调用stat64
和fstat64
(如果可用)
使用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;
}
相关文章:
- C++ - 忽略并从其他文件获取数据
- 为什么从文件获取图标时应用程序有时会崩溃?
- 如何在 c++ 窗口中将参数和返回的退出值传递到批处理文件/从批处理文件获取返回的退出值
- Qt .pro 文件获取 Qtkit 名称
- 提升属性树:如何使用xml文件获取子树的子级
- 从C 中的二进制文件获取整数值时
- 如何在Windows上绕过主机文件获取真实的IP地址
- 如何使用 CPP/C# 从 VHDX 文件获取文件(或文件系统)
- 从读取到对象指针数组的文件获取段错误
- 是否可以从IOS项目中的cpp文件获取文件路径
- 将数据从头文件获取到源文件中的非成员函数中
- 从两个不同的文件获取输入时,输入会发生变化
- 从文件 C++ 获取整数
- 通过在 C++ 中使用发布模式二进制文件获取崩溃原因
- C++ 将值从文件获取到数组中
- 使用HTTP上载文件.获取错误:-HttpSendReuest 12005
- 正在从外部文件获取输入
- 读/写同一个文件(获取gmon.out)
- 从二进制文件获取输入时发生访问冲突错误
- 从特定文件获取函数指针