如何使用C ++复制一些具有不同扩展名的文件

当前,我只能基于扩展名.jpg复制和粘贴一个文件。但是,出于安全考虑,我需要确保复制并粘贴.jpeg,.JPG和.JPEG。

这是我的代码,以粘贴一个扩展名为.jpg的文件:

cfileStatus status;
CString strFileName = _T("Test2.jpg");
CString strFilePath = m_strImagePath + _T("\\") + strFileName;                      
CString strCopypath = m_strCopypath + _T("\\") + strFileName;
if(cfile::GetStatus(strFilePath,status))
{
    CopyFile(strFilePath,strCopypath,FALSE);
}

因此,如果以示例为例,我要从中复制的文件夹如下所示:

如何使用C ++复制一些具有不同扩展名的文件

无论文件的名称是什么,只要文件具有这四个扩展名(。jpg,.jpeg,.JPG,.JPEG),都应将其复制并粘贴。

那么,如何指定4个不同的扩展名?是否要使用正则表达式或添加其他符号?预先谢谢你!

slxxfl0000 回答:如何使用C ++复制一些具有不同扩展名的文件

以下是有关如何在文件夹中查找具有特殊扩展名的文件的演示:

#include"pch.h"
#include<iostream>
#include<io.h>
#include<vector>
#include<string>
#include <Windows.h>

int get_files(std::string fileFolderPath,std::string fileExtension,std::vector<std::string>& file)
{
    std::string fileFolder = fileFolderPath + "\\*" + fileExtension;
    std::string fileName;
    struct _finddata_t fileInfo;
    long long findResult = _findfirst(fileFolder.c_str(),&fileInfo);
    if (findResult == -1)
    {
        _findclose(findResult);
        return 0;
    }
    bool flag = 0;



    do
    {
        fileName = fileFolderPath + "\\" + fileInfo.name;
        if (fileInfo.attrib == _A_ARCH)
        {
            file.push_back(fileName);
        }
    } while (_findnext(findResult,&fileInfo) == 0);



    _findclose(findResult);
}



int main()
{
    //Folder Path
    std::string fileFolderPath = "D:";




    std::cout << "Output all files in jpeg/JPEG format in the current directory" << std::endl;
    std::vector<std::string> jpeg_files;
    std::string fileExtension_jpeg = ".jpeg";
    get_files(fileFolderPath,fileExtension_jpeg,jpeg_files);



    for (int i = 0; i < jpeg_files.size(); i++)
    {
        std::cout << jpeg_files[i] << std::endl;
    }



    std::cout << "\nOutput all files in jpg/JPG format in the current directory" << std::endl;
    std::vector<std::string> jpg_files;
    std::string fileExtension_jpg = ".jpg";
    get_files(fileFolderPath,fileExtension_jpg,jpg_files);



    for (int i = 0; i < jpg_files.size(); i++)
    {
        std::cout << jpg_files[i] << std::endl;
    }
return 0;
}

您可以获取过滤后的文件路径和文件名。然后,您可以尝试使用CopyFile  复制文件。

本文链接:https://www.f2er.com/3162116.html

大家都在问