File IO

This is a discussion on File IO within the C++ Programming forums, part of the General Programming Boards category; I have created a file(file.dat) and have written the following 3 lines.Later i want to delete the second line in ...

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    277

    File IO

    I have created a file(file.dat) and have written the following 3 lines.Later i want to delete the second line in the following way-but this is not happening. When i open the file some garbage is being shown and i see no lines which was written at the starting.May i know where i am wrong?

    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        ofstream fout("file.dat",ios::out);
        fout << "Sunanda 5 \n";
        fout << "Rahool 10 \n";
        fout << "Sunetra 12 \n";
        fout.close();
        
        ofstream fapp("file.dat",ios::out);
        fapp.seekp(23);
        int i = 0;
        while(i < 11)
        {
                fapp << '\b';
                i++;
        }        
        fapp.close();
        system("pause");                   
    }

  2. #2
    ZuK
    ZuK is offline
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Thera are a couple of mistakes in your code.
    First of all
    Code:
    ofstream fapp("file.dat",ios::out);
    truncates the file. So the following code operates on an empty file.
    you would have to use
    Code:
    ofstream fapp("file.dat",ios::out|ios::app);
    In that case the file would not be cleared when opened.
    But I guess that the effect would still not be what you want. Your code would just append a series of backspace characters to the end of the file.
    If you want to remove a line from the file you have to read in the complete file and write it again without the line that you want to remove.
    Kurt

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 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. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  5. File IO with .Net SDK and platform SDK
    By AtomRiot in forum Windows Programming
    Replies: 5
    Last Post: 12-14-2004, 09:18 AM

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