To read 32 bits from a binary file, just use fread
to read into a 32-bit variable. Like
uint32_t address;
fread(&address, sizeof(address), 1, myfile);
You might have to convert the value using htonl
if it's stored in a host endianness that differs from network endianness.
Of course, you must first open the file in binary mode:
FILE *myfile = fopen("binaryipfile.bin", "rb"); // Note the use of "rb"
To do in in C++ using the C++ standard stream library, it would be something like
std::ifstream file("binaryipfile.bin", std::ios::in | std::ios::binary);
uint32_t address;
file.read(reinterpret_cast<char*>(&address), sizeof(address));
No matter if you use the C or C++ way, if you have multiple addresses then read in a loop, possibly putting the addresses into a std::vector
. This can be done much simpler if using the C++ function std::copy
function paired with std::istreambuf_iterator
and std::back_inserter
:
std::vector<uint32_t> addresses;
std::copy(std::istreambuf_iterator<uint32_t>(file),
std::istreambuf_iterator<uint32_t>(),
std::back_inserter(addresses));
After this the vector addresses
will contain all 4-byte values read from the file. If not all of the file contains addresses, you could use std::copy_n
instead.
You should also have some error checking, which I left out of my examples to keep them simple.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…