检查一个目录. readdir返回的条目是目录,链接或文件. dent->
我正在制作一个在
Linux shell中运行的程序,并接受一个参数(一个目录),并显示目录中的所有文件及其类型.
输出应该是这样的: << ./Program testDirectory Dir directory1 lnk linkprogram.c reg file.txt 如果没有参数,则使用当前目录.这是我的代码: #include <stdio.h> #include <dirent.h> #include <sys/stat.h> int main(int argc,char *argv[]) { struct stat info; DIR *dirp; struct dirent* dent; //If no args if (argc == 1) { argv[1] = "."; dirp = opendir(argv[1]); // specify directory here: "." is the "current directory" do { dent = readdir(dirp); if (dent) { printf("%c ",dent->d_type); printf("%s n",dent->d_name); /* if (!stat(dent->d_name,&info)) { //printf("%u bytesn",(unsigned int)info.st_size); }*/ } } while (dent); closedir(dirp); } //If specified directory if (argc > 1) { dirp = opendir(argv[1]); // specify directory here: "." is the "current directory" do { dent = readdir(dirp); if (dent) { printf("%c ",dent->d_name); /* if (!stat(dent->d_name,&info)) { printf("%u bytesn",(unsigned int)info.st_size); }*/ } } while (dent); closedir(dirp); } return 0; } 出于某种原因,dent-> d_type不显示文件类型.我不确定该怎么办,有什么建议吗? 解决方法
d_type是一种速度优化,可以在支持lstat(2)时保存.
正如 如果d_type == DT_UNKNOWN,如果单独的文件名不足以决定它是无趣的,那么你总是需要回到使用 Linux 无论如何,其他答案主要涵盖了一些内容,但是在d_type == DT_UNKNOWN(Linux上为0,d_type存储在曾经是填充字节,直到Linux 2.6.4)的情况下,错过了你需要回退的关键细节. . 为了便于移植,你的代码需要检查struct dirent甚至是一个d_type字段,如果你使用它,或者你的代码甚至不能在GNU和BSD系统之外编译. (见readdir(3)) 我为finding directories with readdir写了一个例子,当d_type在编译时,DT_UNKNOWN和符号链接不可用时,使用带有回退到stat的d_type. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- ssh与ajax结合之json异常:org.apache.struts2.json.JSONEx
- ruby-on-rails – Rails 4.2中未定义的方法’authenticate_
- c – 如果在UNIX中的信号处理过程中会发送相同的信号到程序
- 【全栈React】第9天: 样式
- ios – 为Swift / Obj-c项目运行XCTest时出错(错误83)
- AJAX - onreadystatechange 事件
- c# – 复制除流的最后16个字节以外的所有字节?早期检测到流
- c# – 使用WebClient快速失败
- PostgreSQL explain返回行的评估
- 警告:从不兼容的指针类型传递参数[默认启用]