lINUX,编写程序获取文件的最后修改时间
时间: 2023-06-11 16:06:19 浏览: 339
在Linux中,可以使用C语言中的stat()函数来获取文件的最后修改时间。具体步骤如下:
1. 引入头文件
```c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
```
2. 定义变量
```c
struct stat file_stat;
time_t last_modified;
```
3. 使用stat()函数获取文件状态
```c
if (stat("/path/to/your/file", &file_stat) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
```
4. 从文件状态中获取最后修改时间
```c
last_modified = file_stat.st_mtime;
```
5. 将时间转换为字符串格式
```c
char time_str[30];
strftime(time_str, 30, "%Y-%m-%d %H:%M:%S", localtime(&last_modified));
```
完整的代码如下:
```c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct stat file_stat;
time_t last_modified;
char time_str[30];
if (stat("/path/to/your/file", &file_stat) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
last_modified = file_stat.st_mtime;
strftime(time_str, 30, "%Y-%m-%d %H:%M:%S", localtime(&last_modified));
printf("Last modified time: %s\n", time_str);
return 0;
}
```