File I/O problem

This is a discussion on File I/O problem within the C++ Programming forums, part of the General Programming Boards category; I have a little problem with file I/O. I want to make a program that can open .cpp file, modify ...

  1. #1
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37

    File I/O problem

    I have a little problem with file I/O.
    I want to make a program that can open .cpp file,
    modify something and save it in out.cpp .
    The problem is that when I save file it
    is saved without identation.

    I think that problem is in this line :
    Code:
    ostream_iterator<string> os (file_output, "\n");
    When i change "\n" to " ", there are no newlines,
    whole code is in one line.
    How can I save file without loosing formatting ?

    Here is source of function that opens file,
    outputs file...
    PS: Sorry on mess, i am using tabs, and this board has some problems with tabs...

    Code:
    /*============================================================
        [function]  :   insertInfoHeader
        
        [arguments] :   1. name of file to open
    					2. name of output file
    					3. flags class
    	
    	[Purpose]	:	Inserts header like this 
    					above all functions in 
    					specified file.
    ============================================================*/
    void insertInfoHeader (char		inputFile[], 
    					   char		outputFile[],
    					   Flags	&infoHeaderFlags)
    {
    	ifstream file_input;
    	ofstream file_output;
    
        //  vector for saving contents of file...
    	vector <string> file_buffer;
        //  and its iterator
        vector <string>::const_iterator file_bufferBegin;
    
    	//string text;
    
    	try
    	{
            cout << "\nOpenning " << inputFile << "...";		
            file_input.open  (inputFile,  ios::in);
            file_output.open (outputFile, ios::trunc);
    
            if (!(file_input))
                reportError (FileErr ("Input"), OPEN_FAIL);
            if (!(file_output))
                reportError (FileErr ("Output"), OPEN_FAIL);
    
            const istream_iterator<string> is (file_input);
            const istream_iterator<string> eof;
                  ostream_iterator<string> os (file_output, "\n");
    
            copy (is, eof, back_inserter (file_buffer));
    
            //  can do stuff to vector now
            //  -
            copy (file_buffer.begin(), file_buffer.end(), os);
    
            //	iterate through buffer vector
            for (file_bufferBegin = file_buffer.begin();
                 file_bufferBegin != file_buffer.end();
                 ++file_bufferBegin)
            {
                cout << "\n->\t"
                     << file_buffer.back ();
                file_buffer.pop_back ();
            }
    
    	}
    	catch (exception &exc) 
    	{
    		cout << "\nException catched!\n"
    			 << __DATE__ << "\t" << __TIME__ <<" ."
    			 << "\nreport : " << exc.what ();
    	}		
    
        //  close opened files
    	file_output.close();
        file_input.close ();
    }
    ... and here are the files :

    Input :
    Code:
    Unit::Unit(int Moral, int HP, int Ammo, int ID):_ID(1000)
    {
    	try
    	{
    		Unit::_Moral = Moral;
    		Unit::_Ammo = Ammo;
    		Unit::_HP = HP;
    		Unit::_ID = ID;
    		incID();
    		Unit::_numOf++;
    
    		cout << "\n+\tUnit,\tID| " << Unit::_ID;
    		cout << " |.\t total | " << Unit::_numOf << " | units.\t+"
    			 << "\n______________________________________________________________";
    	}
    	catch(exception &exc)
    	{
    		cerr << exc.what();
    	}
    }
    ... and output:
    Code:
    Unit::Unit(int
    Moral,
    int
    HP,
    int
    Ammo,
    int
    ID):_ID(1000)
    {
    try
    {
    Unit::_Moral
    =
    Moral;
    Unit::_Ammo
    =
    Ammo;
    Unit::_HP
    =
    HP;
    Unit::_ID
    =
    ID;
    incID();
    Unit::_numOf++;
    cout
    <<
    "\n+\tUnit,\tID|
    "
    <<
    Unit::_ID;
    cout
    <<
    "
    |.\t
    total
    |
    "
    <<
    Unit::_numOf
    <<
    "
    |
    units.\t+"
    <<
    "\n______________________________________________________________";
    }
    catch(exception
    &exc)
    {
    cerr
    <<
    exc.what();
    }
    }
    *Sorry on lengthy post....
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,802
    The problem is because of how you are reading through the input file. The istream_iterator uses the stream extraction operator (>>) to parse through the input file which has the behavior of splitting all the input along whitespace (space/newlines/tabs). Therefore your first line of input:

    Code:
    Unit::Unit(int Moral, int HP, int Ammo, int ID):_ID(1000)
    gets split up into many seperate pieces according to the whitespace and stored in your vector as:

    Code:
    Unit::Unit(int
    Moral,
    int
    HP,
    int
    Ammo,
    int
    ID):_ID(1000)
    Which is therefore also how it shows up when you want to output it. All your formatting will get destroyed because the istream_iterator skips that formatting (tabs, etc...). I would suggest not using the copy function and istream_iterators in this case to read through the file and instead use a simple loop along with the getline function to read in entire lines of data from the input file at once and push those entire lines of data onto your vector. You should then still be able to use the copy function and the ostream_iterator to output the file.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37
    Thanks for help.
    It works fine now.
    Here's the changed code :

    Code:
    .
    .
    .
    string text
    .
    .
    .
    while (!std::getline(file_input, text).eof())
    {
        file_buffer.push_back (text);
    }
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  4. #4
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37
    There is one problem with this code...
    If the last line in file is not blank it runs into the infinite loop.
    How can this be solved?
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  5. #5
    Banned
    Join Date
    Jun 2005
    Posts
    594
    Code:
    while ( getline( file_input, text, '\n' ) )
    would let you read in a line at a time,
    and it will stop when it reach end of input,
    no need to check eof, also when your writing it
    just write the string then a newline, then all the
    rest formatting will be kept.

  6. #6
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37
    Is there some way for us lazy programmers?
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  7. #7
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    Is there some way for us lazy programmers?
    Lazy programmers use Python. If you want to use C++ then ILoveVectors's code will work just fine, and it's simpler than yours. If you want it even simpler, you can rely on the fact that getline always defaults to '\n'--widen('\n') actually--as the delimiter:
    Code:
    while (std::getline(file_input, text))
      file_buffer.push_back(text);
    
    if (!file_input.eof()) {
      // Fatal input error?
    }
    I added the test for eof after the loop so that you can tell how the loop broke. If it broke on end of file then you're solid. If not, some funky error happened--like a device error or something equally devastating--and you may need to deal with it. Most people don't bother with that though and just assume that when the loop breaks, it's because of end of file.
    Just because I don't care doesn't mean I don't understand.

  8. #8
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37
    Python? Weakest language i have ever programmed in....

    Thank you both. I will try and see what is better for me...
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  9. #9
    Linker.exe64
    Join Date
    Mar 2005
    Location
    Croatia,Pozega
    Posts
    37
    ILoveVectors's code works now. There was some problem in my code first time so it didn't work, but now works OK.
    Code:
     
     .J?+.                             ?`+.
       .+1P .++.                         ,+` 4++.
      .+zq\ .:.?i                      .!`?  .yz+.
      ?zdd ..:.^`J.                   ,!..?...Kyz+	
     .+dXM ..!p^.N.+                 ,,^.a..`.#XO+.
     .zwWM ^`.Mc`JMhJ.             .:JF`JM..^.#WOz`
      jwpMr`..NF.JMMM,!           .JMMF.dJ..`JNWrc
       0Wgb `!B:.MMMMM,:         ,.MMMF.j$.` NHSZ`
        TWMp`.+;`MMMMMM.:       ;.MMMMM.;+``JHW= 
          7Mh,``JMMMM"`          .TMMMMb``.H#"`
    

  10. #10
    Banned
    Join Date
    Jun 2005
    Posts
    594
    Quote Originally Posted by Narf
    I added the test for eof after the loop so that you can tell how the loop broke. If it broke on end of file then you're solid. If not, some funky error happened--like a device error or something equally devastating--and you may need to deal with it. Most people don't bother with that though and just assume that when the loop breaks, it's because of end of file.

    im sure if that happens the last concern they will have is if it the
    program completed successfully before everything crashed.

  11. #11
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    im sure if that happens the last concern they will have is if it the program completed successfully before everything crashed.
    You do realize that there's an error or two between 'perfect operation' and 'thermonuclear meltdown' that would take full advantage of such a test?
    Just because I don't care doesn't mean I don't understand.

  12. #12
    Banned
    Join Date
    Jun 2005
    Posts
    594
    i dont see your point, my point is if the hardware stops function
    due toa device drive causeing a crash or not working anymore.
    or the hardware actually breaking down, the file is not going
    to be read? and the program may not even continue to run.

  13. #13
    Nonconformist Narf's Avatar
    Join Date
    Aug 2005
    Posts
    174
    i dont see your point
    Clearly.
    my point is if the hardware stops function
    due toa device drive causeing a crash or not working anymore.
    or the hardware actually breaking down, the file is not going
    to be read? and the program may not even continue to run.
    Okay, let's think of it in a light that's easier to follow. Say the stream operates on a file that's on a floppy, and the floppy is removed during an input or output operation. This won't cause the program to crash, but it will cause the badbit to be set for the stream. The loop will end, and if you assume it's because of end of file, data might be lost even though the program is still running. I'm sure you'll agree that data loss is a bad thing. And if you don't know about it, you can't fix it.
    Just because I don't care doesn't mean I don't understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  2. File i/o problem
    By tezcatlipooca in forum C++ Programming
    Replies: 18
    Last Post: 01-01-2007, 08:01 AM
  3. File I/O problem
    By Onions in forum C++ Programming
    Replies: 41
    Last Post: 02-24-2006, 03:32 PM
  4. Replies: 3
    Last Post: 03-04-2005, 01:46 PM
  5. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM

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