69,371
社区成员
发帖
与我相关
我的任务
分享
char dirPath[BUFF_SIZE] = {"/home/doc/"};
DIR* dp = opendir(DIR_PATH);
struct dirent* dir;
while((dir = readdir(dp)) != NULL)
{
int len = strlen(dir->d_name) + strlen(dirPath) + 1;
char fileName[len];
strncpy(fileName,dirPath,strlen(dirPath)+1);
strcat(fileName,dir->d_name);
printf("%s\n",fileName);
}
char path[] = "/usr/doc";
换成了
char path[] = "/dev/fd";
这个目录下刚好是个连接到别的目录的文件
命令ls -l /dev/fd输出是
jiadun@jiadun-desktop:~/linux_c/4th/ShowDir2$ ls -l /dev/fd
lrwxrwxrwx 1 root root 13 5月 29 2018 /dev/fd -> /proc/self/fd
但运行代码程序输出结果是
jiadun@jiadun-desktop:~/linux_c/4th/ShowDir2$ ./a.out
.
..
0
1
2
3
char dirPath[BUFF_SIZE] = {"/home/doc/"}; DIR* dp = opendir(DIR_PATH); struct dirent* dir; while((dir = readdir(dp)) != NULL) { int len = strlen(dir->d_name) + strlen(dirPath) + 1; char fileName[len]; strncpy(fileName,dirPath,strlen(dirPath)+1); strcat(fileName,dir->d_name); printf("%s\n",fileName); }
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
char path[] = "/usr/doc";
DIR *dp = opendir(path);
if (dp != NULL)
{
struct dirent *dir;
while ((dir = readdir(dp)) != NULL)
{
printf("%s\n",dir->d_name);
}
closedir(dp);
}
return 0;
}
测试并没有发现你的问题。
而且!!!就算你没搞错你真正读取的路径,你读取的不是 /home/doc 这一层么,怎么会把 doc 中的文件夹链接中的文件读取出来了?system("dir /b /a-d c:\\*.* >d:\\allfiles.txt"); //读文件d:\\allfiles.txt的内容即C:\\下所有文件的名字 system("dir /b /a-d /s c:\\*.* >d:\\allfilesinsub.txt"); //读文件d:\\allfilesinsub.txt的内容即C:\\下所有文件的名字包含子目录 system("dir /b /ad c:\\*.* >d:\\alldirs.txt"); //读文件d:\\alldirs.txt的内容即C:\\下所有子目录的名字 请记住,能用shell命令获取文件、文件夹信息或者操作文件、文件夹最好用shell命令获取或者操作,而不要用各种API获取或者操作,因为当遇到非法文件夹名或非法文件名或非法文件长度、非法文件日期、压缩文件、链接文件、稀疏文件……等各种意料之外的情况时,API会处理的不全面或陷入死循环,而shell命令不会。 如果嫌system黑窗口一闪,将system("...")替换为WinExec("cmd /c ...",SW_HIDE); linux下使用ls命令。