我想创建一个C程序,它检索文件(或目录文件)的inode信息,并将其作为参数并显示文件创建日期,但我有一个分段问题。我不知道怎么修好它。PS:我应该用Ctime。
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
struct stat *buffer = NULL;
buffer = malloc(sizeof(struct stat));
stat (argv[1],buffer);
printf("Date de création du fichier: %s", ctime(&buffer->st_ctime));
printf("Numéro inode: %ld\n", buffer->st_ino);
return 0;
}发布于 2022-09-17 20:40:28
我对代码做了一些修改。我会在下面详细说明。
% cc -o core core.c ; ./core test.txt
Date de création du fichier: Sun Sep 11 12:03:26 2022
Numéro inode: 41714431
% cat core.c
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main(int argc, char * argv[]) {
struct stat *buffer = NULL;
if (argc < 2 || argv[1] == NULL) {
printf("Need a file name\n");
exit(1);
}
buffer = malloc(sizeof(struct stat));
if (buffer == NULL) {
perror("malloc:");
exit(1);
}
int ret = stat (argv[1], buffer);
if (ret) {
perror("stat:");
exit(1);
}
printf("Date de création du fichier: %s", ctime(&buffer->st_ctime));
printf("Numéro inode: %llu\n", buffer->st_ino);
return 0;
}ctime()。stat()也可能失败,让我们验证一下这是成功的。%ld改为%llu以更好地匹配st_ino。发布于 2022-09-17 20:58:17
首先,没有必要在堆上分配struct stat。只需使用本地堆栈变量
struct stat buf;
int err = stat(argc[1], &buf);接下来,错误来自char *ctime()缺少的声明。当C编译器没有ctime()声明时,它假设返回类型为int。由于这与%s的格式字符串不匹配,所以任何事情都可能发生。
当添加编译器警告时,您可以看到这一点。
$ gcc -Wall -Wextra a.c
/tmp/a.c: In function ‘main’:
/tmp/a.c:13:45: warning: implicit declaration of function ‘ctime’ [-Wimplicit-function-declaration]
13 | printf("Date de création du fichier: %s", ctime(&buffer->st_ctime));
| ^~~~~
/tmp/a.c:13:41: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
13 | printf("Date de création du fichier: %s", ctime(&buffer->st_ctime));
| ~^ ~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | int
| char *
| %d您可以通过声明ctime()来解决这个问题
#include <time.h>现在,该程序运行时没有抛出核心。
https://stackoverflow.com/questions/73741898
复制相似问题