cp
用来复制文件或目录
下面说一下main函数的参数
int main(int ac , char **av)
也可写成
int main(int ac , char * av[])
第一个int型参数是命令行参数个数,第二个char ** 型参数是个字符指针数组,保存命令行各参数的名字(字符串)
比如对于cp来说 命令行有3个参数
cp file1 file2
则av[1] 存储 fille1这个字符串, av[2] 存储file2这个字符串, ac 等于3。
av[0] 不同环境有所不同:
经测Dev-C++ 中是D:\xx\xx\ cp01.exe
$ ./cp01 cp01.c copy_cp01.c
而我的Linux这样的命令行后av[0] 是 ./cp01
以上两者av[0]都是当前可执行文件名,前者包含了路径。
cp 用到了open函数来打开av[1];read函数读av[1];creat函数创建或清空av[2];write函数写入av[2];
/**
* cp01.c
* uses read and write with tunable buffer size
*/
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#define BUFF_SIZE 4096
#define COPY_MODE 0644
void oops(char * s1, char * s2);
int main(int ac, char **av)
{
int in_fd, out_fd, n_chars;
char buf[BUFF_SIZE];
/* check args */
if( ac != 3) // must three parameters
{
fprintf(stderr, "usage: %s source destination\n", *av);
}
/* open files */
if( (in_fd = open(av[1], O_RDONLY)) == -1)
{
oops("Cannot open ", av[1]);
}
if( (out_fd = creat(av[2], COPY_MODE)) == -1 )
{
oops("Cannot creat ", av[2]);
}
/* copy files */
while( (n_chars = read(in_fd, buf, BUFF_SIZE)) > 0 )
{
if(write(out_fd, buf, n_chars) != n_chars )
{
oops("Write error from ", av[1]);
}
}
if( n_chars == -1 )
{
oops("Read error from ", av[1]);
}
/* close files */
if(close(in_fd) == -1 || close(out_fd) == -1)
{
oops("Error closing files", "");
}
return 0;
}
/**
* abnormal information
*/
void oops(char *s1, char *s2)
{
fprintf(stderr, "Error: %s ", s1);
perror(s2);
exit(1);
}
用cmp比较复制的文件并无不同。
有趣的是
它可以复制它自己。
最后把cp01.c复制到Linux和Windows的共享文件夹。作用之一方便我把Linux里的代码粘贴到博客中来。