linux cp命令源码
2013-12-17 10:07
751 查看
本文转载自 http://www.csc.villanova.edu/~mdamian/C/stdc-file-copy.c
/* * stdc-file-copy.c - copy one file to a new location, possibly under a * different name. */ #include <stdio.h> /* standard input/output routines. */ #define MAX_LINE_LEN 1000 /* maximal line length supported. */ /* * function: main. copy the given source file to the given target file. * input: path to source file and path to target file. * output: target file is being created with identical contents to * source file. */ void main(int argc, char* argv[]) { char* file_path_from; /* path to source file. */ char* file_path_to; /* path to target file. */ FILE* f_from; /* stream of source file. */ FILE* f_to; /* stream of target file. */ char buf[MAX_LINE_LEN+1]; /* input buffer. */ /* read command line arguments */ if (argc != 3 || !argv[1] || !argv[2]) { fprintf(stderr, "Usage: %s <source file path> <target file path>\n", argv[0]); exit(1); } file_path_from = argv[1]; file_path_to = argv[2]; /* open the source and the target files. */ f_from = fopen(file_path_from, "r"); if (!f_from) { fprintf(stderr, "Cannot open source file: "); perror(""); exit(1); } f_to = fopen(file_path_to, "w+"); if (!f_to) { fprintf(stderr, "Cannot open target file: "); perror(""); exit(1); } /* copy source file to target file, line by line. */ while (fgets(buf, MAX_LINE_LEN+1, f_from)) { if (fputs(buf, f_to) == EOF) { /* error writing data */ fprintf(stderr, "Error writing to target file: "); perror(""); exit(1); } } if (!feof(f_from)) { /* fgets failed _not_ due to encountering EOF */ fprintf(stderr, "Error reading from source file: "); perror(""); exit(1); } /* close source and target file streams. */ if (fclose(f_from) == EOF) { fprintf(stderr, "Error when closing source file: "); perror(""); } if (fclose(f_to) == EOF) { fprintf(stderr, "Error when closing target file: "); perror(""); } }
相关文章推荐
- linux命令之cp:略过目录
- linux命令,文件与目录(cp,pwd,mkdir,rmdir;ls,cp,rm,mv,basename,dirname;cat,tac,more,less,head,tail,touch,umask,chattr,file,which,locate,find)
- Linux学习笔记--cp命令(复制)
- 第二弹Linux基础一mkdir/cp/mv/rm/zip/unzip命令详解
- Linux使用cp命令直接覆盖不提示的方法
- linux之cp/scp命令+scp命令详解
- Linux进阶之 cp 命令
- 【每天一个Linux命令】20. Linux中的拷贝命令cp
- 一天一个Linux基础命令之复制文件或目录命令cp
- linux之cp/scp命令+scp命令详解(转)
- Linux 的cp命令
- Linux命令:cp (copy)复制文件或目录
- Linux cp 命令详解
- 每天一个linux命令(8):cp 命令
- 每天一个linux命令(8):cp命令
- linux命令之top源码可编译版
- 每天学习一个linux命令(8):cp 命令
- linux基础命令--chmod/cp(目录/权限)
- linux下cp命令详解
- Linux 实现cp 命令