Errors while reading & writing to XML

I have a code which reads XML ,converts read data to a string & returns this string.Another function creates another XML processing this string data.Now I got erros while opening this newly created XML.So I removed processing thing just written whatever came as a part of string & found that some garbage value is getting written at the end of new XML file.Anybody has any clue why this is happening?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string readXML()
{
	ifstream is;
	is.open ("E:\\newFolder\\old.xml", ios::in);
	is.seekg (0, ios::end);
	int length = is.tellg();
	is.seekg (0, ios::beg);
	
	char *buffer = new char [length];
	is.read (buffer,length);
	is.close();
	
	std::string newOutput(buffer);
	delete[] buffer;

	return newOutput;  //this string value will be processed & new XML will be created but it fails even if I used this string as it is.
}

The string(const char*) constructor treats the pointer as the beginning of a null-terminated C string, so you have to null-terminate your array.
However, the temporary array is unnecessary:

1
2
3
string newOutput(length,0);
is.read(&newOutput[0],length);
return newOutput;
@Athar

I could be wrong but I am not entirely sure that you can reliably take the address the first element of a std::string and assume it points to contiguous memory.

is.read(&newOutput[0],length);

That would work in most implementations but I don't think the standard actually guarantees it.

Last edited on
Topic archived. No new replies allowed.