什么是使用stat()函数来测试一个的dirent是一个目录或文件的正确方法? [英] What is the correct way to use the stat() function to test if a DIRENT is a directory or a file?
问题描述
我在遇到一些麻烦了如果(S_IFDIR(stbuf.st_mode))'行。这是测试一个目录递归到正确的方法是什么?目前的功能似乎为1或2个循环做是正确的,然后失败,段故障。
我试过以下,可能更多的条件。
S_ISDIR(ST_MODE)
((ST_MODE&安培; ST_IFMT)== S_IFDIR)
S_IFDIR(stbuf.st_mode)
我已经包含了整个功能,因为我很担心的问题可能是在其他地方。
无效getFolderContents(字符*来源,INT TEMP){
结构统计stbuf;
INT ISDIR;
dirPnt =执行opendir(源);
如果(dirPnt!= NULL){
而(进入= READDIR(dirPnt)){
字符* C =入门> d_name;
如果(STRCMP(入门> d_name,CWD)== 0 || STRCMP(入门> d_name,父母)== 0){
}
其他{
STAT(入门级GT&; d_name,&安培; stbuf);
的printf(%I%I,S_IFMT,stbuf.st_mode);
如果(S_IFDIR(stbuf.st_mode)){//测试DIR或文件
的printf(DIR:%S \\ n,入门> d_name);
getFolderContents(入门> d_name,0);
}
的printf(文件:%s \\ n,入门> d_name);
}
}
closedir(dirPnt);
}
是的,这是正确的。但是,因为你永远不换入目录,你会找不到它。
考虑下面的目录结构:
A
|
+ - B
| |
| + - Ç
...
您code将扫描其当前目录,找到A。这将决定它是一个目录,递归调用本身,打开一阅读。这工作。这种扫描将找到一个名为B目录中,但尝试使用的条目名称只会无法打开它,因为路径现在是A / B。
我建议改变到该目录(以 CHDIR()
)打开它。这意味着你可以只执行opendir(。)
。存储旧路径, CHDIR()递归时该级别完成再次
出来(做一个递归调用深究下去之前没有)。
I'm having some trouble with the 'if(S_IFDIR(stbuf.st_mode))' line. Is this the correct way to test for a directory to recurse into? The function at the moment seems to do it right for 1 or 2 loops and then fails and segmentation faults.
I've tried the following and probably more as the condition.
S_ISDIR(st_mode)
((st_mode & ST_IFMT) == S_IFDIR)
S_IFDIR(stbuf.st_mode)
I've included the whole function because I'm concerned the problem might be elsewhere.
void getFolderContents(char *source, int temp){
struct stat stbuf;
int isDir;
dirPnt = opendir(source);
if(dirPnt != NULL){
while(entry = readdir(dirPnt)){
char *c = entry->d_name;
if(strcmp(entry->d_name, cwd) == 0 || strcmp(entry->d_name, parent) == 0){
}
else{
stat(entry->d_name, &stbuf);
printf("%i %i ", S_IFMT, stbuf.st_mode);
if(S_IFDIR(stbuf.st_mode)){ //Test DIR or file
printf("DIR: %s\n", entry->d_name);
getFolderContents(entry->d_name, 0);
}
printf("FILE: %s\n", entry->d_name);
}
}
closedir(dirPnt);
}
Yes, that's correct. But since you never change into the directory, you will not find it.
Consider the following directory hierarchy:
a
|
+- b
| |
| +- c
...
Your code will scan its current directory, and find "a". It will determine that it is a directory, and call itself recursively, and open "a" for reading. This works. That scan will find a directory called "b", but trying to open it using the entry name only will fail, since the path is now "a/b".
I recommend changing into the directory (with chdir()
) before opening it. That means you can just opendir(".")
. Store the old path, and chdir()
out again when recursing that level is done (not before doing a recursive call to go deeper).
这篇关于什么是使用stat()函数来测试一个的dirent是一个目录或文件的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!