c - 在 Linux 中使用 stat & tm structor 获取文件时间
问题描述
我在 linux 上使用 g++ 和 eclipse。我正在制作一个获取文件时间和输出文件月份、小时等的代码......
调试时,值time1
意外更改,但我不知道这个问题。
这段代码有什么问题?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
struct stat stat1, stat2;
struct tm *time1, *time2;
void filestat1(void);
void filestat2(void);
void filetime1(void);
void filetime2(void);
void datecmp(void);
void timecmp(void);
int main(void)
{
filestat1();
filestat2();
filetime1();
filetime2();
datecmp();
timecmp();
}
void filestat1(void)
{
// check if there is no text1
int check = 0;
check = stat("text1", &stat1);
if(check != 0)
{
printf("Error : there is no text1\n");
}
return;
}
void filestat2(void)
{
// check if there is no text2
int check = 0;
check = stat("text2", &stat2);
if(check != 0)
{
printf("Error : there is no text2\n");
}
return;
}
void filetime1(void)
{
time1 = localtime(&stat1.st_mtime); //!!! this change unexpectedly
return;
}
void filetime2(void)
{
time2 = localtime(&stat2.st_mtime);
return;
}
void datecmp(void)
{
printf("date compare\n");
// compare tm_mon
if(time1->tm_mon > time2->tm_mon)
printf("time1 is early \n");
else if(time1->tm_mon < time2->tm_mon)
printf("time2 is early \n");
else{
// compare tm_mday
if(time1->tm_mday > time2->tm_mday)
printf("time1 is early \n");
else if(time1->tm_mday < time2->tm_mday)
printf("time2 is early \n");
// same date
else
printf("same time \n");
}
printf("\n");
}
void timecmp(void)
{
printf(time1->tm_hour);
printf(time2->tm_hour);
printf("time compare\n");
// compare hour
if(time1->tm_hour > time2->tm_hour)
printf("time1 is early \n");
else if(time1->tm_hour < time2->tm_hour)
printf("time2 is early \n");
else{
// compare minutes
if(time1->tm_min > time2->tm_min)
printf("time1 is early \n");
else if(time1->tm_min < time2->tm_min)
printf("time2 is early \n");
// same time
else
printf("same time \n");
}
}
解决方案
localtime
返回指向静态结构的指针。您需要在localtime
再次调用之前复制结果。
我会将time1
and声明time2
为结构而不是存储值的指针。
struct tm time1, time2;
void filetime1(void)
{
struct tm *tmp = localtime(&stat1.st_mtime);
if (tmp == NULL) {
//... handle error
}
time1 = *tmp;
}
同样对于filetime2
。
如果您正在编写多线程代码,使用函数的可重入变体localtime_r
. 在这种情况下,您将指针传递给结果结构。
void filetime1(void)
{
struct tm *tmp = localtime_r(&stat1.st_mtime, &time1);
if (tmp == NULL) {
//... handle error
} else {
assert(tmp == &time1);
}
}
推荐阅读
- javascript - mapStateToProps 应该异步更新道具吗?
- android - 如何在 Docker 容器中运行 emulator64-arm?
- powershell - 删除特定 OU 中的过期帐户
- python - 具有单个堆栈的二叉树的迭代后序遍历,如何解决这个问题?
- unit-testing - 使用 Mocha Chai 和 Enzyme 对 onClick 方法进行单元测试时遇到问题
- ios - 以编程方式使用“首选大标题”折叠和展开 UINavigationBar
- docker - 使用 kubernetes 扩展 cron 架构
- android - 任何想法如何为音频录制按钮创建优雅的涟漪效果 - 就像在 Google Keep 中一样
- python - 如何在 PyQt 的单元格中居中图像?
- javascript - Javascript 测验 - 获取选定的单选按钮值并比较正确答案