文件读写,cp命令的实现
2015-05-12 18:10
120 查看
用fwite和fread实现文件的复制,闲话少说直接上代码.
#include <stdio.h> /*本程序并未做输入的出错处理,例如,文件路径的正确性以及目标文件是否已经存在等*/ int main(int argc, char *argv[]) { FILE * fp1 = NULL; FILE * fp2 = NULL; char buf[1024] = {'\0'}; int nbytes = 0; if(argc != 3) //检查参数的个数 { printf("wrong command\n"); return -1; } if((fp1 = fopen(argv[1], "rb")) == NULL) //打开源文件 { printf("file1 is failed to open\n"); return -1; } if((fp2 = fopen(argv[2], "wb")) == NULL) //打开目标文件 { printf("file2 is failed to open\n"); return -1; } /*开始复制文件,文件可能很大,缓冲一次装不下,使用一个循环进行读写*/ while((nbytes = fread(buf, sizeof(char), 1024, fp1)) > 0) /*读取源文件,直到将文件内容全部读完*/ { if(fwrite(buf, sizeof(char), nbytes, fp2) == -1) /*将读出的内容全部写到目标文件中去*/ { perror("fail to write\n"); return -1; } } if(nbytes == -1) //如果因为读入字节小于0而跳出循环,则说明出错了 { perror("fail to read"); return -1; } fclose(fp1); fclose(fp2); return 0; }
编译程序使其生成可执行文件:
gcc cp.c -o cp -Wall
运行可执行文件:
./cp file1.txt file2.txt
可打开文件查看对比,这两个文件一致。
相关文章推荐
- shell 中cp命令的简单实现(未考虑复制后文件的权限)
- C语言拷贝文件函数实现(linux cp [source file] [target file] 命令的实现)
- 文件复制命令CP 的简单实现
- 【Linux】文件读写及cat命令的实现
- 用Linux_C语言模拟CP命令,实现文件和文件夹的拷贝
- Linux文件复制cp命令的实现
- 系统调用的文件编程实现cp命令
- Java代码实现对properties文件有序的读写
- java用 pscp 命令方式上传文件,实现自动化部署的一环。
- INF 驱动文件实现命令方式进行安装。。。
- 通过流实现文件读写的方法(上)
- 通过流实现文件读写的方法(中)
- 通过流实现文件读写的方法(下)
- Python遍历文件夹和读写文件的实现方法
- 文件的复制,移动和删除命令(cp,mv,rm)
- C Plus Plus 实现文件读写
- Linux系统使用--定时关机的实现以及crontab命令和文件详解
- C/C++实现bmp文件读写
- C++文件流(ifstream,ofstream,fstream),实现文件读写
- linux使用rz和sz命令,实现小文件上传下载