1.要求将指定路径下,所有文件(除了隐藏文件)的权限及最后一次的访问时间提取出来,写入到file.txt中
代码
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
int main(int argc, const char *argv[])
{
DIR* dp = opendir("./2_day/");
FILE* fp = fopen("./file.txt","w");
char c;//用来写入换行或者制表符的
struct stat buf;//配合stat函数获取文件的权限和修改时间
struct tm* info;
char datetime_string[20];//装时间
if(dp == NULL)
{
perror("opendir");
return -1;
}
while(1)
{
struct dirent* a1 = readdir(dp);
if(NULL == a1)
{
break;
}
if(a1->d_name[0]!='.')
{
fprintf(fp,"%-20s",a1->d_name);//获取文件名字
c = '\t';
fprintf(fp,"%c",c);//写入制表符,让文件名字和权限有间隔增加可读性
stat(a1->d_name,&buf);//获取文件属性
fprintf(fp,"%o",buf.st_mode&0777);//获取权限
c = '\t';
fprintf(fp,"%c",c);
//获取时间
time_t Time = buf.st_atime;
info = localtime(&Time);// 将秒数转换成本地时间
// 格式化输出年月日 时:分:秒
strftime(datetime_string, sizeof(datetime_string), "%Y-%m-%d %H:%M:%S"\
,info);
fprintf(fp,"%s",datetime_string);
c='\n';
fprintf(fp,"%c",c);//写入换行
}
}
closedir(dp);
fclose(fp);
return 0;
}
运行结果
2.使用文件IO对图片进行拷贝。要求子进程拷贝后半部分,父进程拷贝前半部分。要求拷贝到一个文件中。拷贝完毕后与源文件一致。
代码
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int fp=open("./qq.png",O_RDONLY);
int cfp=open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0770);
off_t size = lseek(fp,0,SEEK_END);//获取文件大小
off_t size_head = size / 2;
off_t size1;
char c;
ssize_t num;
lseek(fp,0,SEEK_SET);//将文件偏移修改到文件头
pid_t pid=fork();//创建子进程
printf("pid=%d\n",pid);
if(pid!=0)
{
while(1)
{
num = read(fp,&c,1);
write(cfp,&c,num);
size1 = lseek(fp,0,SEEK_CUR);
if(size1==size_head)
{
printf("前半部分复制完成\n");
break;
}
}
}
else if(pid == 0)
{
sleep(1);//确保子进程后运行
while(1)
{
num = read(fp,&c,1);
write(cfp,&c,num);
if(num==0)
{
printf("后半部分复制完成\n");
break;
}
}
}
close(cfp);
close(fp);
return 0;
}
运行结果