首页 > 解决方案 > 如何将路径名称存储在 C 中的列表或字符串数​​组中?

问题描述

我有以下代码可以在文件夹中递归查找文件。我提示输入的参数是文件所在的路径,以及 2 我要列出的文件的“通配符”:

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#define MAX_STRING_SIZE 255

void listFilesRecursively(char *path, char *suffix);


int main()
{
    // Directory path to list files
    char path[100];
    char suffix[100];

    // Suffix Band Sentinel-2 of Type B02_10m.tif

    // Input path from user
    printf("Enter path to list files: ");
    scanf("%s", path);
    printf("Enter the wildcard: ");
    scanf("%s", suffix);

    listFilesRecursively(path, suffix);

    return 0;
}

int string_ends_with(const char * str, const char * suffix)
{
    int str_len = strlen(str);
    int suffix_len = strlen(suffix);

    return 
        (str_len >= suffix_len) &&
        (0 == strcmp(str + (str_len-suffix_len), suffix));
}

/**
 * Lists all files and sub-directories recursively 
 * considering path as base path.
 */
void listFilesRecursively(char *basePath, char *suffix)
{
    char path[1000];
    struct dirent *dp;
    DIR *dir = opendir(basePath);


    // Unable to open directory stream
    if (!dir)
        return;


    while ((dp = readdir(dir)) != NULL)
    {

        if (strcmp(dp->d_name, ".") != 0 && strcmp(dp->d_name, "..") != 0)
        {
            //printf("%s\n", dp->d_name);

            // Construct new path from our base path
            strcpy(path, basePath);
            strcat(path, "/");
            strcat(path, dp->d_name);

            if (string_ends_with(path, suffix))
                printf("%s\n", path);

            listFilesRecursively(path, suffix);
        }
    }
    //int num = sizeof(arr) / sizeof(arr[0]);
    //printf("%d", num);
    //for(int i = 0; i <= num; i++){
    //    printf(arr[i]);

    closedir(dir);
}

它工作正常,因为它打印以某个结尾(第 66:67 行)结尾的文件,但是,如何将这些值存储在列表中以在我的程序中返回?我尝试了不同的东西,但它们似乎都不起作用。

非常感谢!

标签: carraysstringfilewildcard

解决方案


推荐阅读