我正在使用 nftw(file tree walk) 来遍历一个目录(它有子目录和文件)。我已经使用 CLI 函数传递了一个目录。现在我需要将叶子文件和目录(空目录)存储到一个链表中并打印出来。我为 nftw 创建了一个名为 as disp
& 的函数,并将其传递给 nftw,以便它打印出有关文件的一些信息。链表存储了stat
& 生成的文件信息,用于打印链接 链表printll
功能被使用。对于文件,我可以检查typeflag == FTW_F
然后输入以下内容,但是如何检查nftw 中的空目录并将它们添加到链接列表中?
我试过以下
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef struct node{
long ino; //Inode number
long f_size; //file size
long a_tm; //Access time
long m_tm; //Modify time
long c_tm; //change time
struct node *next;
}node;
node *tmp = NULL;
static node *head = NULL;
void printll(node *head);
//display function
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
//Function to create linked list
static int linked(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw);
/* ------------------Main---------------------*/
int main(int argc, char *argv[]){
int flags = 0;
if(argc > 2 && strchr(argv[2], 'd') != NULL)
flags |= FTW_DEPTH;
printf("File_type\tF_size\t\tPath\t\t\t\t\t\t\tInode\n");
if(nftw((argc < 2) ? "." : argv[1], disp, 20, flags) == -1) {
perror("nftw");
return -1;
}
printf("\n");
// nftw((argc < 2) ? "." : argv[1], linked, 20, flags);
printll(tmp);
exit(EXIT_SUCCESS);
}
static int disp(const char *fpath,
const struct stat *s,
int typeflag,
struct FTW *ftw){
printf("%-3s\t\t%7jd\t\t%-40s\t\t%ld\n",
(typeflag == FTW_D) ? "d" : (typeflag == FTW_F) ? "f": "???",
s->st_size, fpath, s->st_ino);
struct dirent *r;
if(typeflag == FTW_F){ //How to check empty dirs here?
if(head == NULL){
head = malloc(sizeof(node));
head->ino = s->st_ino;
head->f_size = s->st_size;
head->a_tm = s->st_atime;
head->m_tm = s->st_mtime;
head->c_tm = s->st_ctime;
head->next = NULL;
tmp = head;
} else if(head != NULL) {
if(tmp != NULL){
node *ptr = malloc(sizeof(node));
ptr->ino = s->st_ino;
ptr->f_size = s->st_size;
ptr->a_tm = s->st_atime;
ptr->m_tm = s->st_mtime;
ptr->c_tm = s->st_ctime;
ptr->next = NULL;
tmp->next = ptr;
tmp = tmp->next;
}
}
while(tmp != NULL){
printf("%ld\n", tmp->ino);
printf("%ld\n", tmp->f_size);
printf("%ld\n", tmp->a_tm);
printf("%ld\n", tmp->m_tm);
printf("%ld\n", tmp->c_tm);
tmp = tmp->next;
}
}
return 0;
}
void printll(node *head){
node *ptr;
if(head == NULL)
printf("The linked list is NULL\n");
ptr = head;
while(ptr != NULL){
printf("%ld\n", ptr->ino);
printf("%ld\n", ptr->f_size);
printf("%ld\n", ptr->a_tm);
printf("%ld\n", ptr->m_tm);
printf("%ld\n", ptr->c_tm);
ptr = ptr->next;
}
}