最近在做linux程序的时候遇到需要将当前的时间作为文件名称创建日志文件的需求,考虑到这种需求比较普遍,在此将完成的程序献上,并附上个人学习中的一些注释:
#include <stdio.h>//FILE type needs this header file
#include <sys/time.h> //getting time needs this header file
#include <sys/types.h> //writing and reading file needs this header file
//#include <linux/rtc.h>
FILE *fp;
void main(){
char FilenameHdr[80] = "new_log_";
/*transfer the local system time as the log file name */
char FilenameEnd[80];
time_t timep;
struct tm *p;
time(&timep);
p=localtime(&timep); /*get the local time*/
sprintf(FilenameEnd, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d", (1900+p->tm_year),(1+p->tm_mon), p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
//printf("%s\n", FilenameEnd);
/*add the timestamp at the end of log filename*/
int i = 0;
int j = 0;
while(FilenameHdr[i] != '\0'){
i++;