to get time and write it to a file in c

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • santhoshg
    New Member
    • Jul 2013
    • 1

    to get time and write it to a file in c

    i have to write the current time to a file ?how to do it
  • kiseitai2
    New Member
    • Jul 2007
    • 93

    #2
    I have never extracted the system time in c++, but I recently worked on my own io class. As a result, I can help you with the part that deals with writing to a file. First, become familiar with the ofstream class (http://www.cplusplus.com/reference/fstream/ofstream/). The class is not hard to implement as you basically need to specify the file to open. If no file with the specified name is found, ofstream will create a new file with that name. Then, you can pass a string by using the << operator, such that outputFile << timeString;. Finally, close the file so you don't leak file handles. I was a bit vague because I want you to try it and come back with clarification questions. :D

    Comment

    • Gobi Sakthivel
      New Member
      • Jan 2013
      • 26

      #3
      Code:
      
      
      #include <stdio.h>
      #include <time.h>
      #include <sys/time.h>
      
      void getTime()
      {
      	FILE* fp = fopen("Time.txt","w+");
          struct timeval usec_time;
          time_t now = time(0);
          gettimeofday(&usec_time,NULL);
          // format time
          struct tm *current = localtime(&now);
          printf("%d:%d:%d\n",current->tm_hour, current->tm_min, current->tm_sec);
          fprintf(fp,"%d:%d:%d\n",current->tm_hour, current->tm_min, current->tm_sec);
      }
      
      
      
      int main(int argc,char* argv[])
      {
      	getTime();
      }

      Comment

      Working...