C/Reference

[C] 파일 속성의 만든 날짜, 수정한 날짜, 액세스한 날짜 얻고 수정하기

MoongStory 2024. 12. 15. 00:53
반응형
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>

#define STRING_LEN 100

int _tmain(int argc, LPTSTR argv[])
{
	TCHAR fileName[] = _T("data.txt");

	TCHAR fileCreateTimeInfo[STRING_LEN] = {0};
	TCHAR fileAccessTimeInfo[STRING_LEN] = {0};
	TCHAR fileWriteTimeInfo[STRING_LEN] = {0};


	FILETIME ftCreate = {0}, ftAccess = {0}, ftWrite = {0};
	SYSTEMTIME stCreateUTC = {0}, stCreateLocal = {0};
	SYSTEMTIME stAccessUTC = {0}, stAccessLocal = {0};
	SYSTEMTIME stWriteUTC = {0}, stWriteLocal = {0};

	HANDLE hFile = CreateFile(fileName, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	if(hFile == INVALID_HANDLE_VALUE)
	{
		_tprintf(_T("File open fault!\n"));
		return -1;
	}

	if(!GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite))
	{
		_tprintf(_T("GetFileTime function call fault!\n"));
		return FALSE;
	}

	FileTimeToSystemTime(&ftCreate, &stCreateUTC);
	SystemTimeToTzSpecificLocalTime(NULL, &stCreateUTC, &stCreateLocal);

	FileTimeToSystemTime(&ftAccess, &stAccessUTC);
	SystemTimeToTzSpecificLocalTime(NULL, &stAccessUTC, &stAccessLocal);

	FileTimeToSystemTime(&ftWrite, &stWriteUTC);
	SystemTimeToTzSpecificLocalTime(NULL, &stWriteUTC, &stWriteLocal);

	_stprintf_s(fileCreateTimeInfo, _countof(fileCreateTimeInfo), _T("%02d/%02d/%d\t%02d:%02d"), stCreateLocal.wMonth, stCreateLocal.wDay, stCreateLocal.wYear, stCreateLocal.wHour, stCreateLocal.wMinute);
	_stprintf_s(fileAccessTimeInfo, _countof(fileAccessTimeInfo), _T("%02d/%02d/%d\t%02d:%02d"), stAccessLocal.wMonth, stAccessLocal.wDay, stAccessLocal.wYear, stAccessLocal.wHour, stAccessLocal.wMinute);
	_stprintf_s(fileWriteTimeInfo, _countof(fileWriteTimeInfo), _T("%02d/%02d/%d\t%02d:%02d"), stWriteLocal.wMonth, stWriteLocal.wDay, stWriteLocal.wYear, stWriteLocal.wHour, stWriteLocal.wMinute);

	_tprintf(_T("File created time : %s\n"), fileCreateTimeInfo);
	_tprintf(_T("File accessed time : %s\n"), fileAccessTimeInfo);
	_tprintf(_T("File written time : %s\n"), fileWriteTimeInfo);

	CloseHandle(hFile);

	hFile = CreateFile(fileName, GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

	if(hFile == INVALID_HANDLE_VALUE)
	{
		_tprintf(_T("File open fault!\n"));
		return -1;
	}

	stCreateLocal.wYear += 3;
	TzSpecificLocalTimeToSystemTime(NULL, &stCreateLocal, &stCreateUTC);
	SystemTimeToFileTime(&stCreateUTC, &ftCreate);

	_stprintf_s(fileCreateTimeInfo, _countof(fileCreateTimeInfo), _T("%02d/%02d/%d\t%02d:%02d"), stCreateLocal.wMonth, stCreateLocal.wDay, stCreateLocal.wYear, stCreateLocal.wHour, stCreateLocal.wMinute);
	_tprintf(_T("\nFile created time : %s\n"), fileCreateTimeInfo);

	if(!SetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite))
	{
		_tprintf(_T("GetFileTime function call fault!\n"));
		return FALSE;
	}

	CloseHandle(hFile);

	return 0;
}
반응형