Unix/Linux编程实践(cp)

平台:FreeBSD 12.1-RELEASE

本节学习目的:

1)cp命令能做什么?

2)cp命令有什么用?

3)如何编写cp命令程序?

上一节我们学过如何使用man命令来查找程序内容,但是有时候查找没有得到我们想要的东西,比如用man read来查找read函数,会出来这些内容:

这时我们可以使用whatis read命令来缩小查找范围:

找到在第2小节中,所以再使用命令man 2 read来查找:

这时候就可以找到关于read函数定义所在的头文件及其他内容,这样我们就可以打开unistd.h头文件来查看详细内容了。同样方法我们也要查看open、creat、write等函数的相关信息,比如参数、参数类型、返回值等,因为自己编写cp程序时需要用到。

动手编写cp命令实现:

cp1.c

 1 /*
 2  * cp1.c -- version 1 of cp - uses read and write with tunable buffer size
 3  * System: FreeBSD 12.1-RELEASE
 4  * Compiler: clangi-8.0.1
 5  * Compile command: clang -Wall -O3 -o cp1 cp1.c
 6  *
 7  * Usage: cp1 src dest
 8  */
 9 
10  #include <stdio.h>
11  #include <unistd.h>
12  #include <fcntl.h>
13  #include <stdlib.h>
14 
15  #define BUFFERSIZE 4096
16  #define COPYMODE 0755 // 0644
17 
18  void oops(char *, char *);
19 
20  int main(int argc, char *argv[])
21  {
22     int in_fd, out_fd, n_chars;
23     char buf[BUFFERSIZE];
24 
25     if (argc != 3) {
26         fprintf(stderr, "Usage: %s source destination.\n", *argv);
27         exit(1);
28     }
29     
30     /* open source file */
31     if ((in_fd = open(argv[1], O_RDONLY)) == -1) {
32         oops("Cannot open", argv[1]);
33     }
34     
35     /* creat destination file */
36     if ((out_fd = creat(argv[2], COPYMODE)) == -1) {
37         oops("Cannot creat", argv[2]);
38     }
39 
40     while ((n_chars = read(in_fd, buf, BUFFERSIZE)) > 0) {
41         if (write(out_fd, buf, n_chars) != n_chars) {
42             oops("Write error to", argv[2]);
43         }
44     }
45     
46     if (n_chars == -1) {
47         oops("Read error from", argv[1]);
48     }
49 
50     if (close(in_fd) == -1 || close(out_fd) == -1) {
51         oops("Error closing files", "");
52     }
53 
54     return 0;
55 }
56 
57 void oops(char *s1, char *s2)
58 {
59     fprintf(stderr, "Error: %s ", s1);
60     perror(s2);
61     exit(2);
62 }

留意上面代码中第16行代码的含义,这里的0755、0644等都是与权限相关的8进制数,可以用man chmod命令来查看它们的意思:

0644代表的是对任何人可读,但只对所有者可写;而0755的意思是对所有人可读、可执行,但只对所有者可写。所以一般文件拷贝可以使用0644 mode,对于可执行文件可使用0755 mode可以用这两种模式来拷贝文件,然后再查看它们的区别?用ls -l等命令来查看这两种模式下所拷贝的文件权限有何不同

总结:

在本机搜索函数定义,程序等,可以使用man、whatis、apropos等命令交叉使用,以达到自己想要的目的,找到自己想要的东西。

猜你喜欢

转载自www.cnblogs.com/mocuishle/p/12348153.html
今日推荐