linux系统编程:cp的另外一种实现方式
2018-01-10 17:20
344 查看
之前,这篇文章:linux系统编程:自己动手写一个cp命令 已经实现过一个版本。
这里再来一个版本,涉及知识点:
linux系统编程:open常用参数详解
Linux系统编程:简单文件IO操作
View Code
这里再来一个版本,涉及知识点:
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
相关文章推荐
- JFrame嵌套背景另外一种实现方式
- 关于CAS服务端登录前ajax访问后台方法被拦截的配置-另外一种实现方式
- SQL 在查询中插入行号--自定义分页的另外一种实现方式
- FMX有两种消息处理的实现方式,一种是用TMessageManager来实现自定义的消息,另外一种象TEdit中的实现,直接声明消息方法(firemonkey messaging)
- SQL 在查询中插入行号--自定义分页的另外一种实现方式
- MasterPage的另外一种实现方式
- iOS中另外一种多线程实现方式NSOperation
- RecyclerView 实现点击的另外一种方式
- SWT中定时器的一种特殊实现方式/SWT中线程互访时display.asyncExec/display.syncExec...程序死掉无响应的解决办法
- Qt绘图的另外一种方式
- 猴子选大王(约瑟夫环另外的实现方式)
- Netty:实现同步发送并接收消息的一种方式
- 数独的一种实现方式
- 远程通信的几种选择(RPC,Webservice, JMS的区别,其实都是SOA的一种实现方式)
- python 元类型编程, 单例模式SingleTon的一种实现方式
- mfc listctrl实现表头与数据的不同对齐方式(换了一种思维方式)
- CXF实现用户验证(相比前面的另外的一种方法完全Spring)
- CQRS架构中同步服务的一种实现方式
- html遮罩层的一种实现方式
- 另外一种DataGrid与Datalist的嵌套--更好的方式[原创]