guardando los cambios en el archivo

Ojective: To open config file, look for a particular line which has tag and change its value

Ejemplo:

    config .txt    
    bla bla    
    bla bla   
    SYSTEM_A_EXTERNAL_IP=192.168.0.57  // need to change ip address    
    bla bla   
    bla bla 

Lo que he hecho hasta ahora My code open the file and look for the particular line which has tag and change its value .

Problema: I failed to see those changes in the actual file. I am aware that ofstream will write into line but if I do ofstream instead of ifstream getline function gets an error.

Código1:

bool SetIpAddr(string & iAddr)    
{     
    bool check= false;    

    // Open  file    
    ifstream  iFile(IpConfigFile.c_str(), ios_base::out|ios::app | ios::binary);
    if(iFile.is_open())    
    {    
        check= true;    
    }          

    // Read content of ipconf file searching for the value of Head Id Name
    if(true == check)
    {
        string TargetName = SystemAIdValue + ExternalIpNamePostfix+ ValueAssignmentCharacter;
        string outbuf;
        while( !iFile.eof() )
        {
            getline(iFile, outbuf);    

            // find the matching string     
            if( 0 == outbuf.compare(0,TargetName.size(),TargetName) )
            {
            outbuf.erase(outbuf.begin()+TargetName.size(), outbuf.end());    
            outbuf.insert(0+TargetName.size(), iAddr);
                std::cout<< " after insertion  " << outbuf << std::endl;
                break;
            }
        }
    }
    // Close  (input) file
    if( iFile.is_open() )
    {
        iFile.close();
    }
    return check; 
}

Código2: Also doesnt work.

 bool SetIpAddr(string & aIpAddr)
 {
     bool lResult = false;    
     std::fstream  ifile("platform_ip_config");      
     string lTargetIp = HeadAIdValue + ExternalIpNamePostfix+ ValueAssignmentCharacter;
     std::deque<std::string>lines;
     std::string inbuf;
     while( std::getline(ifile, inbuf));
     {
         std::cout<<" we are in while"<<std::endl;
         std::cout<<" getline =="<< inbuf<< std::endl;
         std::cout<<" ip =="<<lTargetIp<< std::endl;
         if( 0 == inbuf.compare(0,lTargetIp.size(),lTargetIp) )
         {
             std::cout<<" we are in matching"<<std::endl;            
             std::cout<< inbuf << std::endl;
         inbuf.erase(inbuf.begin()+lTargetIp.size(), inbuf.end());
             std::cout<<" after erase " << inbuf << std::endl;
         inbuf.insert(0+lTargetIp.size(), aIpAddr);
             std::cout<< " after insertinon  " << inbuf << std::endl;        
         }
         lines.push_back(inbuf);
     } 
     ifile.seekg (0, ios::beg );
     std::copy(lines.begin(), lines.end(), 
     std::ostream_iterator<std::string>(ifile, "\n"));
  }
  lines.push_back(inbuf);
}
ifile.seekg (0, ios::beg );
std::copy(lines.begin(), lines.end(), 
std::ostream_iterator<std::string>(ifile, "\n"));
}

preguntado el 09 de marzo de 12 a las 13:03

ifstream = input file stream, ofstream = output file stream. If you want both: fstream. -

I have tried using fstream but in that case getline function doesnt work. I have added few debug statments to check it before posting -

it doesnt allow to paste all the contents of config file. The file permission is 777 for the config file just in case -

2 Respuestas

What you are doing is inherently tricky, writing to the middle of a file hoping the result will remain in place.

por ejemplo

192.168.120.111 

uses up a lot more characters than

10.10.10.10

the way i would do this is read the whole files into lines.

std::fstream file(file_name);
std::deque<std::string> lines;
std::string temp;
while(std::getline(file, temp))
{
    //detect that this the line you want
    if(this_is_my_line(temp)) 
    {
         //do what you need to do to the string
         modify(temp);
    }

    lines.push_back(temp);
}
file.seekg (0, ios::beg
//write back to file
std::copy(lines.begin(), lines.end(), 
          std::ostream_iterator<std::string>(file, "\n"));

Please note you do not need to explicitly close a file in C++, the RAII semantics will close it for you, by doing it your self your increasing the opportunity for bugs to creep into your code.

THIS WORKS ON MY SYSTEM

#include <iostream>
#include <fstream>
#include <string>
#include <deque>
#include <iterator>
int main()
{
    std::string line;
    const std::string token("SYSTEM_A_EXTERNAL_IP=");
    std::deque<std::string> lines;
    {
        std::ifstream file("config.txt");
        while(std::getline(file, line))
        {
            if(std::equal(token.begin(), token.end(), line.begin()))
            {
                line=token+"10.10.10.5"; //or whatever
            }
            lines.push_back(line);
        }
    }
    {
        std::ofstream file("config.txt");
        std::copy(lines.begin(), lines.end(),
             std::ostream_iterator<std::string>(file,"\n"));
    }
    return 0;
}

respondido 09 mar '12, 16:03

@1111111 , I am stil facing the same problem. it goes to while statement but temp is empty inside it. - samantha

well , in my case the above function doesnt even read line from getline. I have added a debug statement after while to check what are the contents in the temp but it seem to be empty. AM I DOING something wrong here? - samantha

it sounds like you are reading the wrong file or something like that - 111111

I dont think so , I have checked lot of times to make sure I am reading the correct file - samantha

can you add the exact file to your question? - 111111

By using an ifstream you are opening the file for reading, if you use the fstream base class instead you should be able modify the file

Another approach is to read the entire file into a buffer, make changes to the buffer and overwrite the original file using the ofstream class

respondido 09 mar '12, 13:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.