嘿,谢谢你的阅读。
我正在制作一个程序,该程序接受1个参数(目录),并使用opendir()/ readdir()读取目录中的所有文件,并使用stat显示文件类型(reg,链接,目录等)。当我在shell中执行程序时,我收到错误消息“ No Such file or Directory”(我正在使用redhat linux)。这是我的代码:
#define _BSD_SOURCE
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
DIR *dirp;
struct dirent* dent;
struct stat info;
//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)
{
//////////////////////////////////////////////////////////////////////////
if (stat(dent->d_name, &info) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
switch (info.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("dir "); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("lnk "); break;
case S_IFREG: printf("reg "); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
//////////////////////////////////////////////////////////////////////////
printf("%s \n", dent->d_name);
}
} 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)
{
/////////////////////////////////////////////////////////////////////////////////////
if (stat(dent->d_name, &info) == -1) {
perror("stat");
exit(EXIT_FAILURE);
}
switch (info.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("dir "); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFLNK: printf("lnk "); break;
case S_IFREG: printf("reg "); break;
case S_IFSOCK: printf("socket\n"); break;
default: printf("unknown?\n"); break;
}
//////////////////////////////////////////////////////////////////////////////////////
// printf("%s\n", argv[1]);
printf("%s \n", dent->d_name);
}
} while (dent);
closedir(dirp);
}
return 0;
}
有任何想法吗?我有点卡住了。感谢您的输入
另外,是否将使用stat输出“链接”类型的文件,还是必须使用lstat?不知道在这种情况下如何使用lstat,如果我将结构类型更改为“ struct lstat info”,则会引发错误。
dent->d_name
是相对于当前目录的文件名(例如“ /home/barney/myfile.txt”),而不是文件的绝对完整路径(例如/home/barney/sources/myfile.txt),即统计所期望的。
这就是为什么stat无法找到路径。dent->d_name
在每次调用stat之前先打印,以观察这些不正确的路径。
编辑:您可以尝试chdir()将您的工作目录更改为argv [1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句