1.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
DIR *dp=opendir("../opendir");
int count=1;
struct dirent *rp=NULL;
int n;
char buf[30]="";
ssize_t res=0;
struct dirent *abc[10];
while(1)
{
rp=readdir(dp);
if(NULL==rp)
{
if(0==errno)
{
printf("目录读取完毕\n");
break;
}
else
{
perror("opendir");
return -1;
}
}
if(rp->d_name[0]!='.')
{
abc[count-1]=rp;
printf("[%d]%s\n",count++,rp->d_name);
}
}
printf("请输入打印哪个文件的编号:");
scanf("%d",&n);
int fd=open(abc[n-1]->d_name,O_RDONLY);
if(fd<0)
{
perror("open");
return -1;
}
while(1)
{
bzero(buf,sizeof(buf));
res =read(fd,buf,sizeof(buf));
if(0==res)
{
break;
}
write(1,buf,res);
}
close(fd);
closedir(dp);
return 0;
}
运行结果:
2.
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
void get(mode_t mode)
{
char str[]="rwx";
for(int i=0;i<9;i++)
{
if((mode&(0400>>i))==0)
{
putchar('-');
continue;
}
putchar(str[i%3]);
}
putchar(10);
return;
}
int main(int argc, const char *argv[])
{
DIR *dp=opendir("../opendir");
if(NULL==dp)
{
perror("opendir");
return -1;
}
struct dirent *rp=NULL;
while(1)
{
rp=readdir(dp);
if(NULL==rp)
{
if(0==errno)
{
printf("目录文件读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
printf("文件名:%s\n",rp->d_name);
struct stat buf;
int res=stat(rp->d_name,&buf);
if(res<0)
{
perror("stat");
return -1;
}
//打印文件权限
get(buf.st_mode);
//硬连接数
printf("link=%ld\n",buf.st_nlink);
//文件所属用户名 所属组用户名
printf("%d\t%d\n",buf.st_uid,buf.st_gid);
//文件大小
printf("size=%ld\n",buf.st_size);
//时间
printf("time=%ld\n",buf.st_ctime);
printf("-------------\n");
}
closedir(dp);
return 0;
}
运行结果: