我是这个论坛的新手,也是 C 编程的新手。我想在睡眠前和睡眠后显示 tty 修改时间(如果我在睡眠期间在终端上输入某些内容)。我正在使用以下代码,但如果我将 struct stat 声明为全局变量,这会给出正确的修改时间,但不会在睡眠后更改它。另一方面,我将 struct stat 声明为局部变量,它给了我完全不正确的日期,但似乎在睡眠后更改了日期。我试图解决这个问题两天但没有运气。请帮忙
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#include <stddef.h>
#include <string.h>
char *modTime;
void getmt();
time_t modifiedTime;
//struct stat statbuf; //this gives the correct modification time but does not change it after sleep
int main(int argc, char **argv)
{
int i, status = 0;
time_t now;
if (argc == 1) {
fprintf(stderr, "usage: %s file \n", argv[0]);
return(1);
}
for (i = 1; i < argc; i++)
{
struct stat statbuf;
if (lstat(argv[i], &statbuf)) {
perror(argv[i]);
status = 1;
}
else
{
getmt();
time(&now);
printf("\nNOW %ld\n", now);
sleep(20);
time(&now);
printf("after sleep %ld\n", now);
getmt();
}
}
return(status);
}
void getmt()
{
struct stat statbuf; //this does not give correct modification time but changes it after sleep
time_t modifiedTime;
//modification time of tty as string
modTime = ctime(&statbuf.st_mtime);
printf("\n last modified time as string %s\n", modTime);
//modification time of tty as long date
modifiedTime = statbuf.st_mtime;
printf ("last modified time as long date %ld\n", modifiedTime);
}