1:拷贝图片
#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 fp = open("./photo.jpg",O_RDONLY);
if(fp<0)
{
perror("open");
return -1;
}
printf("文件打开成功!\n");
int fp1 = open("photo1.jpg",O_WRONLY |O_CREAT| O_TRUNC,0665);
if(fp1 < 0 )
{
perror("fp1");
return -1;
}
printf("拷贝文件已创建!\n");
//计算文件大小并返回大小值
off_t size = lseek(fp,0,SEEK_END);
//创建一个子进程
pid_t fk = fork();
if(fk > 0)
{
sleep(1);
//进入父进程
lseek(fp,0,SEEK_SET);
lseek(fp1,0,SEEK_SET);
char n;
for(int i=0;i<size/2;i++)
{
//读一个字节就写一个字节,直到循环到总大小的一半结束!
read(fp,&n,1);
write(fp1,&n,1);
}
printf("前半部分拷贝完成!!!\n");
}else if(fk == 0)
{
lseek(fp,size/2,SEEK_SET);
lseek(fp1,size/2,SEEK_SET);
//进入子进程
char n;
for(int i=0;i<size/2;i++)
{
read(fp,&n,1);
write(fp1,&n,1);
}
printf("后半部分拷贝完成!!!\n");
}
else
{
perror("fork");
return -1;
}
close(fp);
close(fp1);
return 0;
}
结果图:
2:提取最后一次修改文件时间
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <dirent.h>
int main(int argc, const char *argv[])
{
DIR* op = opendir("../day13进程/");
if(op == NULL)
{
perror("opendir");
return NULL;
}
printf("目录打开成功!\n");
struct dirent * rp;
struct stat buf;
char str[100]="";
struct tm* info;
while(1)
{
rp = readdir(op);
if(rp == NULL)
{
if(errno == 0)
{
break;
}
perror("readdir");
return -1;
}
if(rp->d_name[0] != '.')
{
printf("%s\n",rp->d_name);
sprintf(str,"%s","./text",rp->d_name);
if(stat(str,&buf)<0)
{
perror("stat");
return -1;
}
info = localtime(&buf.st_ctime);
fprintf("./text","%o %04D-%02d-%02d-%02d %02d:%02d %s\n",buf.st_mode & 0777 , info->tm_year+1900,info->tm_mon+1,\
info->tm_mday,info->tm_hour,info->tm_min,rp->d_name);
}
}
return 0;
}