0

I'm trying to read a file which contain data in binairy mod. The size of the file is 28 bytes but when i try to read this file I only have 22 bytes. I have already tried to modify the info inside the file but it's still missing some bytes. I have no idea why. PS: I know which data are inside the file but they're not readeable in any kind of computer character encoding standard. The code used to read the file:

std::string line{ "" };
    std::string buffer;
    while (std::getline(file, line))
        buffer += line;
    file.close();
  • 2
    If your data is binary you probably don't want to read it like this especially if your OS is MS Windows. – drescherjm Jul 08 '21 at 16:21
  • 2
    You are trying to read binary data as text, which is not going to work. Google for examples on how to read binary files, or consult a [good c++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jul 08 '21 at 16:23
  • Related: [https://stackoverflow.com/a/5420568/487892](https://stackoverflow.com/a/5420568/487892) – drescherjm Jul 08 '21 at 16:26
  • I want to read all of binairy data because it's me who put them in. So if i can recover them entierly it's better (obligatory) – Ismaël Gaye Jul 08 '21 at 16:26
  • Reading it this way you will not be able to recover the data. – drescherjm Jul 08 '21 at 16:27
  • @IsmaëlGaye: It's definitely possible to read binary files in C++. `std::string` and `std::getline` are the wrong tools for binary data. Even `fstream` cannot portably access binary data (it always has a character facet performing text conversions, binary data requires installing a no-op facet, and setting that up is non-portable). – Ben Voigt Jul 08 '21 at 16:27
  • 1
    it works with `std::vector buffer(std::istreambuf_iterator(file), {});` thanks (i have the right number of bytes) – Ismaël Gaye Jul 08 '21 at 16:31

1 Answers1

0

Don't read binary data like its text. If you want to read binary data into a buffer (e.g., load it into a std::vector) here is one recipe that uses stdlib:

#include <cstdio>
#include <cstdlib>
#include <vector>

FILE *f = fopen("myfile.bin", "rb");
if (f == nullptr) { /* ... */}
fseek(f, 0, SEEK_END);
auto size = ftell(f);
fseek(f, 0, SEEK_SET);
std::vector<uint8_t> buffer(size);
if (fread (buffer.data(), 1, size, f) != size) { /* ... */ }
fclose(f);
wcochran
  • 10,089
  • 6
  • 61
  • 69