在C语言中实现ls -t选项

问题描述 投票:0回答:1

我必须在C语言中实现ls -a,ls,-t,我成功实现了ls -a。但是我不能处理-t选项。这是我的代码。

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void opt_a(char* path)
{
  DIR* dp = opendir(path);
  struct dirent* dirp;
  while ((dirp = readdir(dp)) != NULL)
  {
    printf("%s  ", dirp->d_name);
  }
  printf("\n");
  closedir(dp);
}
void print_opt(int ac, char** av)
{
  if (strcmp(av[1], "-a") == 0)
  {
    if (ac == 2)
    {
      opt_a(".");
    }
    else
    {
        opt_a(av[2]);
    }
  }
}

我不能用-t选项。希望你们帮我找出来=)

c linux directory ls creation
1个回答
0
投票

首先,将所有文件(file_name和日期)推送到一个链接列表中。

struct linked_list_t {
    char *file_name;
    time_t date; // Get the last modification date by using stat() -> st_mtim
    struct linked_list_t *next;
};

然后,在你的链接列表中循环,当它不是空的时候;每一次循环你都会搜索修改日期最少的文件,打印这个文件,然后删除节点。

例如

linked_list_t *head; // head of the linked_list, contains all dates
linked_list_t *node;
linked_list_t *min_date_node;

while (head) { // loop while linked_list is not empty
    node = head;
    min_date_node = node;

    while (node) { // loop and check for the lowest date
        if (node->date < min_date_node->date)
            min_date_node = node;
        node = node->next;
    }
    printf("%s\n", min_date_node->file_name);
    removeNode(head, min_date_node); // remove min_date_node from main linked_list
}

ref: https:/man7.orglinuxman-pagesman2stat.2.html。

© www.soinside.com 2019 - 2024. All rights reserved.