I’m new to C++ file io, so the other day I decided to write a small program that simply reads a UTF-8 encoded string and a paired float from a binary file. The pattern is string-float with no extra data or spacing between pairs. EDIT I’ve revised the code based on several answers. However, the output remains the same (“The RoommateAp 0”);
string readString (ifstream* file)
{
//Get the length of the upcoming string
uint16_t stringSize = 0;
file->read(reinterpret_cast<char*>(&stringSize), sizeof(char) * 2);
//Now that we know how long buffer should be, initialize it
char* buffer = new char[stringSize + 1];
buffer[stringSize] = '\0';
//Read in a number of chars equal to stringSize
file->read(buffer, stringSize);
//Build a string out of the data
string result = buffer;
delete[] buffer;
return result;
}
float readFloat (ifstream* file)
{
float buffer = 0;
file->read(reinterpret_cast<char*>(&buffer), sizeof(float));
return buffer;
}
int main()
{
//Create new file that's open for reading
ifstream file("movies.dat", ios::in|ios::binary);
//Make sure the file is open before starting to read
if (file.is_open())
{
while (!file.eof())
{
cout << readString(&file) << endl;
cout << readFloat(&file) << endl;
}
file.close();
}
else
{
cout << "Unable to open file" << endl;
}
}
And a sample of data from the file (spaces for readability):
000C 54686520526F6F6D6D617465 41700000
As one can see, the first two bytes are the length of the string (12 in this case), followed by twelve characters (which spell “The Roommate”), and the final four bytes are a float.
When I run this code, the only thing that happens is that the terminal hangs and I have to close it manually. I think it may be because I am reading past the end of the file, but I have no idea why this would happen. What am I doing incorrectly?
There are at least two issues. First, the line:
Probably should take the address of
stringSize:Second, the line:
Doesn’t allocate enough memory, since it doesn’t take the
NULterminator into account. That code should do something like:Finally, the line:
Fails to
delete[]the buffer after instantiating astringfrom it, which will cause a memory leak.Also note that
std::string‘s UTF-8 support is quite poor out of the box. Fortunately, there are solutions.