编写程序实现简单的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;
}
注:
- 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