C++ 使用 STL 库判断是文件夹还是文件并实现文件复制

该博客介绍了如何使用C++的标准模板库(STL)来判断文件是文件夹还是文件,并提供了实现文件复制的代码示例。通过调用_ioaccess和_stat函数,检查文件权限和文件类型,然后使用ifstream和ofstream对象完成文件的复制操作。
摘要由CSDN通过智能技术生成

C++ 使用 STL 库判断是文件夹还是文件并实现文件复制

C++ 使用 STL 库判断是文件夹还是文件并实现文件复制

#include <iostream>
#include <fstream>
#include <IO.h>

//判断文件是否是一个有效的文件
bool is_valid_file(const char* szFile)
{
    /*
    mode Value          Checks File For
    00                    Existence only
    02                    Write permission
    04                    Read permission
    06                    Read and write permission
    */
    if (0 == _access(szFile, 00))
    {
        struct _stat buf_stat;
        int result = _stat(szFile, &buf_stat);

        if (_S_IFREG & buf_stat.st_mode) {
            printf("file\n");
            return true;
        }
        else if (_S_IFDIR & buf_stat.st_mode) {
            printf("folder\n");
        }
    }
    return false;
}

bool copy_file(const char* szSrcFile, const char* szDstFile, bool bFailIfExists)
{
    if (bFailIfExists && is_valid_file(szDstFile))
    {
        return false;
    }
    std::ifstream in;
    in.open(szSrcFile, std::ios_base::binary);
    if (!in)
    {
        std::cout << "open src file : " << szSrcFile << " failed" << std::endl;
        return false;
    }

    std::ofstream out;
    out.open(szDstFile, std::ios_base::binary | std::ios_base::trunc);
    if (!out)
    {
        std::cout << "create new file : " << szDstFile << " failed" << std::endl;
        in.close();
        return false;
    }

    out << in.rdbuf();

    out.close();
    in.close();
    return true;
}

int main(int argc, char *argv[])
{
    copy_file("E:\\test.dat", "E:\\test2.dat", true);

    std::cout << "hello world." << std::endl;
    return 0;
}

参考:
https://blog.csdn.net/u012750702/article/details/52738859

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值