文件信息
stat.c
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include "05_statfun.h"
#include<time.h>
#include<fcntl.h>
#include <string.h>
#include <errno.h>
#include <dirent.h>
int main(int argc, const char *argv[])
{
DIR *fd=opendir("./");
if(NULL==fd)
{
perror("opendir");
return -1;
}
//读目录
while(1)
{
struct dirent *rp=readdir(fd);
if(NULL==rp)
{
if(errno!=0)
{
perror("readdir");
return -1;
}
else
{
break;
}
}
struct stat buf;
if(stat(rp->d_name, &buf) < 0)
{
perror("stat");
return -1;
}
char per[10]="";
char type=0;
//文件的类型以及权限
type=get_fileType(buf.st_mode);
printf("%c",type);
get_filePermission(buf.st_mode);
//文件的硬链接数
printf(" %ld",buf.st_nlink);
//文件所属用户
get_filepasswd(buf.st_uid);
//文件所属组用户
get_filegroup(buf.st_gid);
//文件的大小
printf(" %ld",buf.st_size);
//文件的时间
struct tm *t=NULL;
t=localtime(&buf.st_ctime);
printf(" %d %d %02d:%02d",t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min);
//文件名
printf(" %s\n",rp->d_name);
}
return 0;
}
statfun.c
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include"05_statfun.h"
#include <time.h>
#include<fcntl.h>
//获取文件权限
void get_filePermission(mode_t mode)
{
int a=0400;
char str[3]={'r','w','x'};
for(int i=0;i<9;i++)
{
if(mode&a)
{
putchar(str[(i)%3]);
}else
{
printf("-");
}
a=a>>1;
}
}
//获取文件类型
char get_fileType(mode_t mode)
{
char c = 0;
switch(mode&S_IFMT)
{
case S_IFSOCK: c = 's'; break;
case S_IFLNK: c = 'l'; break;
case S_IFREG: c = '-'; break;
case S_IFDIR: c = 'd'; break;
case S_IFIFO: c = 'p'; break;
case S_IFCHR: c = 'c'; break;
case S_IFBLK: c = 'b'; break;
}
return c;
}
//获取文件所属用户
void get_filepasswd(mode_t uid)
{
struct passwd* pwd = getpwuid(uid);
if(NULL == pwd)
{
perror("getpwuid");
return ;
}
printf(" %s", pwd->pw_name);
}
//获取文件所属组用户
void get_filegroup(mode_t gid)
{
struct group* grp = getgrgid(gid);
if(NULL == grp)
{
perror("getgrgid");
return ;
}
printf(" %s", grp->gr_name);
}
statfun.h
#ifndef __STATFUNC_H__
#define __STATFUNC_H__
#include<fcntl.h> //只有调用fcntl.h才能用mode_t
//获取文件权限
void get_filePermission(mode_t mode);
//获取文件类型
char get_fileType(mode_t mode);
//获取文件所属用户
void get_filepasswd(mode_t uid);
//获取文件所属组用户
void get_filegroup(mode_t gid);
#endif
结果
***************************************************************
2.
利用父子进程拷贝一张图片
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
int fr = open(argv[1],O_RDONLY);
int fw = open("cpy.png",O_RDWR|O_CREAT|O_TRUNC,0664);
long fsize = lseek(fr,0,SEEK_END);
lseek(fr,fsize/2,SEEK_SET);
lseek(fw,fsize/2,SEEK_SET);
int i=0;
char c;
pid_t cpid = fork();
if(cpid){
while(lseek(fr,0,SEEK_CUR));
lseek(fw,0,SEEK_SET);
while(i<fsize/2){
read(fr,&c,1);
write(fw,&c,1);
i++;
}
}else{
while(read(fr,&c,1)){
write(fw,&c,1);
}
lseek(fr,0,SEEK_SET);
}
close(fr);
close(fw);
return 0;
}
结果