在 C 中访问目录 [英] Accessing Directories in C

查看:10
本文介绍了在 C 中访问目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序是打开一个目录并显示文件名...即如果有一个文件..它应该说 FILE....else DIRECTORY..但程序将所有文件显示为目录..

The program is to open a directory and to display the name of the files... i.e if there is a file..it should say FILE....else DIRECTORY.. but the program displays all the files as directory..

任何人都可以检查代码是否有任何错误....thnx

Could anyone pls check the code for any errors....thnx

#include<stdio.h>
#include<dirent.h>
#define DIR_path "root/test"      
main()
 {
   DIR *dir;
   dir=opendir(DIR_PATH);
   printf("THe files inside the directory :: 
");

  struct dirent *dent;
  if(dir!=NULL)
   {

       while((dent=readdir(dir)))
         {
            FILE *ptr;
            printf(dent->d_name);

              if(ptr=fopen(dent->d_name,"r"))
                {
                     print("	FILE
");
                     fclose(ptr);
                }
              else
                    printf("	 DIRECTORY
");
        }
           close(dir);
    }
    else
            printf("ERROR OPENIN DIRECTORY");

}

推荐答案

一个问题是目录也是一种文件,可以正常fopen()ed.你想对每个文件调用 lstat() 来检查它是否是一个目录.像这样:

One problem is that a directory is also a type of file, and can be normally fopen()ed. You want to call lstat() on each file to check whether it is a directory. Like this:

struct stat st;
lstat(dent->d_name, &st);
if(S_ISDIR(st.st_mode))
   printf("	 DIRECTORY
");
else
   printf("	 FILE
");

但是这个错误应该导致所有条目都显示为文件.您是否对该目录中的文件具有读取权限?fopen() 调用后 errno 的值是多少?

But this error should lead to all entries being displayed as files. Do you have read permissions for the files in this directory? What is the value of errno after the fopen() call?

这篇关于在 C 中访问目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆