在c中为日期和时间添加文件名

时间:2014-07-30 06:27:33

标签: c

我正在寻找一种方法将当前日期和时间添加到我打开的日志文件中 现在我正在使用:

fopen("/var/log/SA_TEST","w");

如何制作

fopen("/var/log/SA_TEST_DATE_AND_TIME","w");

很多 (在c)

5 个答案:

答案 0 :(得分:10)

strftime可用于格式化日期:

#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");

您可以根据strftime manual更改日期的时间格式。

您可以将时间戳用作紧凑格式&#39;结果只有time

sprintf(filename, "/var/log/SA_TEST_%d", (int)now);

答案 1 :(得分:5)

/* 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;
}

输出

/var/log/SA_TEST_Wed_Jul_30_12:17:19_2014

答案 2 :(得分:2)

  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");

参见: man strftime 对于格式,您可以获得时间和日期。

答案 3 :(得分:0)

以下列方式使用sprintf

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");

答案 4 :(得分:0)

#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);
}