Reputation: 27
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.
Upvotes: 0
Views: 406
Reputation: 195
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 fopen
should 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.
Upvotes: 1
Reputation: 12732
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);
Upvotes: 2