【Linux】【C++】实现文件夹或文件拷贝(可直接编译运行)

2024年9月29日14:20:05更新

修改 int CopyFile(std::string sourcePath,std::string destPath) 函数,fopen(destPath)失败时,return 1之前,需要使用fclose()方法关闭源路径文件流。


一、 前言

本文是在该文“Linux C++实现拷贝文件夹”的基础上做了一些修改和优化:

  1. 修改了CopyFile(std::string sourcePath,std::string destPath)函数返回值不匹配的问题;
  2. 原文代码只支持拷贝文件夹,增加拷贝文件功能.

二、代码测试环境

编程语言 操作系统 系统架构 控制器
C++ 11 Ubuntu 18.04 LTS arm64 LCFC EA-B310

三、代码实现

copy.cpp

#include<stdlib.h>
#include<dirent.h>
#include<string.h>
#include<stdio.h>
#include<sys/stat.h>
#include<iostream>
 
#define BUFFER_LENGTH 8192

// 判断传入的路径是否是目录(不是目录就是文件),目录返回1,文件返回0
int IsDir(std::string path)
{
   
   
	if(path.empty())
	{
   
   
		return 0;
	}
	struct stat st;
	if(0 != stat(path.c_str(),&st))
	{
   
   
		return 0;
	}
	if(S_ISDIR(st.st_mode))
	{
   
   
		return 1;
	}
	else
	{
   
   
		return 0;
	}
}

void AddSlash(std::string &sourcePath,std::string &destPath)
{
   
   
	if((IsDir(sourcePath)) && (sourcePath.back() != '/'))
	<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

油炸自行车

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值