c - 如何使用c将目录的文件名添加到数组结构中

标签 c arrays posix

谁能告诉我如何使用 C 中的结构数组保存目录中的目录路径。在下面的代码中,谁能告诉我哪里需要更改?

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/dir.h>
#include <locale.h>
#include <stdint.h>
#include <string.h>

#define FALSE 0
#define TRUE ! FALSE

typedef struct{
    char *path;
}filepath;

struct stat sb;
extern int alpahsort();
int dir_detect(char *name);

int main (int argc, char *argv[])
{
    filepath my_array_path[100];
    char *each_name;
    const char *pathname=NULL;
    char success; int ret=0;
    struct direct **files;
    int j=0,i,count,count_dir;
    int file_select();
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    printf("%s\n",argv[1]);
    pathname=argv[1];
    printf("%s\n",pathname);
    DIR *dp;
    struct dirent *ep;
    dp = opendir (pathname);

    count = scandir(pathname, &files, file_select, alphasort);

    if (dp != NULL)
    {
        while ((ep = readdir (dp))!=NULL){
            printf("the number of files=%d\n",count);
            char *buffer;


            //from here ....
            //my_array_path[i].path=malloc(strlen(buffer+1));
            //strcpy(my_array_path[i].path,buffer);
            my_array_path[i].path=strdup(ep->d_name);
            printf("the name of the file is %s\n",my_array_path[i].path);
            // to here......

我想知道我所做的是否正确。其他代码如下。

最佳答案

C 提供了 2 种主要的读取目录内容的方法,类似于读取文件的 2 种方法。就像您可以选择使用低级别 read/write 进行阅读的文件一样无缓冲输入例程或使用 FILE* 读取文件文件流,您也可以选择读取目录。

对于目录,您可以选择 readdir其中每次调用该函数都会返回一个指向 direct struct指针对于目录中的文件,将文件位置指示器移动到下一个要读取的文件。您必须反复调用readdir访问目录中的所有文件。

第二种类型的目录访问依赖scandir它返回一个指向 dirent structs数组的指针包含从该目录读取的所有文件/目录。与scandir您只需迭代返回的数组即可访问目录中包含的每个文件/目录。

所以这两种方法之间的主要区别是 readdir返回指向文件的单个指针,scandir返回一个指向包含目录中所有文件的数组的指针。 scandir还为文件/目录列表提供了几个预定义的排序例程。 ( alphasortversionsort )提供了一种对 direct struct entries 进行排序的便捷方法。请注意,要使用预定义的排序例程,您必须包含对 _BSD_SOURCE 的定义。在您的代码中。

下面显示了使用 scandir 的示例与预定义的 alphasort在一个小目录上:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>  /* opendir  */
#include <dirent.h>     /* opendir, readdir, scandir  */
#include <errno.h>

#ifndef _BSD_SOURCE     /* for scandir sort routines  */
#define _BSD_SOURCE
#endif /* _BSD_SOURCE */

int sdfilt (const struct dirent *de);

int main (int argc, char **argv) {

    if (argc < 2 )
        fprintf (stderr, "warning: usage: %s [dirname (default '.')][mode (default 14)\n", argv[0]);


    char *dname = (argc > 1) ? argv[1] : ".";   /* directory name to get listing of */
    struct dirent **namelist = NULL;            /* dirent structure to hold listing */
    int ndir = 0;                               /* num dirs scandir returns, -1 err */
    size_t it = 0;                              /* simple iterator for dir list     */

    /* call scandir to fill pointer to array of dirent entries  */
    if ((ndir = scandir (dname, &namelist, sdfilt, alphasort)) < 0)
    {
        perror("scandir");  /* throw error & return on failure  */
        return 1;
    }

    /* print each of the entries in alphasort order  */
    printf ("\nscandir example (alphasort):\n\n");
    for (it = 0; it < ndir; it++)
        printf("  nl[%2zu] %s\n", it, namelist[it]->d_name);

    /* print each entry in reverse sort order & free */
    printf ("\nreverse:\n\n");
    it = ndir;
    while (it--) {
        printf("  nl[%2zu] %s\n", it, namelist[it]->d_name);
        if (namelist[it]->d_name)
            free (namelist[it]);
    }
    free(namelist);

    printf ("\n");

    return 0;
}

/* simple scandir filter that omit strings and
dot files '.' and '..' from dirent entries */
int sdfilt (const struct dirent *de)
{
    if (strcmp (de->d_name, ".") == 0 || strcmp (de->d_name, "..") == 0)
        return 0;
    else
        return 1;
}

输出

$ ./bin/scandir_simple tmp

scandir example (alphasort):

  nl[ 0] bin
  nl[ 1] d1
  nl[ 2] d2
  nl[ 3] rdrmstat.c
  nl[ 4] rmftw-io-out.txt
  nl[ 5] walk-ftw-test.c
  nl[ 6] walk-nftw-test.c

reverse:

  nl[ 6] walk-nftw-test.c
  nl[ 5] walk-ftw-test.c
  nl[ 4] rmftw-io-out.txt
  nl[ 3] rdrmstat.c
  nl[ 2] d2
  nl[ 1] d1
  nl[ 0] bin

关于c - 如何使用c将目录的文件名添加到数组结构中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29484568/

相关文章:

c - fork() 之后无法从子进程检索 mmap 共享内存

C malloc 段错误

arrays - 组合 2D(二维)数组

java - 尝试将数组的元素设置为父类(super class)对象时出现 ArrayStoreException

c - 限制与服务器不工作的最大连接数

c - 保证每个线程的执行

c - 将 GCC 扩展与使用 clang 编译的代码一起使用?

java - 如何将多个不相关的int值添加到数组中

c - msgget 无法加入 mq

c++ - 在 C++ 中取消引用 void 指针