Determine binary file size

I am trying to read a binary file and I need to determine its size, but regardless of the method I tried, I get a zero size.

For instance:

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); //... 

If I used the following:

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

The size is still zero. I also tried the following, but still zero.

 File* fp; fp = open(address.c_str(), "rb"); 

How to get file size?

Thanks for the answers ... I identified the problem: The binary I was trying to get was created at runtime, and I just forgot to close it before trying to read it ...

+4
source share
2 answers

None of your examples check for errors. This program , using your first method, works great for me. It correctly identifies the size of / etc / passwd and the non-existence of / 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"); } 
+4
source

Try uploading the file in this method.

Note. Use ifstream insted fstream on this line ifstream cbf(address, ios::binary | ios::in );

 long size; ifstream cbf(address, ios::binary | ios::in); cbf.seekg(0, ios::end); size=cbf.tellg(); cbf.seekg(0, ios::beg); char* chunk = new char[size]; cbf.read(chunk, size); 
0
source

All Articles