Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C++
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{   //string record;

char key;

    ofstream fout;
    ifstream fin;

fin.open ("text.txt");
fout.open ("text1.txt");
    while(1){
        cin>>key;
             if (key=='a')
             {time_t currentTime = time(0);
               
               printf("The Current Time is %s", ctime(¤tTime));  
  
               fout << ctime(¤tTime);
                  
                 key=='0';

 
                       }
                       if (key =='b')
                       break;
                       }
                       fout.close();
system("PAUSE");
  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.

Thanks
Posted
Updated 17-Dec-12 4:52am
v4

1 solution

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

Input/Output files using C++[^]

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

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
 
Share this answer
 
v2
Comments
Quirkafleeg 17-Dec-12 7:15am    
+5. A rare occasion when a C++ question is answered using C++, rather than C!
Jibesh 17-Dec-12 14:50pm    
Thanks. Quirkafleeg.
Member 9689332 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 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.
eg:

ofstream myfile;
myfile.open ("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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900