Thread: Data File Help!!!

  1. #1
    Registered User
    Join Date
    Feb 2006

    Data File Help!!!

    I want to update a data file. If a == target then I want it to ignore a b and c and then print the rest of the file to the same file.

    Here is my code

    void list(string target)
      string a, b, c;
      ifstream tar("data.txt");
      ofstream fout("data.txt");
      while(! tar.eof())
         tar >> a >> b >> c;
         if(a != target)
            fout << a << b << c << endl;
    I have tried writing to data2.txt instead of data.txt and it works OK. But when I have it like the above my data.txt file looks like this 6.01347e - 154 with nothing else.

    Thanks in advance
    Last edited by noodle24; 09-23-2006 at 02:23 PM.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    I think you may have to close some streams or something before writing to them. Search for examples of fstream

  3. #3
    Registered User
    Join Date
    Jan 2005
    You shouldn't read and write to the file at the same time. Normally you would read in the file, storing the data that you want to keep in some sort of container. A string would be fine here (using +=). Then you write it all back out.

    Another thing to remember is that your loop will run one two many times. You should not check for eof() as the while loop control. Instead you should check the return value of the call to operator>>.

  4. #4
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    New York
    Another thing to remember is that calling ofstream on a file with no openmode (2nd) argument will automatically truncate it. This is unfortunate if it's like, important.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Replies: 3
    Last Post: 02-26-2008, 02:12 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-08-2007, 12:24 AM
  5. Writing and modifying data in a file
    By Micko in forum C Programming
    Replies: 2
    Last Post: 02-17-2005, 03:42 AM