har*_*had 0 c directory-traversal subdirectory
我试图搜索这个问题,但找不到令人满意的答案.所以这是我的问题:
我正在浏览具有以下代码变体的目录:
一世.
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<string.h>
#include<sys/stat.h>
void traverseDirectory(char name[100]){
DIR* dir;
struct dirent *ent;
struct stat states;
dir = opendir(name);
while((ent=readdir(dir)) != NULL){
stat(ent->d_name,&states);
if(!strcmp(".", ent->d_name) || !strcmp("..", ent->d_name)){
continue;
}
else{
printf("%s/%s\n",name,ent->d_name);
if(S_ISDIR(states.st_mode)){
strcat(name,"/");
strcat(name,ent->d_name);
traverseDirectory(name);
}
}
}
closedir(dir);
}
int main(){
char path[100];
printf("Enter the path:\n");
scanf("%s",&path);
traverseDirectory(path);
}
Run Code Online (Sandbox Code Playgroud)
这个遍历子目录但在遍历第一个子目录并打印其文件后给出分段错误.
输出是:
Enter the path:
/home/harshad/dump
/home/harshad/dump/TraverseDirectory.c
/home/harshad/dump/temp
/home/harshad/dump/temp/temptest.txt
Segmentation fault
Run Code Online (Sandbox Code Playgroud)
II.
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<string.h>
#include<sys/stat.h>
void traverseDirectory(char name[100]){
DIR* dir;
struct dirent *ent;
struct stat states;
dir = opendir(name);
while((ent=readdir(dir)) != NULL){
stat(ent->d_name,&states);
if(!strcmp(".", ent->d_name) || !strcmp("..", ent->d_name)){
continue;
}
else{
printf("%s/%s\n",name,ent->d_name);
if(S_ISDIR(ent->d_type & DT_DIR)){
strcat(name,"/");
strcat(name,ent->d_name);
traverseDirectory(name);
}
}
}
closedir(dir);
}
int main(){
char path[100];
printf("Enter the path:\n");
scanf("%s",&path);
traverseDirectory(path);
}
Run Code Online (Sandbox Code Playgroud)
这个打印给定目录中的所有文件和子目录,但不在子目录中遍历.它的输出是:
Enter the path:
/home/harshad/dump
/home/harshad/dump/TraverseDirectory.c
/home/harshad/dump/temp
/home/harshad/dump/TraverseDirectory1.out
/home/harshad/dump/dump
/home/harshad/dump/test.txt
/home/harshad/dump/SortMarks.c
/home/harshad/dump/TraverseDirectory.out
/home/harshad/dump/TraverseDirectoryTemp.out
/home/harshad/dump/TraverseDirectory1.c
/home/harshad/dump/TraverseDirectoryTemp.c
/home/harshad/dump/FindEven.c
Run Code Online (Sandbox Code Playgroud)
这里dump&temp是子目录,每个子目录包含一些文件.首先,我认为由于用户权限,它可能无法在子目录中遍历(因为它们是由root创建和拥有的),但正如您在第一个程序的输出中看到的那样,并非如此.所以我无法弄清楚这两个程序的问题.PS:在前两行后的输出中,程序打印目录和文件.
你应该真的检查错误opendir()
.如果失败,它将返回NULL
,然后下一个readdir()
将是seg-fault.
这可能就足够了:
dir = opendir(name);
if (!dir)
{
perror(name);
return;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1042 次 |
最近记录: |