作业:
1.输入任意路径,将该路径下所有文件的详细信息显示出来,类似ls -l。
2.拷贝一张图片,父进程拷贝前半部分,子进程拷贝后半部分。
1.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <grp.h>
#include <pwd.h>
void get_filepermssion(mode_t m)
{
int t=0400;
for(int i=9;i>=1;i--)
{
if(i%3==0)
{
if(m&t)
putchar('r');
else
putchar('-');
}
if(i%3==2)
{
if(m&t)
putchar('w');
else
putchar('-');
}
if(i%3==1)
{
if(m&t)
putchar('x');
else
putchar('-');
}
t=t>>1;
}
}
char mode(mode_t mode)
{
if(S_ISREG(mode))
{
return '-';
}
else if(S_ISDIR(mode))
{
return 'd';
}
else if(S_ISCHR(mode))
{
return 'c';
}
else if(S_ISBLK(mode))
{
return 'b';
}
else if(S_ISFIFO(mode))
{
return 'p';
}
else if(S_ISLNK(mode))
{
return 'l';
}
else if(S_ISSOCK(mode))
{
return 's';
}
}
int main(int argc, const char *argv[])
{
if(argc<2)
{
printf("输入路径\n");
return -1;
}
//打开
DIR* dp=opendir(argv[1]);
if(NULL == dp)
{
perror("opendir");
return -1;
}
int count=0;
struct dirent* readptr =NULL;
while(1)
{
readptr=readdir(dp);
if(NULL==readptr)
{
if(0==errno)
{
break;
}
else
{
perror("readdir");
return -1;
}
}
char f[30]="";
strcpy(f,argv[1]);
if(readptr->d_name[0]!='.')
{
struct stat buf;
if(stat(strcat(f,readptr->d_name),&buf)<0)
{
perror("stat");
return -1;
}
//文件类型及文件权限
char c=mode(buf.st_mode);
printf("%c",c);
get_filepermssion(buf.st_mode);
//文件的硬链接数,文件创建后默认为1,为0时会删除
printf(" %3ld ",buf.st_nlink);
//文件所属用户
struct passwd *pwd=getpwuid(buf.st_uid);
if(NULL==pwd)
{
perror("getpwuid");
return -1;
}
printf(" %s ",pwd->pw_name);
struct group* grp=getgrgid(buf.st_gid);
if(NULL==grp)
{
perror("getgrgid");
return -1;
}
printf(" %s ",grp->gr_name);
printf("%8ld",buf.st_size);
struct tm *info = NULL;
info = localtime(&buf.st_ctime);
fprintf(stdout, "%2d月 %02d %02d:%02d",info->tm_mon + 1, info->tm_mday,info->tm_hour, info->tm_min);
fflush(stdout);
printf(" %s\n",readptr->d_name);
}}
//关闭
if(closedir(dp)<0)
{
perror("closedir");
return -1;
}
return 0;
}
2.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
int main(int argc,const char * argv[])
{
off_t offset=lseek(fd,0,SEEK_END);
int fd,fd1;
//打开文件
if( -1 == (fd = open("./01.png",O_RDWR))){
perror("open");
printf("%d\n",__LINE__);
return -1;
}
//打开文件1
if( -1 == (fd1 = open("./02.png",O_WRONLY|O_CREAT|O_TRUNC,0666))){
perror("open");
printf("%d\n",__LINE__);
return -1;
}
//创建子进程
pid_t chid = fork();
char buf = '0';
ssize_t res = 0;
if(0 == chid){//子进程偏移
lseek(fd,offset/2,SEEK_SET);
lseek(fd1,offset/2,SEEK_SET);
//
while (0 != (res = (read(fd,&buf,sizeof(buf)))) )
{
write(fd1,&buf,res);
memset(&buf,0,sizeof(buf));
}
}else if(chid > 0){//父进程执行
sleep(20);
lseek(fd,0,SEEK_SET);
lseek(fd1,0,SEEK_SET);
while(lseek(fd,0,SEEK_CUR) != offset/2){
memset(&buf,0,sizeof(buf));
res = (read(fd,&buf,sizeof(buf)));
write(fd1,&buf,res);
}
}
close(fd);
close(fd1);
return 0;
}