通过open(),read(),write()函数实现简单的拷贝命令mycp
用到的主要的3个函数的原型如下:
- int open(const char *pathname, int flags, .../*mode_t mode*/);
- ssize_t read(int filedes, void *buf, size_t nbytes);
- ssize_t write(int filedes, void *buf, size_t nbytes);
下面实例演示了使用文件读写函数实现一个简单的拷贝命令,该程序首先判断命令行参数是否合法,之后打开两个文件,如果目标文件不存在,则创建,
程序的流程图图下:
mycp.c源程序如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- int main(int argc, char **argv)
- {
- char buf[MAX];
- int in, out;
- int n;
- if(argc != 3)
- exit(1);
- if((in = open(argv[2], O_RDONLY)) == -1){
- perror("fail to open");
- exit(1);
- }
- if((out = open(argv[1], O_WRONLY | O_TRUNC | O_CREAT)) == -1){
- perror("fail to open");
- exit(1);
- }
- while((n = read(in, buf, MAX)) > 0)
- if(write(out, buf, n) != n){
- perror("fail to write");
- exit(1);
- }
- if(n < 0){
- perror("fail to read");
- exit(1);
- }
- printf("copy done\n");
- close(in);
- close(out);
- return 0;
- }
阅读(1535) | 评论(0) | 转发(0) |