您的位置:首页 > 其它

[文件时间]_[Windows-macOS]_[修改文件的创建时间-修改时间]

2017-07-07 14:10 519 查看

场景

1.修改文件时间一般用在下载远程文件到本地时, 修改其创建时间为远程文件的原时间, 这样对文件排序查找时也方便归类. 这类文件有很多, 视频, 音频, 图片.

说明

1.Windows 和 macOS都有这种API, Windows以简单的C Win32 api 方式; macOS则使用NSFileManager来修改.

例子

Windows


#include <Windows.h>

//2014-09-13 10:52:36
static bool DateTextConvertToTM(SYSTEMTIME* st,const wchar_t* date){

static const int kLen = 19;
if(!date || wcslen(date)<19)
return false;

memset(st,0,sizeof(SYSTEMTIME));
st->wYear = _wtoi(date);
st->wMonth = _wtoi(date+5);
st->wDay = _wtoi(date+8);
st->wHour = _wtoi(date+11);
st->wMinute = _wtoi(date+14);
st->wSecond = _wtoi(date+17);

return true;
}

static bool ModifyFileDateTime(const wchar_t* date,const wchar_t* path)
{
HANDLE file = CreateFile(path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(file){

SYSTEMTIME st,stUTC;
bool res = DateTextConvertToTM(&st,date);
if(!res) return false;

FILETIME ft;
BOOL f;
//hour: 0-23
TzSpecificLocalTimeToSystemTime(NULL,&st,&stUTC);
SystemTimeToFileTime(&stUTC, &ft);  // Converts the current system time to file time format
f = SetFileTime(file,           // Sets last-write time of the file
&ft,NULL,           // to the converted current system time
&ft);
CloseHandle(file);
return true;
}

return false;
}


macOS


#import <Foundation/Foundation.h>

//2014-09-13 10:52:36
BOOL ModifyFileDateTime(const char* date,const char* path)
{
NSString *dateComponents = @"yyyy-MM-dd HH:mm:ss";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateComponents];

NSDate *nsdate = [dateFormatter dateFromString:[NSString stringWithUTF8String:date]];
NSFileManager* fm = [NSFileManager defaultManager];

NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:nsdate,NSFileCreationDate,nsdate,NSFileModificationDate, nil];
BOOL res = [fm setAttributes:dict ofItemAtPath:[NSString stringWithUTF8String:path] error:nil];

return res;
}


参考

修改文件的创建时间-修改时间-访问时间

NSDateFormatter

NSFileManager

NSDate
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: