C-忽略子目录名称,仅打印文件名称

C-忽略子目录名称,仅打印文件名称,c,recursion,file-listing,C,Recursion,File Listing,有了这段代码,我能够递归地打印给定路径中的所有文件和子目录 我想要的是忽略(而不是打印)所有的子目录名,只打印文件名 代码如下: #include <stdio.h> #include <dirent.h> #include <string.h> void listFilesRecursively(char *basePath) { char path[1000]; struct dirent *dp; DIR *dir = op

有了这段代码,我能够递归地打印给定路径中的所有文件和子目录

我想要的是忽略(而不是打印)所有的子目录名,只打印文件名

代码如下:

#include <stdio.h>
#include <dirent.h>
#include <string.h> 


void listFilesRecursively(char *basePath)
{
    char path[1000];
    struct dirent *dp;
    DIR *dir = opendir(basePath);

    if (!dir)
        return;

    while ((dp = readdir(dir)) != NULL)
    {
        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, dp->d_name);

            listFilesRecursively(path);
            printf("%s\n", path);
        }
    }

    closedir(dir);
}

int main()
{
    char path[100];

    printf("Enter path to list files: ");
    scanf("%s", path);

    listFilesRecursively(path);

    return 0;
}
#包括
#包括
#包括
递归作废列表文件(char*basePath)
{
字符路径[1000];
结构方向*dp;
DIR*DIR=opendir(基本路径);
如果(!dir)
返回;
而((dp=readdir(dir))!=NULL)
{
如果(strcmp(dp->d_name,“.”)=0和&strcmp(dp->d_name,“…”)!=0)
{
strcpy(路径、基本路径);
strcat(路径“/”;
strcat(路径,dp->d_名称);
列表文件递归(路径);
printf(“%s\n”,路径);
}
}
closedir(dir);
}
int main()
{
字符路径[100];
printf(“输入列表文件的路径:”);
scanf(“%s”,路径);
列表文件递归(路径);
返回0;
}

有一些宏告诉您它是什么类型的文件:

  • S_ISREG()
    :常规文件
  • S_ISDIR()
    :目录文件
  • S_ISCHR()
    :字符特殊文件
  • S_ISBLK()
    :阻止特殊文件
  • S_ISFIFO()
    :管道或FIFO -
    S_ISLNK()
    :符号
  • S_ISSOCK()
    :链接套接字
首先,您可以使用以下函数之一获取信息:

#include <sys/stat.h>
int stat(const char *restrict pathname, struct stat *restrict buf );
int fstat(int fd, struct stat *buf);
int lstat(const char *restrict pathname, struct stat *restrict buf );
int fstatat(int fd, const char *restrict pathname, struct stat *restrict buf, int flag);

有一些宏告诉您它是什么类型的文件:

  • S_ISREG()
    :常规文件
  • S_ISDIR()
    :目录文件
  • S_ISCHR()
    :字符特殊文件
  • S_ISBLK()
    :阻止特殊文件
  • S_ISFIFO()
    :管道或FIFO -
    S_ISLNK()
    :符号
  • S_ISSOCK()
    :链接套接字
首先,您可以使用以下函数之一获取信息:

#include <sys/stat.h>
int stat(const char *restrict pathname, struct stat *restrict buf );
int fstat(int fd, struct stat *buf);
int lstat(const char *restrict pathname, struct stat *restrict buf );
int fstatat(int fd, const char *restrict pathname, struct stat *restrict buf, int flag);

man2stat
是你的朋友。
man2stat
是你的朋友。
struct stat *statptr;
if (lstat(fullpath, statptr) < 0)
{
    printf("error\n");
    //return if you want
}
switch (statptr->st_mode & S_IFMT) {
    case S_IFREG:  ...
    case S_IFBLK:  ...
    case S_IFCHR:  ...
    case S_IFIFO:  ...
    case S_IFLNK:  ...
    case S_IFSOCK: ... 
    case S_IFDIR:  ... 
    }