编写程序实现简单的cp功能

编写程序实现简单的cp功能

使用系统函数

  • open
  • read
  • write
  • close

思路

有一个文件 test.txt,复制之后的文件名为 test.cp;
需要主函数传参,参数不够,关闭进程;
打开文件;
需要一个 buf,长度(BUF_SIZE,定义一个宏)随意,每次循环从 test.txt读取BUF_SIZE长度的内容,写入到 test.cp;
打开、读取、写入一旦异常(返回值为 -1),关闭进程;
关闭文件;

mycp.c代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUF_SIZE 1024

int main(int argc, char *argv[]){
    if(argc < 3){
		printf("There are less args.");
		exit(1);
	}
    int fd1, fd2, rr, wr;
    char *buf[1024];
    // read only 
    fd1 = open(argv[1], O_RDONLY);
    if(fd1 == -1){
    	// printf("%s", sterror(errno));
    	perror("open error");
    	exit(1);// close the process
    }
    fd2 = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0664);
    if(fd2 == -1){
    	perror("open error");
    	exit(1);
    }
    while(rr = read(fd1, buf, BUF_SIZE)){
    	if(rr == -1){
    		perror("read error");
    		break;
    	}
    	wr = write(fd2, buf, BUF_SIZE);
        if(wr == -1){
    		perror("write error");
    		break;
    	}
    }
    close(fd1);
    close(fd2);
    return 0;
}

注:

  1. exit在stdlib.h里面包含;

makefile

# get the .c files
src = $(wildcard *.c)
# target that we need
obj = $(patsubst %.c, %, $(src))
# warn
wrning = -wall -g
# target
all:$(obj)
# rules
%:%.c
        gcc $< -o $@
# fake file
.PHONY:clean
# clean
clean:
        -rm -rf $(obj)

调用程序

使用指令
luxurylu@luxurylu-virtual-machine:~/pointer22/0722$ ls	
luxurylu@luxurylu-virtual-machine:~/pointer22/0722$ make
luxurylu@luxurylu-virtual-machine:~/pointer22/0722$ ./mycp test.txt test.cp
luxurylu@luxurylu-virtual-machine:~/pointer22/0722$ cat test.txt 
luxurylu@luxurylu-virtual-machine:~/pointer22/0722$ cat test.cp
运行截图

在这里插入图片描述

2020/07/23 11:02
@luxurylu

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值