I've got code sections which write and read binary files. But when I print data reading from file. It appears unnecessary characters.

int WriteFile(const char* file_name)
{
	fstream file(file_name,ios.out|ios.binary);

	if(file.is_open())
	{
		string data_block="I don't understand!\nAdd one line";
		
		file.write(data_block.c_str(),data_block.length());

		file.close();

		cout << data_block << "(" << data_block.length() << ")" << "\n";
		cout << "Write file successfully!\n";
	}
	else
	{
		cout << "Unable to open file!\n";

		return 1;
	}

	return 0;
} 

int ReadFile(const char* file_name)
{
	fstream file(file_name,ios.in|ios.binary|ios.ate);

	if(file.is_open())
	{
		fstream::pos_type size=file.tellg();

		char* data_block=new char[size];

		file.seekg(0,ios.beg);

		file.read(data_block,size);

		file.close();

		cout << data_block << "(" << size << ")" << "\n";
		cout << "Read file successfully!\n";

		delete []data_block;
	}
	else
	{
		cout << "Unable to open file!\n";

		return 1;
	}

	return 0;
}


help me, please!

Attachments f.JPG 10.73 KB

you need to allocate one more byte than file size for the string's null-terminator, then add the null terminator after the read() operation.

char* data_block=new char[(int)size+1];

		file.seekg(0,ios.beg);

		file.read(data_block,size);
        data_block[size] = 0;
		file.close();

dear Ancient Dragon,
I moved pointer to file ending (line 28). I checked the problem you mentioned but be not wrong.

dear Ancient Dragon,
I moved pointer to file ending (line 28). I checked the problem you mentioned but be not wrong.

Yes I realized that, and I deleted my comment. Please re-read my post as it contains the correct solution.

This article has been dead for over six months. Start a new discussion instead.