您的位置:首页 > 运维架构 > Linux

《C 程序设计语言》 第八章 fsize 读取文件夹内容例子的讨论

2016-08-30 23:05 274 查看
阅读“C程序设计语言”第八章有一个例子,在UNIX系统中自己实现文件夹内容的读取等各种操作。

其中有一个函数readdir 中 利用了open 和read函数来读取文件夹,可是我在Centos7 上总是到失败。

查看stackoverflow上有类似的讨论
http://stackoverflow.com/questions/21405048/linux-open-directory-as-a-file
作者做了这个实验,open是可以打开文件夹但是不能调用读取read,总是返回-1

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char* argv[]) {
int fd = -1;
if (argc!=1) fd=open(argv[1],O_RDONLY,0);
else fd=open(".",O_RDONLY,0);
if (fd < 0){
perror("file open");
printf("error on open = %d", errno);
return -1;
}
printf("file descriptor is %d\n", fd);

char buf[1024];
int n;
if ((n=read(fd,buf,1024))>0){
write(1,buf,n);
}
else {
printf("n = %d\n", n);
if (n < 0) {
printf("read failure %d\n", errno);
perror("cannot read");
}
}
close (fd);
return 0;
}

运行结果

file descriptor is 3
n = -1
read failure 21
cannot read: Is a directory


最佳解释如下

1down
voteaccepted
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.

So use opendir to open diretory.

文件分为 普通文件 和特殊文件。 而Directory可以是普通文件也可以不是。取决于具体的文件系统。 所以才会定义一套通用的接口 opendir readdir 和closedir

而自己去实现readdir的话设计到具体的文件系统。所以就不深入讨论了。

1down
voteaccepted
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.

So use opendir to open diretory.

一个UNIX系统下的使用opendir readdir closedir的例子

#include<stdio.h>
#include<dirent.h>

int main(int argc,char* agrv[]){
DIR* dp;
struct dirent* dirp;

if(argc!=2){
printf("usage:lsdirectory_name\n");
//不返回的话,程序会执行出错
return 0;
}
if((dp=opendir(agrv[1]))==NULL){
printf("cannotopen%s",agrv[1]);
//不返回的话,程序会执行出错
return 0;
}
while((dirp=readdir(dp))!=NULL){
printf("%s\n",dirp->d_name);
}
closedir(dp);
//c语言以非0为真,所以程序执行成功的话返回1,执行失败返回0
return 1;
}


文件分为 普通文件 和特殊文件。 而Directory可以是普通文件也可以不是。取决于具体的文件系统。 所以才会定义一套通用的接口 opendir readdir 和closedir

而自己去实现readdir的话设计到具体的文件系统。所以就不深入讨论了。

1down
voteaccepted
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.

So use opendir to open diretory.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 LINUX