我们知道,向文件中添加数据,a+参数只能在文件尾插入;
要想在文件前写入数据,我们可以先读取文件,(使用stat 函数 获取文件的所包含的字节数);
然后再写文件,再将读取的内容写入;
之所以要这样操作,是因为我们写日志,想将新日志放在文件首,定期清理文件尾的数据,避免时间久了,硬盘存储满了。
size_t filesize(const char* file_name)
{
size_t filesize = _maxFileSize+1;
if (file_name != NULL)
{
struct stat statbuff;
if(stat(file_name, &statbuff) == 0)
{
filesize = statbuff.st_size;
}
}
return filesize;
}
void func(uint16_t type)//type区分日志类型
{
FILE *fp;
char tmp[16];
char filetmp[16*256];
time_t t1 = time(NULL);
struct tm* tmCurTime;
tmCurTime = localtime(&t1);
fp = fopen(RUNLOG_FILENAME,"a+b");
if(fp==NULL)
{
printf("open %s error\n",RUNLOG_FILENAME);
return;
}
int ret= filesize(RUNLOG_FILENAME);
fread(filetmp,ret,1,fp);
fclose(fp);
fp = fopen(RUNLOG_FILENAME,"w+b");
if(fp==NULL)
{
printf("open %s error\n",RUNLOG_FILENAME);
return;
}
sprintf(tmp,"%04d%02d%02d%02d%02d%02d",1900+tmCurTime->tm_year,tmCurTime->tm_mon+1,tmCurTime->tm_mday,tmCurTime->tm_hour,tmCurTime->tm_min,tmCurTime->tm_sec);
type = htons(type);
memcpy(&tmp[14],&type,2);
fwrite(tmp,sizeof(tmp),1,fp);
fwrite(filetmp,ret,1,fp);
fclose(fp);
}