Linux 指令cp的实现

主要函数

  • int open(const char *pathname, int flags, mode_t mode);/ int open(const char *pathname, int flags);
  • ssize_t read(int fd, void *buf, size_t count);
  • ssize_t write(int fd, const void *buf, size_t count);
  • off_t lseek(int fd, off_t offset, int whence);

概述

使用LinuxC库中函数对文件进行操作。首先打开被复制文件读取其中的内容,再创建目标文件将复制在内存buf中的文件内容写入,最后关闭两个文件。其中包括参数个数判断,文件存在判断。巧妙使用lseek函数返回值来计算被复制文件的大小,避免了不必要的空间使用。

代码

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "stdio.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv){
        int fid = 0;    //descriptor of original file
        int f2id = 0;   //descriptor of target file
        int filesize = 0;

        /*check the num of main parameters*/
        if(argc > 3){
                printf("too much arguments after %s\n",argv[2]);
                exit(-1);
        }
        else if(argc <3){
                printf("missing argument!\n");
                exit(-1);
        }
        /*determing if the file exist*/
        fid = open(*(argv+1),O_RDWR, 0600);
        if(fid < 0 ){
                printf("no such file: %s\n",argv[1]);
                exit (-1);
        }

        filesize = lseek(fid, 0, SEEK_END);         //calculate the file size 
        char *buf = (char *)malloc(sizeof(char)*filesize);  //allocate space according to the file size
        lseek(fid, 0, SEEK_SET);            //NOTE: pointer back to the beginning of the file in order to read the content
        read(fid, buf, filesize);
        /*write the content to target file*/
        if(open(argv[2],O_RDWR) > 0){       //NOTE: process content when condition is non-zero, and the return value is -1 as file not exist
                printf("file %s exist!\n",argv[2]);
                exit(-1);
        }else{
                f2id = open(argv[2], O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600);
                write(f2id,buf,filesize);

                printf("done!\n");
        }
        close(fid);
        close(f2id);

        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值