简体   繁体   English

如何创建结构以使用C语言从目录存储日期时间和文件名?

[英]How create a struct to store datetime and filename from a dir in C language?

I'm trying to create a struct to store filename and datatime of files from a dir 我正在尝试创建一个结构来存储目录中文件的文件名和数据时间

  if(dir)
{
  struct dirent *file;
  struct stat info_;
  char buf[256];
  int N=0;

  struct element
  {
      char *name;
      time_t date;
  };
  struct element database[N];

  while ( (file=readdir(dir)) != NULL )
  {
    if(file->d_name[0] != '.')
    {
     strcpy(database->name, file->d_name);
     database->date=info_.st_mtime;
     N++;
     }
    }


    int i;
    for(i=0; i<N; i++)
    {
      printf("%s",database->name);
      printf("%d",database->date);  
    }

I'd like also to sort the struct but It's an other problem that come after this. 我也想对结构进行排序,但这是另一个问题。 The program give me segmentation fault. 该程序给我分割错误。 I'm not very sure that the struct is correct. 我不太确定该结构是否正确。 How can I modify it? 我该如何修改? Thx 谢谢

Oh well, I think it's obvious why it gives you segfault. 哦,我认为这很明显为什么会给您带来段错误。

 int N=0;
 struct element database[N];

Now watch carefully what have you done. 现在,仔细观察您的工作。 You created an array with 0 elements and you try to store something in it. 您创建了一个包含0个元素的数组,然后尝试在其中存储一些内容。

  strcpy(database->name, file->d_name);

Your array must contain enough space to store the name you wanted to store in it. 您的数组必须包含足够的空间来存储要存储在其中的名称。

The best way to achieve that is using dynamically alocated space with malloc() ; 最好的方法是使用带有malloc()动态分配空间;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM