I would:
- Create a type to hold a file name and timestamp.
- Use
FindFirstFile
to get the timestamp you care about for each file.
- Create a name/timestamp object and store it into a vector.
- Call
FindClose
for that file.
- Repeat from 2 for each input file name.
- Sort the vector on the timestamp.
- Display the results.
So, one possible implementation might look something like this:
#include <iostream>
#include <Windows.h>
#include <algorithm>
#include <string>
#include <vector>
#include <iomanip>
class file {
std::string name;
FILETIME time;
public:
bool operator<(file const &other) const {
return CompareFileTime(&time, &other.time) == 1;
}
friend std::ostream &operator<<(std::ostream &os, file const &f) {
SYSTEMTIME st;
FileTimeToSystemTime(&f.time, &st);
return os << std::setw(20) << f.name << "\t" << st.wHour << ":" << st.wMinute << ":" << st.wSecond << " " << st.wYear << "/" << st.wMonth << "/" << st.wDay;
}
file(WIN32_FIND_DATA const &d) : name(d.cFileName), time(d.ftCreationTime) {}
};
int main(){
std::vector<std::string> inputs{ "a.txt", "b.txt" };
std::vector<file> files;
std::transform(inputs.begin(), inputs.end(),
std::back_inserter(files),
[](std::string const &fname) {
WIN32_FIND_DATA d;
HANDLE h = FindFirstFile(fname.c_str(), &d);
FindClose(h);
return d;
}
);
std::sort(files.begin(), files.end());
std::copy(files.begin(),files.end(),
std::ostream_iterator<file>(std::cout, "\n"));
}
To deal with "wide" (Unicode) strings for the file names, you'd modify that (slightly) to look something like this:
#include <iostream>
#include <Windows.h>
#include <algorithm>
#include <string>
#include <vector>
#include <iomanip>
class file {
std::wstring name;
FILETIME time;
public:
bool operator<(file const &other) const {
return CompareFileTime(&time, &other.time) == 1;
}
friend std::wostream &operator<<(std::wostream &os, file const &f) {
SYSTEMTIME st;
FileTimeToSystemTime(&f.time, &st);
return os << std::setw(20) << f.name << L"\t" << st.wHour << L":" << st.wMinute << L":" << st.wSecond << L" " << st.wYear << L"/" << st.wMonth << L"/" << st.wDay;
}
file(WIN32_FIND_DATA const &d) : name(d.cFileName), time(d.ftCreationTime) {}
};
int main(){
std::vector<std::wstring> inputs{ L"a.txt", L"b.txt" };
std::vector<file> files;
std::transform(inputs.begin(), inputs.end(),
std::back_inserter(files),
[](std::wstring const &fname) {
WIN32_FIND_DATA d;
HANDLE h = FindFirstFile(fname.c_str(), &d);
FindClose(h);
return d;
}
);
std::sort(files.begin(), files.end());
for (auto const &f : files)
std::wcout << f << L"\n";
}
Then when you build it you need to tell the compiler you want the Unicode versions of the Windows functions by defining UNICODE
when you compile:
cl -DUNICODE files.cpp