首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >堆芯问题

堆芯问题
EN

Stack Overflow用户
提问于 2022-09-16 08:19:17
回答 2查看 44关注 0票数 1

我想创建一个C程序,它检索文件(或目录文件)的inode信息,并将其作为参数并显示文件创建日期,但我有一个分段问题。我不知道怎么修好它。PS:我应该用Ctime。

代码语言:javascript
复制
#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;
}

在这里输入图像描述

EN

回答 2

Stack Overflow用户

发布于 2022-09-17 20:40:28

我对代码做了一些修改。我会在下面详细说明。

代码语言:javascript
复制
% 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()
  • 检查至少有一个参数( argc和argv1检查)很重要。
  • 内存分配可能会失败,所以我验证我们已经分配了内存。
  • stat()也可能失败,让我们验证一下这是成功的。
  • 我将%ld改为%llu以更好地匹配st_ino
票数 0
EN

Stack Overflow用户

发布于 2022-09-17 20:58:17

首先,没有必要在堆上分配struct stat。只需使用本地堆栈变量

代码语言:javascript
复制
struct stat buf;
int err = stat(argc[1], &buf);

接下来,错误来自char *ctime()缺少的声明。当C编译器没有ctime()声明时,它假设返回类型为int。由于这与%s的格式字符串不匹配,所以任何事情都可能发生。

当添加编译器警告时,您可以看到这一点。

代码语言:javascript
复制
$ 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()来解决这个问题

代码语言:javascript
复制
#include <time.h>

现在,该程序运行时没有抛出核心。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73741898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档