1.读取文件夹
#include <dirent.h>
#include <errno.h>
#include<unistd.h>
#include<time.h>
int main(int argc, const char *argv[])
{
FILE*aa=fopen("./1.txt","w");
if(aa==NULL){
perror("fopen");
return -1;
}
DIR*bp=opendir("./");
if(bp==NULL){
perror("errno");
return -1;
}
printf("打开成功\n");
struct dirent* rp;
struct stat a;
struct tm*t;
while(1){
rp=readdir(bp);
if(rp==NULL){
if(0==rp){
printf("目录读取完毕|\n");
break;
}
else{
perror("readdir");
return -1;
}
}
if(rp->d_name[0]=='.'){//*(rp->d_name)!='.'
continue;
}
if(stat(rp->d_name,&a)<0)
{
perror("stat");
return -1;
}
fprintf(aa,"%o\t",a.st_mode & 0777);
t=localtime(&a.st_ctime);
fprintf(aa,"%04d-%02d-%02d-%02d %02d:%02d:%02d\t",t->tm_year+1900,
t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
fprintf(aa,"%s\n",rp->d_name);
}
fclose(aa);
if(closedir(bp)<0){
perror("closedir");
return -1;
}
return 0;
}
实现
2.复制图片
#include<stdio.h>
#include<errno.h>
#include<sys/types.h>
#include<unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<sys/wait.h>
int main(int argc, const char *argv[])
{
int fp1=open("./saber.png",O_RDONLY);
if(fp1<0){
perror("open");
return -1;
}
int fp2=open("./fsaber.png",O_RDWR|O_CREAT|O_TRUNC,0777);
if(fp2<0){
perror("open");
return -1;
}
off_t size=lseek(fp1,0,SEEK_END);
pid_t pid=fork();
if(pid>0){
wait(NULL);
lseek(fp1,0,SEEK_SET);
lseek(fp2,0,SEEK_SET);
char c;
for(int i=0;i<size/2;i++){
read(fp1,&c,1);
write(fp2,&c,1);
}
}
else if(pid==0){
lseek(fp1,size/2,SEEK_SET);
lseek(fp2,size/2,SEEK_SET);
char c;
for(int i=size/2;i<size;i++){
read(fp1,&c,1);
write(fp2,&c,1);
}
}
else{
perror("fork");
return -1;
}
close(fp1);
close(fp2);
return 0;
}
实现