如何从C中的目录中检索文件名和子目录名?
好的,我有这样的事情:
struct dirent *dp;
DIR *dir;
char fullname[MAXPATHLEN];
char** tmp_paths = argv[1]; //Not the exact code but you get the idea.
...
while ((dp = readdir(dir)) != NULL)
{
struct stat stat_buffer;
sprintf(fullname, "%s/%s", *tmp_paths, dp->d_name);
if (stat(fullname, &stat_buffer) != 0)
perror(opts.programname);
/* Processing files */
if (S_ISDIR(stat_buffer.st_mode))
{
nSubdirs++;
DIRECTORYINFO* subd = malloc(BUFSIZ);
}
/* Processing subdirs */
if (S_ISREG(stat_buffer.st_mode))
{
nFiles++;
FILEINFO *f = malloc(BUFSIZ);
}
}
如何将文件名和子目录名读入我自己的结构 DIRECTORYINFO 和 FILEINFO 中?我浏览了 stat.h 但没有发现任何有用的东西。
Ok I have something like this:
struct dirent *dp;
DIR *dir;
char fullname[MAXPATHLEN];
char** tmp_paths = argv[1]; //Not the exact code but you get the idea.
...
while ((dp = readdir(dir)) != NULL)
{
struct stat stat_buffer;
sprintf(fullname, "%s/%s", *tmp_paths, dp->d_name);
if (stat(fullname, &stat_buffer) != 0)
perror(opts.programname);
/* Processing files */
if (S_ISDIR(stat_buffer.st_mode))
{
nSubdirs++;
DIRECTORYINFO* subd = malloc(BUFSIZ);
}
/* Processing subdirs */
if (S_ISREG(stat_buffer.st_mode))
{
nFiles++;
FILEINFO *f = malloc(BUFSIZ);
}
}
How do I go about reading in the file names and subdirectory names into my own structure DIRECTORYINFO and FILEINFO? I've gone through stat.h and haven't found anything useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 UNIX 世界中,名称不是文件的一部分,因此 stat(2) 无法检索有关它的信息。但在您的代码中,您的名称为
dp->d_name
,因此您可以将该字符串复制到您自己的数据结构中。这应该是相当简单的。如果这不是你的问题,我不明白这个问题。
In the UNIX world the name is not part of the file, so
stat(2)
cannot retrieve information about it. But in your code you have the name asdp->d_name
, so you can copy that string into your own data structure. That should be fairly simple.If this is not your problem I didn't understand the question.
看看这个问题及其答案。您可能想使用
dirent->d_name
。Take a look at this question and its answers. You probably want to use
dirent->d_name
.Glob 是你的朋友
glob() 函数根据 shell 使用的规则搜索所有匹配模式的路径名
始终可以使用unix man 页面
Glob is your friend
The glob() function searches for all the pathnames matching pattern according to the rules used by the shell
To get more details you can always use the unix man page