(C language) modify file time program (creation time, modification time, access time)

background

In some cases, we need to modify the file time. Here we mainly share the program to modify the file creation time, modification time and access time, written in C language.

Solution

We mainly call the Windows API to directly modify the file time to any time set by ourselves. In the Windows system, the SetFileTime function can directly modify the time attribute of the file. The detailed API instructions can be viewed on the Windows official website:

BOOL SetFileTime(
      HANDLE               hFile,
      CONST  FILETIME      *IpCreationTime,        //File creation time
      CONST  FILETIME      *IpLastAccessTime,      //Access time
      CONST  FILETIME      *IpLastWriteTime        //Modification time
);

practice

First, we create a txt file:
New txt document

Then run the program we wrote:
Screenshot of program operation
Then let's look at the time attribute of the file
File time after running program

Program source sharing

#include <Windows.h>
#include<stdio.h>
#include <stdlib.h>
#include <tchar.h>

int main(int argc, char *argv[])
{
    //Format: filetime.exe test.txt 2011-01-08 17:00:33
    SYSTEMTIME spec_time;
    sscanf(argv[2], "%d-%d-%d", &spec_time.wYear, &spec_time.wMonth, &spec_time.wDay);
    sscanf(argv[3], "%d:%d:%d", &spec_time.wHour, &spec_time.wMinute , &spec_time.wSecond);
    spec_time.wDayOfWeek        = 1;
    spec_time.wMilliseconds     = 0;

    HANDLE hFile = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        printf("Get file handle failed,error = %s\n", GetLastError());
        return -1;
    }

    FILETIME ft, LocalFileTime;
    SystemTimeToFileTime(&spec_time, &ft);
    LocalFileTimeToFileTime(&ft, &LocalFileTime);

    if(SetFileTime(hFile, &LocalFileTime, &LocalFileTime, &LocalFileTime))
    {
        printf("success\n");
    }
    else
    {
        printf("fail\n");
    }
    CloseHandle(hFile);
    return 0;
}

In the next article, I will share a program to modify the folder time. Children can try it in advance!

Tags: Windows Attribute C

Posted on Sat, 30 Nov 2019 04:29:40 -0800 by growler123