C++设置文件修改时间

53 篇文章 0 订阅

VS2010新建控制台空项目,加入C++代码:

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

bool ConvertFileTimeToLocalTime(const FILETIME *lpFileTime, SYSTEMTIME *lpSystemTime)
{
	if (!lpFileTime || !lpSystemTime) {
		return false;
	}
	FILETIME ftLocal;
	FileTimeToLocalFileTime(lpFileTime, &ftLocal);
	FileTimeToSystemTime(&ftLocal, lpSystemTime);
	return true;
}

bool ConvertLocalTimeToFileTime(const SYSTEMTIME *lpSystemTime, FILETIME *lpFileTime)
{
	if (!lpSystemTime || !lpFileTime) {
		return false;
	}

	FILETIME ftLocal;
	SystemTimeToFileTime(lpSystemTime, &ftLocal);
	LocalFileTimeToFileTime(&ftLocal, lpFileTime);
	return true;
}

int main()
{
	HANDLE hFile;
	FILETIME ftCreate, ftAccess, ftWrite;
	SYSTEMTIME stCreate, stAccess, stWrite;
	int year, month, day;

	hFile = CreateFile(L"C:\\1.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
	if (INVALID_HANDLE_VALUE == hFile) {
		printf("CreateFile error: %d", GetLastError());
		ExitProcess(0);
	}
	GetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite);
	ConvertFileTimeToLocalTime(&ftCreate, &stCreate);
	ConvertFileTimeToLocalTime(&ftAccess, &stAccess);
	ConvertFileTimeToLocalTime(&ftWrite, &stWrite);

	printf("yyyy-MM-dd:");
	scanf("%d-%d-%d", &year, &month, &day);
	stAccess.wYear = stWrite.wYear = year;
	stAccess.wMonth = stWrite.wMonth = month;
	stAccess.wDay = stWrite.wDay = day;

	ConvertLocalTimeToFileTime(&stAccess, &ftAccess);
	ConvertLocalTimeToFileTime(&stWrite, &ftWrite);

	SetFileTime(hFile, &ftCreate, &ftAccess, &ftWrite);
	CloseHandle(hFile);
	return 0;
}

只修改年月日,时分秒不变。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值