Reputation: 1101
Im looking for a way to add the current date and time to a log file im opening for now im using :
fopen("/var/log/SA_TEST","w");
How to make it
fopen("/var/log/SA_TEST_DATE_AND_TIME","w");
Thx a lot (In c)
Upvotes: 9
Views: 23305
Reputation: 1
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
printf("Runfile: %s Date: %s Time : %s \n", __FILE__, __DATE__, __TIME__ );
FILE *fptr;
char *fmode, filename[255], strtime_sec[20], strtime_nsec[20];
struct tm* tm;
struct timespec ts;
time_t now;
now = time(NULL); // get current time
tm = localtime(&now); // get time structure
// Get current time from system clock
clock_gettime(CLOCK_REALTIME, &ts);
// Convert integer times to strings using snprintf()
snprintf(strtime_sec, 20, "%d", ts.tv_sec);
snprintf(strtime_nsec, 20, "%ld", ts.tv_nsec);
// Generate dynamic filename and set filemode
sprintf(filename, "file_%04d%02d%02d_%s.txt", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, strtime_sec);
fmode = "a";
// Open file and write some text into the file
fptr = fopen(filename, fmode);
if (fptr == NULL) {
printf("Cannot open filename \n");
exit(0);
}
// Test by writing text into the file stream using fprintf()
fprintf(fptr, "# Runfile: %s Date: %s Time : %s \n", __FILE__, __DATE__, __TIME__ );
int i; double value, result;
value = 0.5;
for(i = 0; i < 10; i++) {
result = value/5.5;
fprintf(fptr, "%d \t %f \t %f \n", i, value, result);
value = value * 2.5;
}
fclose(fptr);
return(0);
}
Upvotes: 0
Reputation: 493
strftime
can be used to format the date an time :
#include <time.h>
char filename[40];
struct tm *timenow;
time_t now = time(NULL);
timenow = gmtime(&now);
strftime(filename, sizeof(filename), "/var/log/SA_TEST_%Y-%m-%d_%H:%M:%S", timenow);
fopen(filename,"w");
You can change the date an time format for whatever you want according to the strftime manual.
You can use the timestamp as 'compact format' with the result of time
only.
sprintf(filename, "/var/log/SA_TEST_%d", (int)now);
Upvotes: 13
Reputation: 6674
time_t rawtime;
struct tm * timeinfo;
char buffer [64];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer,64,"/var/log/SA_TEST_%x_%X",timeinfo);//generate string SA_TEST_DATE_TIME
fopen(buffer, "w");
Refer:
man strftime
for the formats you can get time and date in.
Upvotes: 3
Reputation: 27210
/* ctime example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, time, ctime */
int main ()
{
time_t rawtime;
char buffer [255];
time (&rawtime);
sprintf(buffer,"/var/log/SA_TEST_%s",ctime(&rawtime) );
// Lets convert space to _ in
char *p = buffer;
for (; *p; ++p)
{
if (*p == ' ')
*p = '_';
}
printf("%s",buffer);
fopen(buffer,"w");
return 0;
}
Output is
/var/log/SA_TEST_Wed_Jul_30_12:17:19_2014
Upvotes: 7
Reputation: 1149
Use sprintf
in following way
char date_time[30]; //Collect system date and time in this character array
char filename[40]
sprintf(filename, "/var/log/SA_TEST_%s", date_time);
fopen(filename,"w");
Upvotes: 1