//調用errorlog 函數可以向指定的logfile檔案中寫入自訂的結構體error_message類型的資料
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/signal.h>
#include <time.h>
#include <errno.h>
struct error_message
{
time_t occur_time;//錯誤發生的時間
const char * filename;//產生錯誤的檔案
int occur_no;//錯誤發生的行號
const char *error_content;//錯誤的內容
};
typedef struct error_message error_message_t;
void errorlog(const char* logfile, error_message_t *emt)
{
FILE *fp;
struct tm ts;
char time[20];
int exist=0;
localtime_r(&(emt->occur_time),&ts);
sprintf(time,"%04d.%02d.%02d %02d:%02d:%02d",ts.tm_year+1900,ts.tm_mon+1,ts.tm_mday,ts.tm_hour,ts.tm_min,ts.tm_sec);
exist=access(logfile,F_OK);//判斷檔案是否存在,不存在返回-1
fp=fopen(logfile,"a+");
if(fp!=NULL)
{
if(exist<0)
{//檔案不存在
fprintf(fp,"%20s/t%20s/t%5s/t%s/n","錯誤時間","檔案名稱","行號","錯誤內容");
}
fprintf(fp,"%s/t%s/t%d/t%s/n",time,emt->filename,emt->occur_no,emt->error_content);
}
else
{
printf("error:%s/n",strerror(errno));
}
signal(SIGXFSZ, SIG_DFL);
fclose(fp);
}
int main(int argc,char **argv)
{
error_message_t emt;
bzero(&emt,sizeof(emt));
time(&(emt.occur_time));
emt.filename=__FILE__;
emt.occur_no=__LINE__;
emt.error_content="test";
errorlog("/home/henry/stat/logfile.txt",&emt);
}
有時我們有這樣的需求,那就是刪除某個目錄下到期的檔案,可以由下面的函數實現:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <time.h>
#include <string.h>
#include <errno.h>
void clean_file(char* cleandir,int days)
{//刪除cleandir目錄下days天前的檔案
DIR *dir;
struct dirent *de;
struct stat buf;
time_t tim;
int i;
dir=opendir(cleandir);
if(dir==NULL)
{
printf("open directory %s error:%s/n",cleandir,strerror(errno));
return;
}
chdir(cleandir);
while((de=readdir(dir))!=NULL)
{
bzero(&buf,sizeof(buf));
i=lstat(de->d_name,&buf);
if(i<0)
{
printf("i=%d,de->d_name=%s/n",i,de->d_name);
break;
}
else
{
if(S_ISDIR(buf.st_mode))
{
if((strcmp(de->d_name,".")==0)||(strcmp(de->d_name,".."))==0)
continue;
clean_file(de->d_name,days);
}
else
{
time(&tim);
if(tim-days*24*60*60>buf.st_mtime)
{
printf("delete file:%s/n",de->d_name);
unlink(de->d_name);//delete file
}
}
}
}
closedir(dir);
}
int main()
{
clean_file("/home/henry/programtest",30);
}
//該程式有個缺陷,就是對於programtest 下不能有更多的子目錄了。
可以從shell指令碼中啟動某個程式,指令碼內容:
#!/bin/sh
/home/henry/programtest/cleanfile
exit
其中/home/henry/programtest/cleanfile為可執行檔的路徑