添加日志文件
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<unistd.h> 4 #include<string.h> 5 #include<errno.h> 6 #include<sys/types.h> 7 #include<sys/stat.h> 8 #include<fcntl.h> 9 #include<time.h> 10 11 void writelog(const char* log) 12 { 13 time_t tDate; 14 struct tm* eventTime; 15 time(&tDate);//得到系统当前时间 16 eventTime=localtime(&tDate);//将time_t数据类型转化为struct tm结构 17 int iYear = eventTime->tm_year+1900; 18 int iMon = eventTime->tm_mon +1; 19 int iDay =eventTime->tm_wday; 20 int iHour = eventTime->tm_hour; 21 int iMin = eventTime->tm_min; 22 int iSec = eventTime->tm_sec; 23 24 printf("wday =%d\n",eventTime->tm_wday); //星期几 25 printf("wday =%d\n",eventTime->tm_yday); //从一月一号到现在多少天了 26 printf("eventTime->tm_isdst = %d\n",eventTime->tm_isdst); 27 28 char sDate[16]; 29 sprintf(sDate,"%04d-%02d-%02d",iYear,iMon,iDay); 30 char sTime[16]; 31 sprintf(sTime,"%02d:%02d:%02d",iHour,iMin,iSec); 32 char s[1024]; 33 sprintf(s,"%s %s %s\n",sDate,sTime,log); 34 FILE* p=fopen("my.log","a+"); 35 if(p==NULL) 36 { 37 printf("write log my.log error:%s\n",strerror(errno)); 38 } 39 else 40 { 41 fputs(s,p); 42 fclose(p); 43 } 44 } 45 46 int main(int arg, char *args[]) 47 { 48 writelog("process begin"); 49 printf("hello world\n"); 50 writelog("process end"); 51 52 return 0; 53 }