SJ93
SJ93

Reputation: 5

How to read a string from a binary file?

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?

Upvotes: 0

Views: 411

Answers (1)

john
john

Reputation: 87944

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.

Upvotes: 1

Related Questions