我想知道如何通过 C 中的代码导航和编辑文件夹和文件。我查找了库 dirent.h 但我不确定哪些函数用于遍历目录。我什至在这种情况下使用了正确的库吗?如果是这样,您能否简要解释一下我需要在文件夹中移动和更改文件的一些基本功能。另外,我是否必须使用某种指针来跟踪我当前所在的目录,就像使用链表一样?我是否需要创建一棵二叉树才能获得指针可以指向的东西?
问问题
6777 次
1 回答
5
最重要的功能是:
opendir(const char *) - 打开一个目录并返回一个 DIR 类型的对象
readdir(DIR *) - 读取目录的内容并返回 dirent (struct) 类型的对象
closedir(DIR *) - 关闭一个目录
例如,您可以使用以下代码列出目录的内容:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
char *pathcat(const char *str1, char *str2);
int main()
{
struct dirent *dp;
char *fullpath;
const char *path="C:\\test\\"; // Directory target
DIR *dir = opendir(path); // Open the directory - dir contains a pointer to manage the dir
while (dp=readdir(dir)) // if dp is null, there's no more content to read
{
fullpath = pathcat(path, dp->d_name);
printf("%s\n", fullpath);
free(fullpath);
}
closedir(dir); // close the handle (pointer)
return 0;
}
char *pathcat(const char *str1, char *str2)
{
char *res;
size_t strlen1 = strlen(str1);
size_t strlen2 = strlen(str2);
int i, j;
res = malloc((strlen1+strlen2+1)*sizeof *res);
strcpy(res, str1);
for (i=strlen1, j=0; ((i<(strlen1+strlen2)) && (j<strlen2)); i++, j++)
res[i] = str2[j];
res[strlen1+strlen2] = '\0';
return res;
}
pathcat 函数只是连接 2 个路径。
此代码仅扫描所选目录(而不是其子目录)。您必须创建自己的代码来执行“深入”扫描(递归函数等)。
于 2014-08-01T02:49:59.143 回答