我正在从 Ubuntu 的终端运行我的代码,以搜索特定文件,但搜索会在该文件夹内部以及外部生成文件夹和文件。这是代码:
(编译和运行)
#include <stdio.h> // For perror
#include <stdlib.h>
#include <sys/types.h> // For stat, opendir, readdir
#include <sys/stat.h> // For stat
#include <unistd.h> // For stat
#include <dirent.h> // For opendir, readdir
int displayAllFiles(char * directory)
{
DIR *dir;
struct dirent *ent;
dir = opendir (directory);
if (dir != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
return 1;
}
int main(int argc , char * argv[])
{
DIR *dir;
struct dirent *entry;
int result;
struct stat status;
char path[PATH_MAX];
dir = opendir(argv[1]);
if (!dir)
{
perror("opendir");
exit(1);
}
entry = readdir(dir);
while (entry)
{
result = snprintf(path, sizeof(path), "%s", argv[1]);
snprintf(&path[result], sizeof(path) - result, "/%s", entry->d_name);
int out = displayAllFiles(path);
printf("%s", path);
result = lstat(path, &status);
if (-1 == result)
{
printf("\n");
perror("stat");
exit(2);
}
if (S_ISLNK(status.st_mode))
{
printf("%s", " is a symbolic link");
}
printf("\n");
entry = readdir(dir);
}
return(0);
}
我从终端打./exer4 check
,那个文件夹check
是父文件夹,然后:
insideCheck
在里面check
moreInside
在里面insideCheck
- 并且
david.txt
在里面moreInside
但是,我得到的是:
a@ubuntu:~/Desktop$ ./exer4 check
check
..
Link to workspace2
eclipse 4 linux
fol
.
basherFolder
Link to eclipse
test
eclipse
exer4
doc.txt~
check/..
..
.
insideCheck
check/.
..
moreInside
.
david.txt~
check/insideCheck
出了点问题,我可以看到,但不知道是什么。
我会很感激你的帮助。