如何获取文件的大小

Sij*_*ith 2 c c++ file-io

可能重复:
使用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
Run Code Online (Sandbox Code Playgroud)

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

toz*_*zka 6

你可以使用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;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,stat不是C或C++的一部分,而是POSIX. (2认同)