您的位置:首页 > 其它

文件读写,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


可打开文件查看对比,这两个文件一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: