c - 将文件的时间戳设置为自定义时间
问题描述
我想将文件的时间戳更改为自定义日期,我发现以下代码必须将文件的时间戳更改为当前时间,但是它不起作用。如何实现一个函数,它可以将文件的时间戳更改为自定义时间(由用户指定)。
bool SetFileToCurrentTime(const char* arg_path, const char* arg_file_name)
{
HANDLE h_File;
FILETIME ft_FileTime;
SYSTEMTIME st_SystemTime;
char l_c_Path[MAX_PATH];
strcpy(l_c_Path, arg_path);
strcat(l_c_Path, arg_file_name);
h_File = CreateFile(l_c_Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
GetSystemTime(&st_SystemTime); // Gets the current system time
SystemTimeToFileTime(&st_SystemTime, &ft_FileTime); // Converts the current system time to file time format
if (SetFileTime(h_File, (LPFILETIME)NULL, (LPFILETIME)NULL, &ft_FileTime))
return true;
else
return false;
}
解决方案
我发现以下代码必须将文件的时间戳更改为当前时间,但它不起作用
我不知道出了什么问题,我没有要检查的 Windows 编译器,但这里有一些可能性。
SystemTimeToFileTime
检查和的返回值CreateFile
。- 用于
GetLastError
找出他们失败的原因。 l_c_Path
没有在路径和文件名之间放置路径分隔符。如果调用者不提供一个路径将是不正确的。打印出来l_c_Path
。
strcpy
与其使用and ,不如strlcat
考虑使用_makepath_s
来连接路径。
char l_c_Path[_MAX_PATH];
errno_t errorCode = _makepath_s(l_c_Path, _MAX_PATH, NULL, arg_path, arg_file_name, NULL);
if( errorCode ) {
// check the errorCode
}
如何实现一个函数,它可以将文件的时间戳更改为自定义时间(由用户指定)。
不要用 调用GetSystemTime
和转换它,而是让调用SystemTimeToFileTime
者传入FILETIME
.
推荐阅读
- text-to-speech - Get Pepper 机器人告诉时间和日期
- sql - 执行sql的优先级
- lua - 如何将 lua 堆栈放在外部 PSRAM 上
- generics - 在函数参数中接受不同类型的 ArrayList
- c++ - 如何获得“基于堆栈”的 std::stack?(具有固定的最大尺寸)
- java - 使用Jackson时的Spring Batch序列化问题
- python - 没有迭代的两个数据帧的硬匹配
- hive - Superset - Hive 连接问题
- sql - SQL Server - 如果只有一个不同的值 + 没有 ansi 警告的空值,则聚合
- sql-server - 将表两次部署到不同的模式