【发布时间】:2020-05-31 13:32:39
【问题描述】:
我在 Windows 上使用 C 来读取目录的内容和有关每个条目的信息,但是 stat() 函数仅在我打开当前目录“。”时才有效。
directory = opendir(".")
每当我尝试这样的“C:\Users\User\Desktop\programming”时,它都不起作用并输出 -1
directory = opendir("C:\\Users\\User\\Desktop\\programming")
你能在这里指导我吗
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
void perror(const char *str);// for error detail
int main()
{
DIR *directory;
struct dirent *file;
struct stat info;
int entries = 0 ;
// entering the directory
directory = opendir("C:\\Users\\User\\Desktop\\programming");//also C:\\Users\\User\\Desktop\\programming\\ didn't work
if ( directory == NULL )
{
puts("the directory couldn't be accessed or does not exist");
return(2);
}
printf("No type name size TimeStamp \n\n");
while((file=readdir(directory))!= NULL)
{
entries++;
// problem : the stat is not working properly
stat(file->d_name,&info);
if ((stat(file->d_name,&info)) == -1){
printf("can't find %s\n", file->d_name);
perror("ERROR");
}
// show the number of the entry
printf("%2d ",entries);
// determine if file or directory
if(S_ISDIR(info.st_mode))
printf("Dir ");
else
printf("File");
// display the name of the file
printf("%20s",file->d_name);
// display the size of the file
printf("%10d",info.st_size);
// show the last modified time
if(!(S_ISDIR(info.st_mode)))
printf("%30s\n",ctime(&info.st_mtime));
else puts("\n");
}
return(0);
}
【问题讨论】:
-
使用
perror获得额外的错误输出 -
我用过它显示“没有这样的文件或目录”
-
顺便说一句,你为什么要给
stat(file->d_name,&info);打两次电话? -
错了,虽然不影响代码
-
关于声明:
void perror(const char *str);原型已经通过:#include <stdio.h>公开,因此无需编写该原型。