电脑垃圾太多?自己用c++做一个清理垃圾程序

说明:本文章主要是小编对于文件操作的一个总结,实用性不强,但是可以参考。

本文章代码已放在结尾,并在csdn上传资源,大家可以点击https://download.csdn.net/download/CSDN_Anonymous/21425579下载。但是资源需要三积分的,如果不想花积分,请高抬贵手,点击一下关注,再翻到本文章最后复制吧~(*^▽^*)

首先,清理文件的前提是找到文件。所以,我们首先要写一个获取文件夹里文件地址的代码(这个是我从csdn上复制来的):

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include<io.h>
using namespace std;
void getAllFiles(string path, vector<string>& files){
	long   hFile = 0;
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do
		{
			if ((fileinfo.attrib &  _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
				{
					files.push_back(p.assign(path).append("/").append(fileinfo.name));
					getAllFiles(p.assign(path).append("/").append(fileinfo.name), files);
				}
			}
			else{
				files.push_back(p.assign(path).append("/").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

int main(){
	string DATA_DIR = "文件夹路径";
	vector<string> files;
	getAllFiles(DATA_DIR, files);
	int size = files.size();
	int  FaiNum = 0;
	cout<< size << endl;
	for (int i = 0; i<size; i++){
		cout << files[i] << endl;
	}
	fclose(stdout);
	return 0;
}

好的,我们得到了一个文件夹里所有文件的地址。下一步就是清理了。当然清理不是清空,应该先筛选文件。我们可以将垃圾文件定义为很长时间没有打开的文件,所以我们要找到文件的最后访问时间(为了凑字数,我写了一大堆废话)。代码如下(再次说明:下面代码“学习”于某博客文章):

#include <windows.h>
#include <stdio.h>
//----------- Error Handling Function -------------------
void error(LPSTR lpszFunction){ 
    CHAR szBuf[80]; 
    DWORD dw = GetLastError(); 
    sprintf(szBuf, "%s failed: GetLastError returned %u\n", 
        lpszFunction, dw); 
    MessageBox(NULL, szBuf, "Error", MB_OK); 
    ExitProcess(dw);
}
//--------------------------------------------------------

BOOL GetFileTime(HANDLE hFile, LPSTR lpszCreationTime,LPSTR lpszLastAccessTime,LPSTR lpszLastWriteTime)
{
    FILETIME ftCreate, ftAccess, ftWrite;
    SYSTEMTIME stUTC1, stLocal1,stUTC2,stLocal2,stUTC3,stLocal3;

    // -------->获取 FileTime
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite)){
error("GetFileTime()");
        return FALSE;
}
    //---------> 转换: FileTime --> LocalTime
    FileTimeToSystemTime(&ftCreate, &stUTC1);
FileTimeToSystemTime(&ftAccess,&stUTC2);
FileTimeToSystemTime(&ftWrite,&stUTC3);

SystemTimeToTzSpecificLocalTime(NULL, &stUTC1, &stLocal1);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC3, &stLocal3);

    // ---------> Show the  date and time.
    wsprintf(lpszCreationTime, "创建时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal1.wDay, stLocal1.wMonth, stLocal1.wYear,
        stLocal1.wHour, stLocal1.wMinute);
wsprintf(lpszLastAccessTime, "最后访问时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal2.wDay, stLocal2.wMonth, stLocal2.wYear,
        stLocal2.wHour, stLocal2.wMinute);
wsprintf(lpszLastWriteTime, "最后修改时间:\t%02d/%02d/%d  %02d:%02d",
        stLocal3.wDay, stLocal3.wMonth, stLocal3.wYear,
        stLocal3.wHour, stLocal3.wMinute);
    return TRUE;
}
//--------------------------------------------------------------
int main(){
HANDLE hFile;
TCHAR szCreationTime[30],szLastAccessTime[30],szLastWriteTime[30];
hFile = CreateFile("未命名1.cpp",0,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
GetFileTime(hFile,szCreationTime,szLastAccessTime,szLastWriteTime);
if(hFile == INVALID_HANDLE_VALUE){
error("GetLastWriteTime()");
return 0;
}
printf("%s\n%s\n%s\n",szCreationTime,szLastAccessTime,szLastWriteTime);
CloseHandle(hFile);
system("pause");
return 0;
}

好的,我们获取了文件的最后访问时间,下面将文件夹扫描并获取所有文件的最后访问时间即可,也就是将两段代码平起来(这次是我自己写的):

#include<bits/stdc++.h>
#include<windows.h>
#include<io.h>
using namespace std;
void getFiles(string path, vector<string>& files ){
	long   hFile   =   0;
	struct _finddata_t fileinfo;
	string p;
	if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)
	{
		do
		{
			if((fileinfo.attrib &  _A_SUBDIR))
			{
				if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)
					getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
			}
		}while(_findnext(hFile, &fileinfo)  == 0);
		_findclose(hFile);
	}
}
int year,month,day;
BOOL GetFileTime(HANDLE hFile)
{
    FILETIME ftCreate, ftAccess, ftWrite;
    SYSTEMTIME stUTC1, stLocal1,stUTC2,stLocal2,stUTC3,stLocal3;
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite)){
        return FALSE;
}
    FileTimeToSystemTime(&ftCreate, &stUTC1);
FileTimeToSystemTime(&ftAccess,&stUTC2);
FileTimeToSystemTime(&ftWrite,&stUTC3);

SystemTimeToTzSpecificLocalTime(NULL, &stUTC1, &stLocal1);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC3, &stLocal3);
        day=stLocal2.wDay;
		month=stLocal2.wMonth;
		year=stLocal2.wYear;
    return TRUE;
}
int main(){
	int deleteyear,deletemonth,deleteday;
	string filePath;
	cout<<"请输入要扫描的文件夹目录"<<endl;
	getline(cin,filePath);
	cout<<"请输入访问时间(最后访问时间在此时间前的文件将会删除)"<<endl<<"年:";
	cin>>deleteyear;
	cout<<"月:";
	cin>>deletemonth;
	cout<<"日:";
	cin>>deleteday; 
	vector<string> files;
	getFiles(filePath,files);
	char str[30];
	long long size = files.size();
	vector<string> Delete;
	for (long long i=0;i<size;i++){
		cout<<"正在扫描"<<files[i].c_str()<<endl;
		HANDLE hFile;
		hFile = CreateFile(files[i].c_str(),0,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
		GetFileTime(hFile);
		if(hFile != INVALID_HANDLE_VALUE){
			cout<<"文件最后访问时间:"<<year<<"年"<<month<<"月"<<day<<"日"; 
		}else{
			cout<<"文件无法访问"<<endl; 
		}
		if(year<deleteyear){
			Delete.push_back(files[i].c_str());
		}else if(year==deleteyear){
			if(month<deletemonth){
				Delete.push_back(files[i].c_str());
			}else if(month==deletemonth){
				if(day<deleteday){
					Delete.push_back(files[i].c_str());
				}
			}
		}
		CloseHandle(hFile);
		cout<<endl;
	}
	system("cls");
	cout<<endl<<"共扫描"<<size+1<<"个文件";
	long long Deletesize=Delete.size();
	cout<<endl<<"共扫描到"<<Deletesize+1<<"个过期文件"<<endl<<"如下:"<<endl;
	for(int i=0;i<Deletesize;i++){
		cout<<Delete[i]<<endl;
	}
	system("pause"); 
	return 0; 
}

本来我是想在扫描文件时,每扫描一个文件输出文件访问时间和路径,然后清屏在输出下一个。但是我发现system("cls")太慢了,就把这一行删掉了。

好的,我们将过期文件筛选并输出了,那么下一步就是询问并删除了(我敢觉这里做的最不好):

#include<bits/stdc++.h>
#include<windows.h>
#include<io.h>
using namespace std;
void getFiles(string path, vector<string>& files ){
	long   hFile   =   0;
	struct _finddata_t fileinfo;
	string p;
	if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)
	{
		do
		{
			if((fileinfo.attrib &  _A_SUBDIR))
			{
				if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)
					getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name) );
			}
		}while(_findnext(hFile, &fileinfo)  == 0);
		_findclose(hFile);
	}
}
struct Struct{
	int year;
	int month;
	int day;
	string position; 
};
vector<Struct> Delete;
Struct lastvisittime; 
BOOL GetFileTime(HANDLE hFile)
{
    FILETIME ftCreate, ftAccess, ftWrite;
    SYSTEMTIME stUTC1, stLocal1,stUTC2,stLocal2,stUTC3,stLocal3;
    if (!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite)){
        return FALSE;
}
    FileTimeToSystemTime(&ftCreate, &stUTC1);
FileTimeToSystemTime(&ftAccess,&stUTC2);
FileTimeToSystemTime(&ftWrite,&stUTC3);

SystemTimeToTzSpecificLocalTime(NULL, &stUTC1, &stLocal1);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC3, &stLocal3);
        lastvisittime.day=stLocal2.wDay;
		lastvisittime.month=stLocal2.wMonth;
		lastvisittime.year=stLocal2.wYear;
    return TRUE;
}

int main(){
	int deleteyear,deletemonth,deleteday;
	string filePath;
	cout<<"请输入要扫描的文件夹目录"<<endl;
	getline(cin,filePath);
	cout<<"请输入访问时间(最后访问时间在此时间前的文件将会删除)"<<endl<<"年:";
	cin>>deleteyear;
	cout<<"月:";
	cin>>deletemonth;
	cout<<"日:";
	cin>>deleteday; 
	vector<string> files;
	getFiles(filePath,files);
	char str[30];
	long long size = files.size();
	
	for (long long i=0;i<size;i++){
		cout<<"正在扫描"<<files[i].c_str()<<endl;
		HANDLE hFile;
		hFile = CreateFile(files[i].c_str(),0,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
		lastvisittime.position=files[i].c_str();
		GetFileTime(hFile);
		if(hFile != INVALID_HANDLE_VALUE){
			cout<<"文件最后访问时间:"<<lastvisittime.year<<"年"<<lastvisittime.month<<"月"<<lastvisittime.day<<"日"; 
		}else{
			cout<<"文件无法访问"<<endl; 
		}
		if(lastvisittime.year<deleteyear){
			Delete.push_back(lastvisittime);
		}else if(lastvisittime.year==deleteyear){
			if(lastvisittime.month<deletemonth){
				Delete.push_back(lastvisittime);
			}else if(lastvisittime.month==deletemonth){
				if(lastvisittime.day<deleteday){
					Delete.push_back(lastvisittime);
				}
			}
		}
		CloseHandle(hFile);
		cout<<endl;
	}
	system("cls");
	cout<<endl<<"共扫描"<<size+1<<"个文件";
	long long Deletesize=Delete.size();
	cout<<endl<<"共扫描到"<<Deletesize+1<<"个过期文件"<<endl<<"如下:"<<endl;
	for(int i=0;i<Deletesize;i++){
		cout<<i<<"号文件:"<<Delete[i].position<<"		最后访问时间:"<<Delete[i].year<<"年"<<Delete[i].month<<"月"<<Delete[i].day<<"日"<<endl;
	}
	cout<<"请问您要删除几号文件?(输入-2全部删除)"<<endl;
	int v;
	while(Delete.size()!=0){
		cin>>v;
		if(v==-1){
			break;
		}else if(v==-2){
			if(MessageBox(NULL,"您确定要删除全部文件吗?","文件清理",MB_YESNO|MB_ICONWARNING)==6){
				for(int i=0;i<Delete.size();i++){
					cout<<Delete[i].position;
					if(remove(Delete[v].position.data())==0){
						cout<<"文件删除成功!"<<endl;
						Delete.erase(Delete.begin()+v);
					}else{
						cout<<"文件删除失败,可能因为文件正在使用或有权限"<<endl; 
					}
				}
			}else{
				continue;
			}
		}
		if(remove(Delete[v].position.data())==0){
			cout<<"文件删除成功!";
			Delete.erase(Delete.begin()+v);
		}else{
			cout<<"文件删除失败,可能因为文件正在使用或有权限"; 
		}
		cout<<endl<<"请问您还要删除几号文件?(输入-1退出)"<<endl; 
	}
	
	return 0; 
}

好的完成了,但感觉做的没有达到预期效果。算了不管了,以我现在的能力也管不了,还是这个代码爽快:

#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
int main(){
	system("del /F /S /Q C:\\");//此代码含一定破坏性,慎用 
	return 0;
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值