How to read one byte from a file? The following code works, but some bytes are skipped ( 0x09, 0x0a, 0x0b, 0x0c, 0x0d ) and the next byte is read.

 ifstream file(fileName, std::ios_base::in | std::ios_base::binary); uint8_t s; file >> s; 

Tried to do more like this,

 file.readsome(&s, 1); 

but uint8_t* does not cast to char* . I use uint8_t because, as far as I know the standard, the size of the char is not regulated.

What is the problem?

    5 answers 5

    I would use char (so that it was not a byte - it is necessary to work hard to find one ...) Then

     file.get(char&); или file.read(char*,1); 

    Well, if uint8_t strictly (which, I’m ready to argue, it’s just unsigned char ... if not, then it’s even interesting what you are dealing with) -

     file.read(reinterpret_cast<char*>(&s),1); 
    • Is it safe to use reinterpret_cast at all? Just want to write a portable program. - Asem pm
    • As for me, in this case - easily. - Harry
    • And why through the overloaded operator some bytes are not read do not know? The file in binary mode is open because. - Asem
    • \r \n Apparently - vegorov

    ASCII

    • 0x09 - horizontal tab ( \t )
    • 0x0a - newline ( \n )
    • 0x0b - vertical tab
    • 0x0c - “page run”, new page - command for the printer to start printing from a new page
    • 0x0d - carriage return ( \r )

    It looks as if you are still reading a text file as text, can you leave only std::ifstream::binary in the constructor?

    As a last resort, there is always a fread() .

      For reading files bytes, there is a specially designed function fread (). Use it.

      • This is still a legacy of C, I thought there was a replacement for it in stream. - Asem

      C ++ has a lot of smart formatted input functions, such as >> . Do not get dirty, but use std :: basic_istream :: read .

      • Your read hang tight waiting for it if it tries to read more than is in the file. It is readsome() . - ߊߚߤߘ

      According to the ISO / IEC 14882 standard, <cstdio> is the same C ++ part as <iostream> . Therefore, no one bothers to use it where it is convenient. After all, no one is worried about such a “legacy with” as operations += , %= No one even thinks of removing “legacy C” from C ++, but on the contrary, adding to the C ++ standard all sorts of convenient initializations that came about in C11. By the way, <iostream> has no advantages over <cstdio> .

      • And get it right - "where it is." - 0xdb