Click here to Skip to main content
11,705,139 members (49,702 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C++
I want to write a C++ programmer to:
1. record the computer time when user click on the mouse
2. export the time to a file ( .txt)
3. update the file
For the first part, I have tried out:
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{   //string record;

char key;
    ofstream fout;
    ifstream fin; ("text.txt"); ("text1.txt");
             if (key=='a')
             {time_t currentTime = time(0);
               printf("The Current Time is %s", ctime(&currentTime));  
               fout << ctime(&currentTime);
                       if (key =='b')
  return 0;
But every time I restart the .exe, the .txt file is overwriten,
I need to keep the old data and update/insert the new data.

Posted 16-Dec-12 2:46am
Edited 17-Dec-12 4:52am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You can use the file stream classes to read/write files.

Input/Output files using C++[^]

#include <iostream>
#include <fstream>
using namespace std;
int main () {
  ofstream myfile; ("example.txt");
  myfile << "Writing this to a file.\n";
  return 0;
Quirkafleeg at 17-Dec-12 7:15am
+5. A rare occasion when a C++ question is answered using C++, rather than C!
jibesh at 17-Dec-12 14:50pm
Thanks. Quirkafleeg.
Member 9689332 at 17-Dec-12 8:41am
I can output the time but when I update the time, the old time is overwrote.
How can I update the new time into a new line?
jibesh at 17-Dec-12 14:55pm
Did you check the link i provided in my solution. you need to open a file with append flag on.

ofstream myfile; ("example.bin", ios::out | ios::app | ios::binary);

os::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.

Read the link carefully you will get the solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 595
1 OriginalGriff 289
2 Andy Lanng 175
3 CPallini 162
4 ppolymorphe 126
0 OriginalGriff 8,958
1 Sergey Alexandrovich Kryukov 8,276
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,606

Advertise | Privacy | Mobile
Web03 | 2.8.150819.1 | Last Updated 17 Dec 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100