文件大小保护

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;  
}  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值