6

I need to know, how I can select the Last modified/created file in a given directory.

I currently have a directory named XML, and inside that there are many XML files. But I would like to select only the last modified file.

pmr
  • 58,701
  • 10
  • 113
  • 156
Fahad.ag
  • 181
  • 1
  • 8
  • 19

3 Answers3

4

I use the following function to list all the items inside a folder. It writes all the files in a string vector, but you can change that.

bool ListContents (vector<string>& dest, string dir, string filter, bool recursively)
{
    WIN32_FIND_DATAA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    DWORD dwError = 0; 

    // Prepare string
    if (dir.back() != '\\') dir += "\\";

    // Safety check
    if (dir.length() >= MAX_PATH) {
        Error("Cannot open folder %s: path too long", dir.c_str());
        return false;
    }

    // First entry in directory
    hFind = FindFirstFileA((dir + filter).c_str(), &ffd);

    if (hFind == INVALID_HANDLE_VALUE) {
        Error("Cannot open folder in folder %s: error accessing first entry.", dir.c_str());
        return false;
    }

    // List files in directory
    do {
        // Ignore . and .. folders, they cause stack overflow
        if (strcmp(ffd.cFileName, ".") == 0) continue;
        if (strcmp(ffd.cFileName, "..") == 0) continue;

        // Is directory?
        if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            // Go inside recursively
            if (recursively) 
                ListContents(dest, dir + ffd.cFileName, filter, recursively, content_type);
        }

        // Add file to our list
        else dest.push_back(dir + ffd.cFileName);

    } while (FindNextFileA(hFind, &ffd));

    // Get last error
    dwError = GetLastError();
    if (dwError != ERROR_NO_MORE_FILES) {
        Error("Error reading file list in folder %s.", dir.c_str());
        return false;
    }

    return true;
}

(don't forget to include windows.h)

What you have to do is adapt it to find the newest file. The ffd structure (WIN32_FIND_DATAA data type) contains ftCreationTime, ftLastAccessTime and ftLastWriteTime, you can use those to find the newest file. These members are FILETIME structures, you can find the documentation here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724284%28v=vs.85%29.aspx

Tibi
  • 4,015
  • 8
  • 40
  • 64
1

You can use FindFirstFile and FindNextFile, they deliver a struct describing the file like size as well as modified time.

AndersK
  • 35,813
  • 6
  • 60
  • 86
0

Boost.Filesystem offers last_write_time. You can use this to sort the files in a directory. Boost.Filesystem and (Boost) in general can be a little bit intimidating for a C++ new-comer so you might want to check a solution for your OS first.

pmr
  • 58,701
  • 10
  • 113
  • 156