首页 文章

C open()目录没有错误

提问于
浏览
0

我有一个打开文件的函数,然后使用标准的open()和read()函数读取这些文件 . 我使用errno变量来解决所有可能的错误,例如拒绝权限或没有这样的文件或目录,但是当我在目录上使用open时它不会返回错误,只需打开它并尝试读取它 . 那么当我打开目录时如何才能收到错误消息?

3 回答

  • 2

    目录也是一个文件(就Unix / Linux而言) . 所以一般来说你不会得到错误 . 您可以使用statfstat函数来跟踪普通或特殊文件 .

    当您使用stat或fstat时,您需要声明一个struct stat变量,如 struct stat var . stat 结构有一个名为 st_mode 的成员,它具有哪种文件的信息 .

    struct stat {
        dev_t     st_dev;     /* ID of device containing file */
        ino_t     st_ino;     /* inode number */
        mode_t    st_mode;    /* protection */
        nlink_t   st_nlink;   /* number of hard links */
        uid_t     st_uid;     /* user ID of owner */
        gid_t     st_gid;     /* group ID of owner */
        dev_t     st_rdev;    /* device ID (if special file) */
        off_t     st_size;    /* total size, in bytes */
        blksize_t st_blksize; /* blocksize for file system I/O */
        blkcnt_t  st_blocks;  /* number of 512B blocks allocated */
        time_t    st_atime;   /* time of last access */
        time_t    st_mtime;   /* time of last modification */
        time_t    st_ctime;   /* time of last status change */
    };
    
  • 1

    目录也是Unix *中的文件,如果要避免通过 open() 打开目录,则可能需要检查文件类型 . 正如@nayabbashasayed所说,您可以使用 stat 来检查文件类型和更多信息 .

    以下是通过 stat 检查类型的示例代码:

    const char  *filePath;
    struct stat  fileStatBuf;
    if(stat(filePath,&fileStatBuf) == -1){
         perror("stat");
         exit(1);
    }
    
    /*
     *You can use switch to check all
     *the types you want, now i just use 
     *if to check one.
    */
    if((fileStatBuf.st_mode & S_IFMT) == S_IFDIR){
        printf("This type is directory\n");
    }
    

    希望能帮到你 .

  • 0

    我不想使用其他任何东西作为读写,我发现使用 read() 而不是open()返回错误

相关问题