Search code examples
c++filefile-type

How to read filename of the last modified file in a directory?


I have a directory with some files of different type extension. Among them, there are .grb2 files (meteo data). For instance:

...

20140729_0000_000.grb2

20140729_1200_000.grb2

20140730_1200_000.grb2

...

The thing is that I would like to read with C++ the last modified file of only this type (.grb2). Since they are named by the date, it would be also valid to read the file with the biggest number in its filename, since that is the most updated meteo data. I am currently reading it manually (entering its filename directly in C++), which is obviously not optimal since I download a lot of these files.

Have you any idea? By the way, I'm working in Windows (if it is of any help).


Solution

  • You could consider using Boost Filesystem. Boost Filesystem implements the upcoming standard library specification for this.

    You can use it to write more robust code and be platform independent at the same time:

    Live On Coliru

    for (auto&& entry : boost::make_iterator_range(fs::directory_iterator("."), {})) {
        fs::path p = entry.path();
        if (is_regular_file(p) && p.extension() == ".grb2") 
        {
            std::time_t timestamp = fs::last_write_time(p);
            if (timestamp > latest_tm) {
                latest = p;
                latest_tm = timestamp;
            }
        }
    }
    

    Although this code wasn't written in Notepad ¹, it is tested:

    /tmp$ mkdir q
    /tmp$ cd q
    /tmp/q$ touch {a..z}.grb2
    /tmp/q$ ../test

    Reports:

    Last modified: "./z.grb2"
    

    /tmp/q$ touch k.grb2
    /tmp/q$ ../test

    Reports:

    Last modified: "./k.grb2"
    

    ¹ Full disclosure: It was written in Vim on Ubuntu Linux