Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,383 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,396 people online right now. Registration is fast and FREE... Join Now!




Clearing a filestream object

 
Reply to this topicStart new topic

Clearing a filestream object

Rioghasarig
22 Jan, 2008 - 02:16 PM
Post #1

New D.I.C Head
*

Joined: 4 Jan, 2008
Posts: 3

Is there a function that completely clears all text from a text file? I've tried clear() but apparently that only clears one line.
User is offlineProfile CardPM
+Quote Post

nirvanarupali
RE: Clearing A Filestream Object
22 Jan, 2008 - 06:06 PM
Post #2

D.I.C Stomach
Group Icon

Joined: 1 Aug, 2007
Posts: 994



Thanked: 4 times
Dream Kudos: 375
My Contributions
Well, you have to write your own function or you can directly use the ios::out ios::trunc

Here is the link to start with:

http://en.wikipedia.org/wiki/Fstream

Example:
CODE
char buffer[255];
    char file[80];
    cout <<"Enter filename: ";
    cin >>file;
    
    ofstream fout(file); //Open for writing
    fout << "This line written directly to the file...\n";
    cout << "Enter text for the file: ";
    
    cin.ignore(1,'\n');  // eat the newline after the file name
    cin.getline(buffer,255);  // get the user's input
    fout << buffer << "\n";   // and write it to the file
    fout.close();             // close the file, ready for reopen
    
    ifstream fin(file);    // reopen for reading
    cout << "\nHere's the contents of the file:\n" << endl;
    char ch;
    while (fin.get(ch))
        cout << ch;

    cout << "\n***End of file contents.***\n";
    fin.close();
    
    
    
    cout <<"\nErase what is written" << endl;
    system("pause");
    
    //file is now empty due to ios::trunc
    fin.open(file, ios::out | ios::trunc);
    
    fin.close();

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/7/09 09:42AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month