//系统 IO 下实现文件复制
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
//打开源文件和目标文件
int fd1 = open(argv[1], O_RDNOLY);
int fd2 = open(argv[2], O_WRNOLY|O_CREAT|O_TRUNC, 0644);
//判断文件是否打开成功
if ((fd1 != -1) && (fd2 == -1))
{
close(fd1);
perror("打开文件失败");
exit(1);
}
if ((fd1 == -1) && (fd2 != -1))
{
close(fd2);
perror("打开文件失败");
exit(1);
}
if ((fd1 == -1) && (fd2 == -1))
{
perror("打开文件失败");
exit(1);
}
//定义缓冲区
char *buf = (char *)calloc(1, 100);
int count = 0;
//文件复制
while (1)
{
count = read(fd1, 100, buf);
if (count == 0)
break;
write(fd2, 100, buf);
}
close(fd1);
close(fd2);
return 0;
}
//标准 IO 下实现文件复制
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
//打开源文件和目标文件
FILE *fp1 = fopen(argv[1], "r");
FILE *fp2 = fopen(argv[2], "w");
//判断文件打开情况
if ((fp1 != NULL) && (fp2 ==NULL))
{
fclose(fp1);
perror("打开文件出错");
exit(1);
}
if ((fp2 != NULL) && (fp1 ==NULL))
{
fclose(fp2);
perror("打开文件出错");
exit(1);
}
if ((fp1 == NULL) && (fp2 ==NULL))
{
perror("打开文件出错");
exit(1);
}
//分配缓冲区
char *buf = (char *)calloc(100);
int count = 0;
while (1) //文件读取
{
long a = ftell(fp1)
count = fread(buf, 50, 2, fp1);
if (count == -1)
{
perror("读取文件失败");
break;
}
else if (count < 2)
{
long b = ftell(fp1);
fwrite(buf, b-a, 1, fp2);
break;
}
else
fwrite(buf, 50, count, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
标准 IO 和系统 IO 下的文件复制
猜你喜欢
转载自blog.csdn.net/qq_41985711/article/details/81389051
今日推荐
周排行