最近看一个小程序,看到它打开一个目录,同时使用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>
#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
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;
}
结果为:
}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
the length is 35
与直接运行命令 wc -m test.txt的结果一样,都是35字符(节)
如果修改,将文件改成目录,即把filename改成/home/liujie/,则结果如下
the file /home/liujie/ is a directory
not implemented
the file /home/liujie/ is a directory
not implemented
the length is -1
这说明这样读目录是不正确的,在c中参考,如果判断是目录,则使用opendir,readdir,closedir等函数来操作目录。
继续学习