linux实现复制文件的两种方法

分享在linux系统下拷贝文件的两种方法:

1

使用系统调用的read和write实现文件拷贝:

#include 
#include 
#include 
#include 
#include 
#include  
#define N 32
 
int main(int argc, const char *argv[])
{
	clock_t start, end;
	double cpu_time_used;
	start = clock();

	int fd_r = open(argv[1], O_RDONLY);
	if(fd_r == -1)
	{
		printf("open error\n");
		return -1;
	}
 
	int fd_w = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0664);
	if(fd_w == -1)
	{
		printf("open error\n");
		return -1;
	}
 
	char buf[N];
	int ret = 0;
 
	while((ret = read(fd_r, buf, N)) > 0)
	{
		write(fd_w, buf, ret);
	}
	printf("copy ok\n");
 
	close(fd_r);
	close(fd_w);

 	end = clock();
 	cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
	
        printf("运行时间:%d s",cpu_time_used);
	return 0;
}

测试:

 

2

使用fputc和fgetc等库函数实现文件拷贝:

//使用fgetc、fputc完成文件的拷贝操作
#include 
#include 

int main(int argc, const char *argv[])
{
        clock_t start, end;
        double cpu_time_used;
        start = clock();

        if(argc < 3)
        {
            printf("Usage : %s  \n", argv[0]);
                return -1;
        }

        FILE *fp_r = fopen(argv[1], "r");
        if(fp_r == NULL)
        {
                printf("fp_r fopen error\n");
                return -1;
        }

        FILE *fp_w = fopen(argv[2], "w");
        if(fp_w == NULL)
        {
                printf("fp_w fopen error\n");
                return -1;
        }

        int ret = 0;

        while((ret = fgetc(fp_r)) != EOF)
        {
                fputc(ret, fp_w);
        }
        printf("copy ok\n");

        fclose(fp_r);
        fclose(fp_w);

        end = clock();
        cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;

        printf("运行时间:%d s",cpu_time_used);
        return 0;
}

测试:

 

 

最终目录结构:

linux实现复制文件的两种方法_第1张图片

 

你可能感兴趣的:(linux,c++,算法,开发语言)