要求显示指定路径下的所有文件的属性;
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <dirent.h>
#include <errno.h>
void get_filePermission(mode_t m)
{
char per[]="rwx";
int i;
for(i=0;i<=8;i++)
{
if((m&(0400>>i))==0)
{
putchar('-');
}
else
{
printf("%c",per[i%3]);
}
}
}
void get_fileType(mode_t m)
{
switch(m & S_IFMT)
{
case S_IFSOCK: putchar('s'); break;
case S_IFLNK: putchar('l'); break;
case S_IFREG: putchar('-'); break;
case S_IFBLK: putchar('b'); break;
case S_IFDIR: putchar('d'); break;
case S_IFCHR: putchar('c'); break;
case S_IFIFO: putchar('p'); break;
default: printf("mode错误\n");
}
}
void time_file(time_t n)
{
struct tm* info=NULL;
info=localtime(&n);
if(NULL==info)
{
printf("localtime");
}
printf("%d-%02d-%02d %02d:%02d:%02d",info->tm_year+1900,info->tm_mon+1,info->tm_mday,info->tm_hour,info->tm_min,info->tm_sec);
}
int main(int argc, const char *argv[])
{
DIR* dp=opendir(argv[1]);
if(NULL==dp)
{
perror("opendir");
return -1;
}
struct dirent* rp=NULL;
while(1)
{
rp=readdir(dp);
if(NULL==rp)
{
if(0==errno)
{
break;
}
else
{
perror("readdir");
return -1;
}
}
if('.'!=rp->d_name[0])
{
struct stat buf;
if(stat(argv[1],&buf)<0)
{
perror("stat");
return -1;
}
// printf("mode:%d:%o\n",buf.st_mode,buf.st_mode);
// printf("uid:%d\n",buf.st_uid);
struct passwd* usr=getpwuid(buf.st_uid);
if(NULL==usr)
{
perror("getpwuid");
return -1;
}
struct group* grp=getgrgid(buf.st_gid);
if(NULL==grp)
{
perror("getgrgid");
return -1;
}
// printf(" %d\n",buf.st_gid);
// printf("time:%ld\n",buf.st_ctime);
get_filePermission(buf.st_mode);
printf(" %ld",buf.st_nlink);
printf(" %s ",usr->pw_name);
printf(" %s",grp->gr_name);
printf(" %ld ",buf.st_size);
time_file(buf.st_ctime);
printf(" %s\n",rp->d_name);
}
}
if(closedir(dp)<0)
{
perror("closedir");
return -1;
}
return 0;
}
结果:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
void cpy(int size,int fp,int fp1,char* buf)
{
ssize_t res=0;
while(1)
{
bzero(buf,sizeof(buf));
res=read(fp,buf,sizeof(buf));
if(res==0)
{
printf("读取完毕\n");
break;
}
else if(res<0)
{
perror("read");
}
write(fp1,buf,res);
}
}
int main(int argc, const char *argv[])
{
int fp=open(argv[1],O_RDWR);
int fp1=open("13.png",O_RDWR|O_TRUNC|O_CREAT,0664);
//
off_t size=lseek(fp,0,SEEK_END);
printf("%ld\n",size);
//
char buf[32]="";
int i=0;
int j=0;
pid_t pid=fork();
if(pid>0)
{
sleep(1);
lseek(fp,0,SEEK_SET);
lseek(fp1,0,SEEK_SET);
cpy(size/2,fp,fp1,buf);
}
else if(0==pid)
{
lseek(fp,(size/2),SEEK_SET);
lseek(fp1,(size/2),SEEK_SET);
cpy(size/2,fp,fp1,buf);
}
else if(pid<0)
{
perror("fork");
return -1;
}
close(fp1);
close(fp);
return 0;
}
结果: