确定二进制文件的大小

Ash*_*Ash 4 c++ file-io input

我正在尝试读取一个二进制文件,并且需要确定其大小,但无论我尝试过什么方法,我得到的大小都是零。

例如:

fstream cbf(address, ios::binary | ios::in | ios::ate);
fstream::pos_type size = cbf.tellg();                   // Returns 0.

char* chunk = new char[size];
cbf.read(chunk, size);
//...
Run Code Online (Sandbox Code Playgroud)

如果我要使用以下内容:

#include <sys/stat.h>
struct stat st;
stat(address.c_str(),&st);
int size = st.st_size;
Run Code Online (Sandbox Code Playgroud)

大小仍然为零。我也尝试过以下方法,但它仍然为零。

File* fp;
fp = open(address.c_str(), "rb");
Run Code Online (Sandbox Code Playgroud)

如何获取文件的大小?

感谢您的回复...我已经确定了问题:我试图访问的二进制文件是在执行期间创建的,而我只是忘记在尝试读取它之前关闭它...

Rob*_*obᵩ 5

你的两个例子都没有检查失败。这个程序使用你的第一种方法,非常适合我。它正确地识别了 /etc/passwd 的大小以及 /etc/motd 的不存在。

#include <fstream>
#include <iostream>
#include <string>

void printSize(const std::string& address) {
  std::fstream motd(address.c_str(), std::ios::binary|std::ios::in|std::ios::ate);
  if(motd) {
    std::fstream::pos_type size = motd.tellg();
    std::cout << address << " " << size << "\n";
  } else {
    perror(address.c_str());
  }
}

int main () {
    printSize("/etc/motd");
    printSize("/etc/passwd");
}
Run Code Online (Sandbox Code Playgroud)

  • @Ash,当您运行我的程序**不做任何更改**时,您会得到什么输出? (3认同)