2014年3月24日09:53:59
文件大小保护
1、使用VS2008创建一个带预编译头的控制台项目。
2、源文件内容:
#include "stdafx.h"
#include <sys/stat.h>
#include <time.h>
#include<iostream>
using namespace std;
//#define LOG_FILE_MAX_SIZE 10*1024*1024
#define LOG_FILE_MAX_SIZE 5
bool getLogFile_NewName(char * strNewFileName,char * strOldFileName)
{
tm * pNowTm;
time_t nowTime;
nowTime = time(NULL);
pNowTm = localtime(&nowTime);
char strTmp[40]={0};
sprintf(strTmp,"_%02d%02d%02d",pNowTm->tm_mday,pNowTm->tm_hour,pNowTm->tm_min);
strncpy(strNewFileName,strOldFileName,strlen(strOldFileName)-4);
strcat(strNewFileName,strTmp);
strcat(strNewFileName,".txt");
return true;
}
void protectLogFileSize(char * strFileName)
{
struct stat buf;
if(0 != stat(strFileName, &buf))
{
printf("获得文件大小失败\n");
return;
}
if(buf.st_size < LOG_FILE_MAX_SIZE)
return;
char ch;
printf("准备重命名文件\n");
cin>>ch;
char strNewFileName[_MAX_PATH]={0};
if(!getLogFile_NewName(strNewFileName,strFileName))
{
printf("获得新文件名失败\n");
}
if(0 !=rename(strFileName,strNewFileName))
{
printf("重命名文件失败\n");
}
return;
}
int main( void )
{
char ch;
char * strFileName = "a.txt";
FILE * pFileR = fopen(strFileName,"r");
if(NULL == pFileR)//文件不存在。创建文件
{
FILE * pFileW = fopen(strFileName,"w");
if(NULL == pFileW)
{
printf("文件创建失败\n");
cin>>ch;
return 1;
}
else
{
fprintf(pFileW,"%s \n","1234567890");
fclose(pFileW);
}
}
else
{
fclose(pFileR);//不要用NULL调用该函数
}
printf("准备文件大小保护\n");
cin>>ch;
protectLogFileSize(strFileName);
cin>>ch;
return 0;
}