C++ 将字符串转换为 time_t

C++ convert string to time_t

我正在使用 stat.st_mtime 获取目录的最后修改时间,然后将其存储到 file.txt(存储的字符串类似于:1467035651

稍后,当我从 file.txt 中检索数据时,我尝试将字符串从 file.txt 类型转换为 int 类型,因为string 只包含几秒钟,但我不知道这样做是否是个好主意。

有没有办法直接转换成time_t

根据reference documentation time_t只是一种未指定的数字格式。

直接从文件中读回数值即可,无需特殊转换:

time_t t;
std::ifstream input("File.txt");
// ...
input >> t;

stdlib.h 中的函数 atoll 应该可以工作。示例:

time_t t;
char *time_string = //...

t = (time_t) atoll(time_string);

[假设 C]

strto*() 函数族提供了将 C-"string" 转换为整数 signed or unsigned, as well as to float and double.

的故障安全方法

Is there any way to convert directly to time_t?

其他各种答案 post 给出了具有优点和缺点的直接解决方案。

contains just seconds but I don't know if it's a good idea to do that.

答案取决于目标。 IMO,这是错误的方法

而不是 save/reading 作为一些依赖于编译器的格式,考虑使用 ISO 8601 标准并将时间戳保存在明确表示时区的文本标准版本中,最好是通用时间。

作为 post 的示例 C 代码被标记为 C
对于写作,类似于

// Minimum size to store a ISO 8601 date/time stamp
//YYYY-MM-DDThh:mm:ss[=10=]
#define N (4 + 5*3 + 1 + 1)

time_t x;
struct tm *tm = gmtime(&x);
if (tm == NULL) {
  return failure;
}

char dest[N + 1];
int cnt = snprintf(dest, sizeof(dest), "%04d-%02d-%02dT%02d:%02d:%02dZ", 
    tm.tm_year + 1900, tm.tm_mon+1, tm.tm_mday,
    tm.tm_hour, tm.tm_min, tm.tm_sec);
if (cnt < 0 || cnt >= sizeof(dest)) {
  return failure;
}

小数秒需要额外的代码。
另见 ftime( , , "%FT%T %z", ).

您更愿意在 file.txt 中阅读什么内容?

1467035651 

2016-06-27T13:54:11Z