简体   繁体   中英

Determine length of compiled binary

I'm trying to access the length of the compiled binary of a program, but it returns -1. Could someone point me on the right track? I'm uncertain as to why the following code isn't producing the correct result.

std::fstream file(argv[0], std::ios::binary | std::ios::ate);
std::cout << file.tellg() << "\n";

A result of -1 indicates that the open failed. You should always test for this:

if (std::fstream file(argv[0], std::ios::binary | std::ios::ate)) {
    std::cout << file.tellg() << "\n";
} else {
    // Report error.
}

The second problem is that if you just want to get its length, you should open it for reading only (this might be why the open is failing):

std::ifstream file(argv[0], …);

The third issue is that argv[0] isn't guaranteed to contain a valid executable name. That's just a widely held assumption. You'll usually get away with it, but you should keep it in mind.

Simply adding std::ios::in to the open mode flags makes it work for me. (The constructor was failing to open the file. According to the Standard, you must specify one of in , out , or app .)

Changing the stream type to std::istream also works, but the resulting binary is 8 bytes larger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM