Tuesday, 8 January 2019

Instead of print write the data to file with timestamp

 Instead of print write the data to file with timestamp


Program:


/* Instead of print write to file by Velraj.K
 * Check : http://velrajcoding.blogspot.in
 */

#include <stdio.h>
#include <time.h>  // For time
#include <stdarg.h>  // For va_start

#define TIME_BUF    25
void write_to_default_file(const char *format, ...)
{
    va_list args;
    FILE * fp;
    time_t tim;   // not a primitive datatype
    char str_time[TIME_BUF] = {0};
    struct tm *time_local = NULL;

    fp = fopen ("vel_test.txt", "a+");
    va_start(args, format);
    time(&tim);
    /* Ctime automatically append new line to the output, so we count not use
     * EG: time_str = ctime(&t); // Ctime giving automatically new line, so not using
     */
     // Tue Dec 18 12:01:25 2018
    time_local = localtime(&tim);
    /*
     * A for full weekend, B for Full Month name
     * EG: strftime(s, 100, "%A, %B %d %Y %H:%M:%S", p);
     * a for abbrevated weekend, b for abbreviated month name.
     */
    strftime(str_time, TIME_BUF, "%a %b %d %H:%M:%S %Y", time_local);
    fprintf(fp, "%s:: ", str_time);
    vfprintf(fp, format, args);
    fprintf(fp, "\n");
    va_end(args);
    fclose(fp);
}


int main()
{
    write_to_default_file("Vel test %s = %d ", "id", 100);
}

Output:
labuser@labuser-virtual-machine:~/velrajk/sample$ cat vel_test.txt
Tue Jan 08 21:42:13 2019:: Vel test id = 100
Tue Jan 08 21:42:14 2019:: Vel test id = 100
Tue Jan 08 21:42:14 2019:: Vel test id = 100
labuser@labuser-virtual-machine:~/velrajk/sample$



No comments:

Post a Comment