Data File Help!!!

This is a discussion on Data File Help!!! within the C++ Programming forums, part of the General Programming Boards category; I want to update a data file. If a == target then I want it to ignore a b and ...

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    27

    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

    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
    Location
    Ireland
    Posts
    2,262
    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
    Posts
    7,319
    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
    Location
    New York
    Posts
    1,465
    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.

    ╔╗╔╦══╦╗╔╦══╦╗
    ║╚╝║╔╗║╚╝║╔╗║║
    ║╔╗║╠╣║╔╗║╠╣╠╣
    ╚╝╚╩╝╚╩╝╚╩╝╚╩╝

    codez http://code.google.com/p/zxcvbn/

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, 01:12 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 04:02 AM
  4. Bitmasking Problem
    By mike_g in forum C++ Programming
    Replies: 13
    Last Post: 11-07-2007, 11:24 PM
  5. Writing and modifying data in a file
    By Micko in forum C Programming
    Replies: 2
    Last Post: 02-17-2005, 02:42 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21