0

I want to output time to a text file, and the time should be formatted as (dd-mm-yy). I've referred to How to print time in format: 2009‐08‐10 18:17:54.811 (using code from top answer) and I am now stuck with this piece of code:

int main()
{
    time_t timer;
    char buffer[26], line[50]; // Hoping to feed in date and time into a string (line[50])
    struct tm* tm_info;

    time(&timer);
    tm_info = localtime(&timer);

    strftime(buffer, 26, "%d-%m-%y %H:%M:%S", tm_info);
    puts(buffer);


    return 0;
}

Which give mes an output of the current local time and date in the format (dd-mm-yy) and (hh-mm-ss) on stdout. So now I'm just wondering if I can feed this format into a text file as well.

Thanks for any help.

  • So your actual question is "How can I write text into a file rather than on the screen", right? Please confirm. – Jabberwocky Nov 29 '18 at 11:37
  • Yes. I'm stuck at assignment so I can't really go through with writing the time into the file yet. – partynextdoor18 Nov 29 '18 at 11:39
  • It's `int main(void)` and your code does not compile. – Swordfish Nov 29 '18 at 11:41
  • Next time when you ask a question please focus on your actual problem, time functions and other time related questions are not related to your problem, so you should not have mentioned them. – Jabberwocky Nov 29 '18 at 11:41
  • Look into [`fopen`](http://www.cplusplus.com/reference/cstdio/fopen/) and [`fputs`](http://www.cplusplus.com/reference/cstdio/fputs/) and read the chapter dealing with files in your C text book. – Jabberwocky Nov 29 '18 at 11:43

2 Answers2

2

You can use fopen,fclose and fputs to write to a file.

For more info read fopen. fclose. fputs.

Example:

FILE *fp = fopen("time.txt", "w");
if (fp == NULL) return 1;
fputs(buffer, fp);
fclose(fp);
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
1

Use the fputs function. Add this code after your puts(buffer) line.

FILE* file = fopen("yourtextfile.txt","w");
if (file != NULL){
    fputs(buffer,file);
    fclose(file);
}

The second parameter in fopenshould be changed according to your needs: "w" will erase what was previously written in the file, "a" will append (write at the end of your file). In both cases, the file will be created if it doesn't exist.

Alex
  • 195
  • 7