开发者

Inserting a tag in between xml using C++

开发者 https://www.devze.com 2023-02-20 14:26 出处:网络
I have a xml inside which I wish to insert the tag using insert() of string class. Here is my xml: < ? xml version=\"1.0\" ? >

I have a xml inside which I wish to insert the tag using insert() of string class.

Here is my xml:

< ? xml version="1.0" ? >
< Dependency_Structure >
   < Main_Package >
      < Package_Name >
         WinTools
      < /Package_Name >
      < Header_File >
         WinTools.h
      < /Header_File >
      < Implementation_File >
         WinTools.cpp
      < /Implementation_File >
   < /Main_Package >
   < Dependenci开发者_开发百科es >
      < Dependency_Package >
         wintools
      < /Dependency_Package >
   < /Dependencies >
< /Dependency_Structure >

Here is my function code which is aborting the execution of the program whenever I try to execute it:

std::string line,str;

std::fstream myfile(xmlFileName, ios::out | ios::in);
//myfile.open()
 if(myfile.is_open())
 {
        getline(myfile,line);
        size_t pos=line.find("</Dependency_Package >");
        line.insert(pos,fileInput);

 }
 else
    std::cout<<"Unable to open the file. "<<endl;
myfile.close();


Two things. First, you are not testing the result of the find to see if the position is greater or equal to zero. Second, if you are going to insert and save back to the file, you are closing the file before the insert.


Your mistake here is trying to write to line instead of writing to the file itself.

line is the string you just read. This is how you could write to the file:

// Move the write cursor where read cursor is currently located 
// (or wherever you want it to be)
myfile.seekp(myfile.tellg());
myfile << "<CheckThisTag>\n\t YEAH BABY\n<\\CheckThisTag>\n";
0

精彩评论

暂无评论...
验证码 换一张
取 消