文件IO第2天作业

1、用read write实现文件拷贝

//用read write实现文件拷贝
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

//将head.h拷贝到1.txt文件中
int main(int argc, char const *argv[])
{
    int fd1 = open("./head.h", O_RDWR|O_CREAT|O_APPEND, 0775);
    if(fd1 < 0)
    {
        perror("open");
        return -1;
    }
    int fd2 = open("./1.txt", O_RDWR|O_CREAT|O_APPEND, 0775);
    if(fd2 < 0)
    {
        perror("open");
        return -1;
    }

    char c;
    ssize_t res = 0;
    while(1)
    {
        res = read(fd1, &c, sizeof(c));
        if(0 == res)
            break;
        write(fd2, &c, sizeof(c));
    }

    close(fd1);
    close(fd2);
    return 0;
}

2、更新任务:要求将当前路径下,所有文件的权限及最后一次的访问时间提取出来,写入到file.txt中! !

//将当前文件夹的所有文件的权限,以及最后一次访问时间写入文件file.txt中
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include <dirent.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    DIR *dp = opendir("./");
    if(NULL == dp)
    {
        perror("opendir");
        return -1;
    }
    FILE *fp = fopen("./file.txt", "w+");
    if(NULL == fp)
    {
        perror("fopen");
        return -1;
    }
    struct dirent* dir = NULL;
    struct stat buf;
    struct tm *info = NULL;
    int t[4] = {0};
    int i = 0;
    while(1)
    {
        dir = readdir(dp);
        if(NULL == dir)
        {
            break;
        }
        stat(dir->d_name, &buf);
        info = localtime(&buf.st_ctime);
        fprintf(fp, "%-10s\t%o\t", dir->d_name, buf.st_mode & 0777);
        t[0] = info->tm_mon+1;
        t[1] = info->tm_mday;
        t[2] = info->tm_hour;
        t[3] = info->tm_min;
        fprintf(fp, "%d %02d %02d:%02d\n", t[0], t[1], t[2], t[3]);
        
    }

    fclose(fp);
    closedir(dp);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值