6.11 文件io作业

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;
}
                                     

实现

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值