c - 如何将路径名称存储在 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 行)结尾的文件,但是,如何将这些值存储在列表中以在我的程序中返回?我尝试了不同的东西,但它们似乎都不起作用。
非常感谢!
解决方案
推荐阅读
- continuous-integration - 在 CircleCI 构建的目录中找不到 package.json
- r - 如何阻止合并重叠多边形的强化
- javascript - 获取消息(按 ID)并进行编辑
- apache - 为什么我的根目录可以从 apache 访问?
- visual-studio-code - 文件被 VS Code (Visual Studio Code) 锁定
- c# - 使用 JQuery/Ajax 的级联下拉菜单返回重复第一个表行的数据
- git - 如何在 graphql 查询中按文件扩展名过滤
- javascript - 表单验证后如何重定向页面
- google-sheets - Google Sheets 在查询功能中的动态数据范围
- thread-safety - 在 Huey 中使用线程管理共享资源