0

I am trying to read a string(ver) from a binary file. the number of characters(numc) in the string is also read from the file.This is how I read the file:

 uint32_t numc;
 inFile.read((char*)&numc, sizeof(numc));
 char* ver = new char[numc];
 inFile.read(ver, numc);
 cout << "the version is: " << ver << endl;

what I get is the string that I expect plus some other symbols. How can I solve this problem?

SJ93
  • 5
  • 2
  • it is not null terminated in the file. You will need to store it in a length-aware string storage, like for example std::string, or provide the null character yourself. See also https://stackoverflow.com/questions/27061489/copying-a-fixed-length-of-data-from-an-stdistream-to-a-string – Kenny Ostrom Jul 09 '20 at 19:18
  • Thanks for the response @Kenny Ostrom – SJ93 Jul 09 '20 at 20:14

1 Answers1

1

A char* string is a nul terminated sequence of characters. Your code ignores the nul termination part. Here's how it should look

uint32_t numc;
inFile.read((char*)&numc, sizeof(numc));
char* ver = new char[numc + 1]; // allocate one extra character for the nul terminator
inFile.read(ver, numc);
ver[numc] = '\0'; // add the nul terminator
cout << "the version is: " << ver << endl;

Also sizeof(numc) not size(numc) although maybe that's a typo.

john
  • 85,011
  • 4
  • 57
  • 81
  • If this doesn't work for you, make sure the [endian](https://en.wikipedia.org/wiki/Endianness) of `numc` matches the endian of the file – user4581301 Jul 09 '20 at 19:31
  • You were right. I'd forgotten the null character. the problem is solved. Thanks. – SJ93 Jul 09 '20 at 19:36
  • Don't forget to `delete[] ver` when you are done using it. Better to use `std::string` instead, or at least `std::unique_ptr` – Remy Lebeau Jul 09 '20 at 20:28
  • @RemyLebeau I don't understand why is that a problem? – SJ93 Jul 09 '20 at 21:42
  • @MahshadJavidan Memory leak vs no memory leak. You have to `delete` whatever you allocate with `new`. `std::unique_ptr` will handle that for you. And you don't have to worry about that at all with `std::string`. – Remy Lebeau Jul 09 '20 at 22:08
  • @john alternatively, instead of null-terminating the string, you can use `cout.write(ver, numc)` instead of `cout << ver`. – Remy Lebeau Jul 09 '20 at 22:11