开发者

C++: how can I get the list of folders

I am not familiar with C++ as I am a C# developer.

In my project, I need to delete all folders of one week开发者_运维技巧 before. In C++, how can I get the list of the folders of one week before based on the current system date time?

I am working on Eclipse IDE running on Ubuntu 10.10.

If you could provide some sample of code, that would be great.

Thanks in advance and your help is much appreciated!


With boost:

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

or without using 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);
    }
}


It's more a question of your OS API than C++. C++ itself provides no facilities for filesystem operations. However, there are several portable libraries that do, boost::filesystem for example.

However, if you're stuck only to one operating system, it's easier to use it's facilities -- POSIX on *nixes, or WinAPI on Windows.

Both are C based, to get a C++ solution, you need a third party library.

On Linux, the following might get you started:

  • File Access and Directory System Calls


I would have thought you should look at the functions opendir and readdir - also look at stat. Basically, open the top level directory, and examine all entries in it that are directories. The stat function will be able to give you access and modify times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜