簡體   English   中英

在 C 中實現 ls -t 選項

[英]Implementing ls -t option in C

我必須在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 選項。 希望大家幫我看看=)

首先,將所有文件(文件名和日期)推送到鏈表:

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
}

參考: https://man7.org/linux/man-pages/man2/stat.2.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM