Linux/Open目录作为文件 [英] Linux/ Open directory as a file

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

问题描述

我一直在阅读Brian Kernighan和Dennis Ritchie-C编程语言,第8.6章是关于UNIX OS下的目录列表.他们说所有内容甚至目录都是文件.这意味着我应该能够将目录作为文件打开吗?我已经使用stdio函数尝试过它,但是它没有用.现在,我正在尝试使用UNIX系统功能.当然,我没有使用UNIX,而是使用Ubuntu linux.这是我的代码:

I've been reading Brian Kernighan and Dennis Ritchie - The C Programming Language and chapter 8.6 is about directory listing under UNIX OS. They say that everything and even directory is a file. This means that I should be able to open directory as a file? I've tried it using stdio functions and it didn't work. Now, I'm trying it with UNIX system functions. Of course, I'm not using UNIX, I'm using Ubuntu linux. Here is my code:

#include <syscall.h>
#include <fcntl.h>

int main(int argn, char* argv[]) {
    int fd;
    if (argn!=1) fd=open(argv[1],O_RDONLY,0);
    else fd=open(".",O_RDONLY,0);
    if (fd==-1) return -1;

    char buf[1024];
    int n;
    while ((n=read(fd,buf,1024))>0)
        write(1,buf,n);

    close (fd);
    return 0;
}

即使argn为1(无参数),这也不会写入任何内容,而我正在尝试读取当前目录.有什么想法/解释吗?:)

This writes nothing even when argn is 1 (no parameters) and I'm trying to read current directory. Any ideas/explanations? :)

推荐答案

文件也称为常规文件,以区别于特殊文件.

Files are also called regular files to distinguish them from special files.

目录或不是常规文件.最常见的特殊文件是目录.目录文件的布局由所使用的文件系统定义.

Directory or not a regular file. The most common special file is the directory. The layout of a directory file is defined by the filesystem used.

因此,使用 opendir 打开目录.

这篇关于Linux/Open目录作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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