【问题标题】:How can I check whether this is directory-path or any filename-path?如何检查这是目录路径还是任何文件名路径?
【发布时间】:2012-01-15 16:18:51
【问题描述】:

通过这个

Why does fopen("any_path_name",'r') not give NULL as return?

我知道在linux中目录和文件被认为是文件。所以当我在 fopen 中以读取模式给出任何目录路径或文件路径时,它不会给出 NULL 文件描述符和?

那么我如何检查它是目录路径还是文件路径?如果我从命令参数中得到一些路径?

【问题讨论】:

  • 通常文件都有扩展名,即“.txt”、“.log”,因此,根据这些,你可以知道它是文件还是目录,但等待更好的答案
  • @DorinDuminica:在 UNIX 上下文中,依赖后缀来识别任何东西都被认为是不好的风格。首先考虑文件属性(如本例中的文件类型),然后尝试file 来识别文件,如果没有其他方法则仅使用扩展名。
  • @thiton 谢谢你,我很感激!

标签: c linux file directory


【解决方案1】:

感谢 zed_0xff 和 lgor Oks

这些东西可以通过这个示例代码来检查

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat statbuf;

FILE *fb = fopen("/home/jeegar/","r");
if(fb==NULL)
    printf("its null\n");
else
    printf("not null\n");

stat("/home/jeegar/", &statbuf);

if(S_ISDIR(statbuf.st_mode))
    printf("directory\n");
else
    printf("file\n");
return 0;
}

输出是

its null
directory

【讨论】:

    【解决方案2】:

    你可以使用S_ISDIR宏。

    【讨论】:

      【解决方案3】:

      man 2 stat:

      NAME
           fstat, fstat64, lstat, lstat64, stat, stat64 -- get file status
      
      ...
      
           struct stat {
               dev_t           st_dev;           /* ID of device containing file */
               mode_t          st_mode;          /* Mode of file (see below) */
      
      ...
      
           The status information word st_mode has the following bits:
      
      ...
      
           #define        S_IFDIR  0040000  /* directory */
      

      【讨论】:

        猜你喜欢
        • 2018-12-18
        • 2011-12-26
        • 2013-08-14
        • 2015-07-30
        • 2013-03-15
        • 2014-03-09
        • 2011-10-16
        • 1970-01-01
        • 2017-08-16
        相关资源
        最近更新 更多