该程序运行时有两个参数,分别为源文件和目标文件,程序能够显示打开、读取、写入、关闭文件操作时的错误。
假定编译后的程序名为mycopy,使用方法如下:
./mycopy src.txt dest.txt
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024 //每次读写缓存大小,影响运行效率
int main(int argc, char *argv[])
{
int src_fd, dest_fd;
unsigned char buff[BUFFER_SIZE];
int real_read_size;
if(argc!=3) //命令要跟两个参数
{
printf("usage: ./mycopy <src file> <dest file>\n");
exit(EXIT_FAILURE);
}
src_fd = open(argv[1], O_RDONLY); //只读打开第1个参数代表的源文件
if(src_fd==-1)
{
perror("open src file error: ");
exit(EXIT_FAILURE);
}
dest_fd = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0777); //读写打开第2个参数代表的目标文件
if(dest_fd==-1)
{
perror("open dest file error: ");
exit(EXIT_FAILURE);
}
while( (real_read_size=read(src_fd, buff, BUFFER_SIZE))>0 )
{
write(dest_fd, buff, real_read_size);
}
close(src_fd);
close(dest_fd);
printf("copy %s to %s successfully.\n", argv[1], argv[2]);
exit(EXIT_SUCCESS);
}