0

i used to use C years ago and am not proficient on it anymore however i needed some code to output the current date and time in the format "YYYY-MM-DD HH:MM:SS " to a file called TIME.TXT. and i would need this .txt file to be output to my desktop or a certain location. if anyone could please help me or even direct me to some answers so i could find the solution to my problem then i would be eternally grateful!!!

also i don't know if this helps but im on a mac, anything at all would help greatly.

the code doesn't necessarily have to be C, if there is anything easier that i could use then please feel free to advise me so that i can do that!

Thank you in advance :)

Bradley
  • 19
  • 1

2 Answers2

2

The following C program writes current date and time into a text file named TIME.txt in the c:\temp folder.

#include <stdio.h>
#include <time.h>

#define LEN 256
int main()
{
   FILE * fp;

   /* open the file for writing*/
   fp = fopen("c:\\temp\\TIME.txt","w");
 
   /* write time as text into the file stream*/
   char cur_time[128];
  
   time_t      t;
   struct tm*  ptm;
  
   t = time(NULL);
   ptm = localtime(&t);
   
   strftime(cur_time, 128, "%Y-%m-%d %H:%M:%S", ptm);
   
   fprintf(fp, "%s\n", cur_time);
   
   /* close the file*/  
   fclose(fp);
   return 0;
}

Output:

2020-08-09 09:27:28
Nishan
  • 3,644
  • 1
  • 32
  • 41
1

If you just want to do it quickly you can run it from the terminal, as you are using a mac you can just use the bash command:

date "+%Y-%m-%d %H:%M:%S" > TIME.TXT

Otherwise, you can use this same string in c++ using the ctime package which has been answered before: Current date and time as string

If you are calling your code from the terminal you can just use the > to output the result to the file, otherwise you can use an ostream to write to a file.

edit: As user anki notes in the comments below, > will overwrite TIME.TXT. You can use >> to append to the file and keep previous timestamps.

frazb
  • 76
  • 2
  • Please mention `>>` operator for appending time to the file. timestamps are normally used relative to other timestamps. –  Aug 09 '20 at 09:45