如何获取文件的大小

How to get the size of a file

本文关键字:文件 获取 何获取      更新时间:2023-10-16

可能的重复项:
使用 C++ 文件流 (fstream),如何确定文件的大小?
C 程序中的文件大小

我想检索文件的大小,为此我以这种方式实现

(void)fseek(m_fp, 0, SEEK_END); // Set the file pointer to the end of the file
pFileSize = ftell(m_fp);        // Get the file size
(void)fseek(m_fp, oldFilePos, SEEK_SET);  // Put back the file pointer at the original location

这对于需要是不可行的,并且是获取文件大小或检查文件是否包含和数据的任何其他方法

您可以使用 stat

#include <sys/types.h>
#include <sys/stat.h>
#if defined (_WIN32)
#  include <io.h> // make portable for windows
#else
#include <unistd.h>
#endif
struct stat st;
stat (filename, &st);
std::cout << st.st_size;

如果它是一个二进制流,那么 pFileSize 是从 oldFilePos 到文件末尾的字节数。

你写的是一种100%多平台的方式来做你需要的事情。使用操作系统的调用来执行更多操作,stat()类 Unix 操作系统或 Windows 上的GetFileAttributesEx()