//调用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为可执行文件的路径