C++:如何获取文件夹列表

oli*_*dev 1 c++ linux

我不熟悉C++,因为我是C#开发人员.

在我的项目中,我需要删除一周之前的所有文件夹.在C++中,如何根据当前系统日期时间获取一周之前的文件夹列表?

我正在研究在Ubuntu 10.10上运行的Eclipse IDE.

如果您可以提供一些代码示例,那就太棒了.

在此先感谢您的帮助,非常感谢!

Kor*_*icz 5

这是一个关于OS API的问题,而不是C++.C++本身不提供文件系统操作的功能.但是,有几个可移植库,例如boost :: filesystem.

但是,如果您只关注一个操作系统,则可以更轻松地使用它的工具 - POSIX on*nixes或Windows上的WinAPI.

两者都是基于C的,要获得C++解决方案,您需要第三方库.

在Linux上,以下内容可能会帮助您入门:


chr*_*ris 5

有了提升:

#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>

int main(int, char**)
{
    time_t one_week_ago = std::time(NULL) - (7 * 24 * 3600);

    boost::filesystem::directory_iterator dir("/tmp"), end;

    BOOST_FOREACH(const boost::filesystem::path& p, std::make_pair(dir, end))
        if(boost::filesystem::is_directory(p))
            if(boost::filesystem::last_write_time(p) < one_week_ago)
                boost::filesystem::remove_all(p);
}
Run Code Online (Sandbox Code Playgroud)

或者不使用boost :: foreach

#include <boost/filesystem.hpp>

int main(int, char**)
{
    time_t one_week_ago = std::time(NULL) - (7 * 24 * 3600);

    boost::filesystem::directory_iterator dir("/tmp"), it, end;

    for(it = dir; it != end; it++)
    {
        const boost::filesystem::path& p = *it;
        if(boost::filesystem::is_directory(p))
            if(boost::filesystem::last_write_time(p) < one_week_ago)
                boost::filesystem::remove_all(p);
    }
}
Run Code Online (Sandbox Code Playgroud)