我使用stat来获取文件的最后修改时间,但我想在整个时间内添加几秒钟。
if (stat(file_path, &st) == 0)
{
char estimate_time[50];
strftime(estimate_time, 50, "\'%F %T\'", localtime(&st.st_mtime)
}
因此,此代码可以很好地获取文件的上次修改时间,但我只想在整个时间内添加几秒钟。有没有办法在几秒钟内获得“st_mtime”所以我可以简单地添加到该值,然后使用strftime转换为格式化的输出?
由于
答案 0 :(得分:1)
要便携式添加几秒钟到struct tm
,只需添加到tm_sec
成员并致电mktime()
以规范化结构。
struct stat st;
struct tm *tm = localtime(&st.st_mtime);
if (tm == NULL) Handle_Error();
tm->tm_sec += offset;
time_t time_new = mktime(tm); // adjust fields.
if (time_new == (time_t) -1) Handle_Error();
strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);
根据[stat]
标记,OP位于需要time_t
的POSIX系统上,以秒为单位,因此POSIX代码可能会添加到st.st_mtime
。
time_t new_time = st.st_mtime + offset;
struct tm *tm = localtime(&new_time);
if (tm == NULL) Handle_Error();
strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);