windows C++ 判断文件大小,清空文件,写日志

windows C++ 判断文件大小,清空文件,写日志等几个常见的接口,记录一下备忘

#include <iostream>
#include <vector>
#include<Windows.h>
#include<string>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
using namespace std;

//清除文件
void ClearFile(string p_strFile)
{
	FILE *fp = fopen(p_strFile.c_str(), "w");
	if (fp!= NULL)
	{
		fclose(fp);
		printf("文件已清空。\n");
	} 
	else 
	{
		perror("无法打开文件");
	}
}

//获取文件大小
int getFileSize() 
{
	struct stat fileStat;
	const char* filePath = "D:\\LOG.ini";
	if (stat(filePath, &fileStat) == 0) 
	{
		// 文件大小以字节为单位,存储在st_size成员变量中
		std::cout << "文件大小为: " << fileStat.st_size /1024/1024<< "M" << std::endl;
	} 
	else
	{
		perror("获取文件状态失败");
		return	-1;
	}

	return fileStat.st_size /1024/1024;
}

//写日志文件
int writelog(string p_str_filename , string p_str_log) 
{
	SYSTEMTIME timeCur;
	GetLocalTime(&timeCur);
	char t_logbuffer[1024] = {0};
	sprintf(t_logbuffer , ("%04d%02d%02d_%02d:%02d:%02d:%03d,")
		, timeCur.wYear, timeCur.wMonth, timeCur.wDay
		, timeCur.wHour, timeCur.wMinute, timeCur.wSecond , timeCur.wMilliseconds);

	p_str_log+="\n";
	strcat(t_logbuffer , p_str_log.c_str());
	t_logbuffer[1024-1]='\0';
	FILE*FP = fopen(p_str_filename.c_str()  , "a+");
	if(FP==NULL)
	{
		return -1;
	}
	fwrite(t_logbuffer , 1 , strlen(t_logbuffer),FP);
	fclose(FP);
	return 0;
}

int main() 
{
	while(true)
	{
		int t_size = getFileSize();
		if(t_size>5)
		{
			ClearFile("D:\\LOG.ini");
		}
		writelog("D:\\LOG.ini" , "123456789");
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值