栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【Linux】Linux环境下用C++删除指定文件

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Linux】Linux环境下用C++删除指定文件

【Linux】Linux环境下用C++删除指定文件
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const long day = 86400;

//获取文件的给更新时间
long get_file_modify_time(string filepath)
{
    struct stat filehand;
    FILE *fp;
    fp = fopen(filepath.c_str(), "r");
    int fileid = fileno(fp);
    fstat(fileid, &filehand);
    fclose(fp);
    return filehand.st_mtime;
}
//获取文件夹中的所有文件
void get_files(const string dirname, vector &filelist)
{
    if(dirname.empty())
        return;
    struct stat s;
    stat(dirname.c_str(), &s);
    if(!S_ISDIR(s.st_mode))
        return;
    DIR *dirhand = opendir(dirname.c_str());
    if(NULL == dirhand){
        exit(EXIT_FAILURE);
    }
    dirent *fp = nullptr;
    while((fp = readdir(dirhand)) != nullptr){
        if(fp->d_name[0] != '.'){//十分重要的一行(?)
            string filename = dirname + "/" + string(fp->d_name);
            struct stat filemod;
            stat(filename.c_str(), &filemod);
            if(S_ISDIR(filemod.st_mode)){
                get_files(filename, filelist);
            }
            else if(S_ISREG(filemod.st_mode)){
                filelist.push_back(filename);
            }
        }
    }
    closedir(dirhand);
    return;
}

bool delete_file(string filepath)
{
    return remove(filepath.c_str());
}

bool date_from_now(long now, long modify)
{
    int dis = int((1.0 * (now - modify) / day + 0.5));
    return dis >= 9;//删除最近更新时间距今超过14天的文件
}

int main()
{
    time_t now;
    time(&now);//获取当前系统时间
    string dir = "/file/cpp";//需要处理的文件夹
    vector filelist;
    get_files(dir, filelist);//获取文件夹中的所有文件
    for(auto i : filelist){
        if(date_from_now(now, get_file_modify_time(i))){
            cout << i << endl;
            if(!delete_file(i)){
                cout << "The file named : " << i << " has been deleted." << endl;
            }
            else{
                cout << "Delete Failed!" << endl;
            }
        }
    }
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629605.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号