CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2009
    Posts
    5

    Which file mode to use

    My problem is that I have to modify a record in a text file. Suppose there are 10 records in a file and I have modify the 5th record. I am trying to do this with the help of tellg and seekp.

    Whenever I use fout.open("filename"), the previous contents of the file are discarded/deleted. Which filemode do I use which allows me to use seekp and at the same time, doesn't delete the contents of the file. I cannot use ios::app because seekp can't be used then. Even ios::ate is deleting the contents of the file.

    If there is no file mode to do this, then I can think of only one solution, i.e. to copy till the 4th record to another file, write the modified 5th record to the second file, and then write the remaining records from the first file to second file. After this, remove the first file and rename the second file.

    Please help.

  2. #2
    Join Date
    May 2007
    Location
    Scotland
    Posts
    1,164

    Re: Which file mode to use

    The way to do it is to read the data into memory, modify it in memory and then write it back out. e.g.

    Code:
      const char* filename = "file.txt";
      std::string data;
    
      std::ifstream infile(filename,std::ios_base::binary);
      if(infile.is_open())
      {
        //Read data into string object and then close the file
        data.assign(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>());
        infile.close();
    
        //print the file if you like
        //std::cout << data << std::endl;
    
        //modify data here...
        //...
    
        //write the modified data to the file
        std::ofstream outfile(filename,std::ios_base::binary);
        if(outfile.is_open())
        {
          outfile.write(data.c_str(), data.size());
          infile.close();
        }
        else
        {
          std::cout << "Unable to open " << filename << " for writing!" << std::endl;
        }
      }
      else
      {
        std::cout << "Unable to open " << filename << " for reading!" << std::endl;
      }

  3. #3
    Join Date
    Jan 2009
    Posts
    5

    Re: Which file mode to use

    Thanks anyways I managed to modify the record by using the method of writing to another file and then renaming it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured