clear contents of text file?

Nov 24, 2008 at 3:41pm
Hi guys,

I have set up a transaction log to log different bank account transactions.

as my first menu choice option below is to print the log from the text file to console, is there a way of clearing the contents inside text file say if i choose option2?

if(menuChoice == 1)
{
infile.open("transactionLog.txt");
while(infile.is_open())
{
while(!infile.eof())
{
getline(infile,line);
cout << line << endl;
}
infile.close();
infile.clear();
system("PAUSE");
system("CLS");
}
}
else if(menuChoice == 2)
{

//Clear transactionLog.txt code here

}
Nov 24, 2008 at 3:50pm
The far as i know, if you open a file using ofstream the file will automaticly be cleared unless you tell the program otherwise.

Here you should find all you need:
http://www.cplusplus.com/reference/iostream/ofstream/
Nov 24, 2008 at 5:02pm
Opening an ofstream with ios::trunc flag will explicitally tell the stream to be cleared
Nov 24, 2008 at 7:14pm
how do i declare an ofstream of ios::trunc flag?
Last edited on Nov 24, 2008 at 7:15pm
Nov 24, 2008 at 9:14pm
Hmm, that link doesn't provide an example...

All you need is to #include <fstream> and you have it declared for you. All you need to do is use it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// truncate.cpp

#include <fstream>
#include <iostream>
using namespace std;

int usage( ostream& outs, int result )
  {
  outs << "usage:\n"
          "  truncate FILE ...\n\n"
          "Zeros the named files.\n";
  return result;
  }

int main( int argc, char* argv[] )
  {
  if (argc == 1) return usage( cout, 0 );

  for (int n = 1; n < argc; n++)
    {
    // Does file exist?
    fstream f( argv[ n ], ios::in );
    if (f)
      {
      // Yes, truncate it
      f.close();
      f.open( argv[ n ], ios::out | ios::trunc );
      }
    // No, or file could not be modified
    if (!f)
      cerr << "Could not truncate \"" << argv[ n ] << "\"\n";
    // Close file (if open)
    f.close();
    }

  return 0;
  }

Hope this helps.
Topic archived. No new replies allowed.