Reputation: 249
I am using Visual C++ with an MFC program, using Visual Studio 2008, and I will be creating or appending to an XML file.
If the file doesn't exist, it will be created, and there is no worries, but it's when the file already exists and I have to append to it that there seems to be an issue.
What I was instructed, and found through some research, was to read the file into a string, back up a bit, and write to the end of the string. My idea for that was to read the file into an array of strings.
bool WriteXMLHeader(string header, ofstream xmlFile)
{
int fileSize = 1;
while(!xmlFile.eof())
{
fileSize++;
}
string entireFile[fileSize];
for(int i = 0; i < fileSize; i++)
{
xmlFile >> entireFile[i];
}
//Processing code to add more to the end
//Save the File
return true;
}
However, this causes an error where entireFile is of unknown size, and there are constants errors popping up.
I am not allowed to use any third party software (already looked into TinyXML and RapidXML).
What would be a better way to append to the end of an XML file above an unknown amount of closing tags?
Edit: My boss keeps talking about sending in a path to a node, and writing after the last instance of the node. He wants this capable of processing xml files with a million indents if needed. (Impossible for one man to accomplish?)
Upvotes: 1
Views: 83
Reputation: 47804
std::vector < std::string>
"I mentioned that, and my boss said no and to focus on strings"
Well this is what a most preferred, easiest, least error prone solution. Keeping aside you xml parsing, (if any), coming to the question/confusion, whatever it is.
Consider following:
#include <vector>
#include <string>
//...
std::vector < std::string > entireFile;
while ( std::getline(xmlFile, line) )
{
entireFile.push_back( line ) ;
}
xmlFile.close( );
// entireFile now contains all lines from xml file.
// To iterate its just like simple array
for( std::size_t i = 0; i < entireFile.size( ); ++i )
{
// entireFile[i]
}
Note: with <algorithm>
and <iterators>
you can achieve this in still fewer lines of code.
Suggested Reading: Why is iostream::eof inside a loop condition considered wrong?
If your boss says no, ask him why with courtesy, why ? There can't be any valid reason unless you're tired with specific environment/platform with limited capabilities.
Upvotes: 3