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?

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 stackoverflow.com/questions/27061489/… Commented Jul 9, 2020 at 19:18
  • Thanks for the response @Kenny Ostrom Commented Jul 9, 2020 at 20:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

If this doesn't work for you, make sure the endian of numc matches the endian of the file
You were right. I'd forgotten the null character. the problem is solved. Thanks.
Don't forget to delete[] ver when you are done using it. Better to use std::string instead, or at least std::unique_ptr<char[]>
@RemyLebeau I don't understand why is that a problem?
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.