有无读目录(dir)这一说

最近看一个小程序,看到它打开一个目录,同时使用dirfd函数,将其打开的DIR流转化为普通的文件描述符,然后对其想普通文件一样读,

那么这个读是合法的吗,我自己有点疑惑,然后写了一个小测试程序,测试一下

#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>              /* errno */
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main(){
        int n, result,handle;
        int length = 100;
        unsigned char data[100];
        int mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
        struct stat filestat;
        char filename[] = "/home/liujie/test.txt";
        if ((stat(filename, &filestat) == 0) && (S_ISDIR(filestat.st_mode)))
        {
                printf("the file %s is a directory/n", filename);
                DIR *dirp = opendir(filename);
                handle = dirfd(dirp);  //extract the file descriptor used by a DIR stream
                //flags_and_attributes |= FILE_DIRECTORY_FILE;
        }else{
                printf("the file %s is a file./n", filename);
                handle = open(filename, O_RDWR , mode);
        }
        n = read(handle, data, length);
        if (n < 0)
        {
                result = 0;
                switch (errno)
                {
                        case EISDIR:
                                printf("not implemented/n");
                                break;
                         default:
                                perror("read");
                               
                }
        }
        printf("the length is %d/n", n);    
        return 0;
}
结果为:
the file /home/liujie/test.txt is a file.
the length is 35
与直接运行命令 wc -m test.txt的结果一样,都是35字符(节)
如果修改,将文件改成目录,即把filename改成/home/liujie/,则结果如下
the file /home/liujie/ is a directory
not implemented
the length is -1
这说明这样读目录是不正确的,在c中参考,如果判断是目录,则使用opendir,readdir,closedir等函数来操作目录。
继续学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值