Could anyone please tell me how to read data from a binary file???..

Dani AI

Generated

As asked and as pointed out, the key is to first determine whether the file is ASCII hex text (human-readable hex bytes like "1B 1C" or "0x01") or raw binary (actual byte values). A short diagnostic step that avoids guessing: read a small sample and check whether bytes are printable hex characters and whitespace. If they are, treat the file as text; otherwise treat it as binary.

If the file is ASCII hex, parse it as text, not as raw bytes. A robust, fast C++ way is to normalize the stream (strip optional "0x", skip non-hex separators, pad odd nibble runs) and convert two hex characters into one byte repeatedly. For reliable, locale-independent conversion prefer std::from_chars (C++17) over formatted extraction; it is faster and avoids iostream locale issues (std::from_chars).

If the file is raw binary, use fixed-width types (uint32_t) rather than long (size varies by platform), open the file in binary mode to avoid CR/LF translation, read exactly four bytes into a byte buffer, check the read count, then safely copy bytes into an integer with std::memcpy to avoid strict-aliasing problems (std::memcpy). Finally, handle endianness explicitly (either assemble with shifts or use std::endian/byte-swap on supported platforms) so the same code works across architectures (std::endian).

Recommended Answers

All 3 Replies

It depends on the contents of the file -- every binary file is different. In a nutshell, use ifstream's read() method.

It is a hexadecimal file and I have to read four bytes from the file.

Then you will not have to open that file as binary. If the file looks like this: 0x01 0x02 0x03 0x04 OR maybe even like this: 1B 1C 1D 1E 1F (numbers separated by white space) Then you read it like this:

ifstream in("something.txt");
int a, b, c, d;
in >> hex >> a >> b >> c >> d;

On the otherhand, if the file contains the binary value of an integer, then read it like this (assuming sizeof(long) = 4 on your computer and compiler)

long x;
ifstream in("something.txt", ios::binary);
in.read( (char*)&x, sizeof(long));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.