C++ 递归遍历修改所有文件/文件夹的创建时间、修改时间、访问时间

代码如下:

#include <locale.h>  
#include <locale>  
#include <stdio.h>
#include <windows.h>
#include <fstream>
#include <iostream>
#include <vector>
#include <io.h>
#include <string>

using namespace std;

void getAllFiles(std::string path, std::vector<std::string>& filePaths, std::vector<std::string>& directoryPaths);
bool changeFileTime(const char* filename, bool isFile, int wYear, int wMonth, int wDay, int wHour, int wMinute, int wSecond);

//SetFileTime function document in MSDN
//https://docs.microsoft.com/zh-cn/windows/win32/api/fileapi/nf-fileapi-setfiletime
//https://docs.microsoft.com/zh-cn/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror
int main(int argc, char** argv) {

    std::string path("E:/test/info");

    //Greenwich Mean Time
    int wYear = 2016;
    int wMonth = 8;
    int wDay = 9;
    int wHour = 2;
    int wMinute = 45;
    int wSecond = 12;

    std::cout << "Start ..." << endl;
    std::vector<std::string> filePaths;
    std::vector<std::string> directoryPaths;
    getAllFiles(path, filePaths, directoryPaths);
    for (std::vector<std::string>::const_iterator iter = filePaths.cbegin(); iter != filePaths.cend(); iter++) {
        std::string path(*iter);
        const char* path_c = path.c_str();
        bool flag = changeFileTime(path_c, true, wYear, wMonth, wDay, wHour, wMinute, wSecond);
        cout << "File Changed -> " + std::to_string(flag) + "," +path << endl;
    }
    for (std::vector<std::string>::const_iterator iter = directoryPaths.cbegin(); iter != directoryPaths.cend(); iter++) {
        std::string path(*iter);
        const char* path_c = path.c_str();
        bool flag = changeFileTime(path_c, false, wYear, wMonth, wDay, wHour, wMinute, wSecond);
        cout << "Directory Changed -> "+std::to_string(flag)+","+path << endl;
    }

    std::cout << "Finish !" << endl;
    return 0;
}
void getAllFiles(std::string path, std::vector<std::string>& filePaths, std::vector<std::string>& directoryPaths){
    //file handle
    long fHandle = 0;
    //file info struct
    struct _finddata_t fInfo;
    std::string s;
    if ((fHandle = _findfirst(s.assign(path).append("\\*").c_str(), &fInfo)) != -1){
        do{
            const char* fName = fInfo.name;
            if ((fInfo.attrib & _A_SUBDIR)) {  //is directory
                if (strcmp(fName, ".") != 0 && strcmp(fName, "..") != 0) {
                    directoryPaths.push_back(s.assign(path).append("/").append(fName));
                    getAllFiles(s.assign(path).append("/").append(fName), filePaths, directoryPaths);
                }
            }else{ //is file
                filePaths.push_back(s.assign(path).append("/").append(fName));
            }
        } while (_findnext(fHandle, &fInfo) == 0);  //find next, if success return 0 or fail return -1
        _findclose(fHandle);
    }
}

bool changeFileTime(const char* filename,
                    bool isFile, //file:true,directory:false
                    int wYear,
                    int wMonth,
                    int wDay,
                    int wHour,
                    int wMinute,
                    int wSecond) {
    SYSTEMTIME createTime;
    GetSystemTime(&createTime);
    createTime.wYear   = wYear;      //changes the year
    createTime.wMonth  = wMonth;     //changes the month
    createTime.wDay    = wDay;       //changes the day
    createTime.wHour   = wHour;      //changes the hour
    createTime.wMinute = wMinute;    //changes the minute
    createTime.wSecond = wSecond;    //changes the second

    SYSTEMTIME lastWriteTime;
    GetSystemTime(&lastWriteTime);
    lastWriteTime.wYear   = wYear;   //changes the year
    lastWriteTime.wMonth  = wMonth;  //changes the month
    lastWriteTime.wDay    = wDay;    //changes the day
    lastWriteTime.wHour   = wHour;   //changes the hour
    lastWriteTime.wMinute = wMinute; //changes the minute
    lastWriteTime.wSecond = wSecond; //changes the second

    SYSTEMTIME lastAccessTime;
    GetSystemTime(&lastAccessTime);
    lastAccessTime.wYear   = wYear;   //changes the year
    lastAccessTime.wMonth  = wMonth;  //changes the month
    lastAccessTime.wDay    = wDay;    //changes the day
    lastAccessTime.wHour   = wHour;   //changes the hour
    lastAccessTime.wMinute = wMinute; //changes the minute
    lastAccessTime.wSecond = wSecond; //changes the second

    //convert time to filetime
    FILETIME lastWriteFiletime;
    SystemTimeToFileTime(&lastWriteTime, &lastWriteFiletime);

    FILETIME createFiletime;
    SystemTimeToFileTime(&createTime, &createFiletime);

    FILETIME lastAccessFileTime;
    SystemTimeToFileTime(&lastAccessTime, &lastAccessFileTime);

    if (isFile) {
        //get the file handle
        HANDLE hFile = CreateFile(filename, 
            GENERIC_READ | GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            NULL, OPEN_EXISTING, 
            FILE_ATTRIBUTE_NORMAL, NULL);

        //set time to the file
        bool flag = SetFileTime(hFile, &createFiletime, &lastAccessFileTime, &lastWriteFiletime);

        //close handle.
        CloseHandle(hFile);

        if (!flag) {
            std::printf("fail, error code: %d -> ", GetLastError());
        }
        return flag;
    } else {
        //get the directory handle
        HANDLE hDir = CreateFile(filename,
            GENERIC_READ | GENERIC_WRITE,
            0 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            NULL, OPEN_EXISTING,
            FILE_FLAG_BACKUP_SEMANTICS, NULL);

        //set time to the directory
        bool flag = SetFileTime(hDir, &createFiletime, &lastAccessFileTime, &lastWriteFiletime);

        //close handle.
        CloseHandle(hDir);

        if (!flag) {
            std::printf("fail, error code: %d -> ", GetLastError());
        }
        return flag;
    }
}


运行结果:

(提示:使用的是UTC时间即格林威治时间时间,中国是东八区,所以UTC时间会比中国时间多8个小时)

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/u012714280/article/details/112691314

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页