今天学了带缓存的I/O操作,于是写了一个linux中的cp操作的实现
#include <stdio.h> //头文件,stdio.h中存有带缓冲的I/O操作函数
#include <string.h>int main(int argc, char* argv[])
{
if (argc != 3) //当调用的不是文件时不成立
{
printf("usage: ./copy filename1 filename2\n");
}
FILE* file1 = fopen(argv[1], "r+"); //打开第一个文件,并赋予其读与写的权限
if (NULL == file1) //当第一个文件未打开,结束操作
{
perror("open1");
return 1;
}
FILE* file2 = fopen(argv[2], "w+"); //打开第二个文件,并赋予其读与写的权限,当文件不存在时,创建文件
if (NULL == file2) //当文件未打开时,结束操作并关闭第一个文件
{
perror("open2");
fclose(file1);
return 2;}
char buf[1024] = {0}; //创建一个有1024个元素的char型数组
int cont = 0;
while(cont = fread(buf, sizeof(char), 1024, file1)) //当读到的数不为0时,循环,这里并且将循环次数计入cont中
{
if (cont == 0) //当读操作失败,关闭两个文件并结束操作
{
perror("fread");
fclose(file1);
fclose(file2);
return 3;
}
int cont2 = fwrite(buf, sizeof(char), cont, file2); //将计入buf中的数据转入第二个文件中
if (0 == cont2) //当写操作失败,关闭两个文件并结束操作
{
perror("fwrite");
fclose(file1);
fclose(file2);
return 4;
}
memset(buf, 0, 1024); //将buf中的内容清空
}
fclose(file1); //关闭两个文件
fclose(file2);
return 0;
}
这里需要注意库函数的调用,并且一定要进行循环,否则文件大小最多只能有1024个字节。
1367

被折叠的 条评论
为什么被折叠?



