您的位置:首页 > 运维架构 > Linux

linux系统编程:cp的另外一种实现方式

2018-01-10 17:20 344 查看
之前,这篇文章:linux系统编程:自己动手写一个cp命令 已经实现过一个版本。

这里再来一个版本,涉及知识点:

linux系统编程:open常用参数详解

Linux系统编程:简单文件IO操作

/*================================================================
*   Copyright (C) 2018 . All rights reserved.
*
*   文件名称:cp.c
*   创 建 者:ghostwu(吴华)
*   创建日期:2018年01月10日
*   描    述:用open和write实现cp命令
*
================================================================*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#ifndef BUFSIZE
#define BUFSIZE 1024
#endif

int main(int argc, char *argv[])
{
int input_fd, output_fd, openflags;
mode_t fileperms;
ssize_t num;

openflags = O_WRONLY | O_CREAT | O_TRUNC;
fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH;

if( argc != 3 || strcmp( argv[1], "--help" ) == 0 ) {
printf( "usage:%s old-file new-file\n", argv[0] );
exit( -1 );
}

//打开源文件
input_fd = open( argv[1], O_RDONLY );
if( input_fd < 0 ) {
printf( "源文件%s打开失败\n", argv[1] );
exit( -1 );
}

//创建目标文件
output_fd = open( argv[2], openflags, fileperms );
if( output_fd < 0 ) {
printf( "目标文件%s创建失败\n", argv[2] );
exit( -1 );
}

char buf[BUFSIZE];

//开始读取源文件的数据,向目标文件拷贝数据
while( ( num = read( input_fd, buf, BUFSIZE ) ) > 0 ) {
if( write( output_fd, buf, num ) != num ) {
printf( "向目标文件%s写入数据失败\n", argv[2] );
exit( -1 );
}
}

if( num < 0 ) {
printf( "读取源文件%s数据失败\n", argv[1] );
exit( -1 );
}

if( close( input_fd ) < 0 ) {
perror( "close input_fd" );
exit( -1 );
}
if( close( output_fd ) < 0 ) {
perror( "close output_fd" );
exit( -1 );
}

return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: