C++ 文件操作—移动文件

基本问题是,需要把一个文件夹下的所有文件移动到新的文件夹。以原有的C#或者Java都是操作比较简单的。今天在使用C++操作时,折腾了挺久。需要针对不同版本的C++有不同的解决方式。

一、C++17以前

在C++17以前可以使用 fstream 库操作文件,如基本的复制、移动(重命名),但是没有遍历文件夹。这里就结合 Windows API 来实现。

1、遍历文件夹

void MoveFilesFromOneDirectoryToAnother(const std::string& sourceDir, const std::string& destDir) {
    ListFilesInDirectory(sourceDir); // 列出源目录中的所有文件(仅为演示,实际使用时可以注释掉)
    WIN32_FIND_DATA data;
    HANDLE hFind = FindFirstFile((sourceDir + "/*").c_str(), &data);
    if (hFind == INVALID_HANDLE_VALUE) {
        std::cerr << "Path not found: " << sourceDir << std::endl;
        return;
    }
 
    do {
        if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { // 确保是文件而不是目录
            std::string sourcePath = sourceDir + "\\" + data.cFileName;
            std::string destPath = destDir + "\\" + data.cFileName;
            MoveFile(sourcePath, destPath); // 移动文件
        }
    } while (FindNextFile(hFind, &data) != 0);
 
    FindClose(hFind);
}

2、移动文件

#include <fstream>
#include <iostream>
 
void MoveFile(const std::string& source, const std::string& destination) {
    if (std::rename(source.c_str(), destination.c_str()) != 0) {
        std::cerr << "Error moving file: " << source << " to " << destination << std::endl;
    } else {
        std::cout << "File moved successfully: " << source << " to " << destination << std::endl;
    }
}

二、C++17以后

在 C++17 以后,集成了 filesystem 库,可以实现遍历、移动等操作。这样一个类库引用,就可实现,代码如下。

#include <iostream>
#include <filesystem>
#include <string>
 
namespace fs = std::filesystem;
 
void moveFilesToNewDirectory(const fs::path& sourceDir, const fs::path& destDir) {
    // 确保目标目录存在,如果不存在则创建
    if (!fs::exists(destDir)) {
        fs::create_directory(destDir);
    }
 
    try {
        // 遍历源目录下的所有条目
        for (const auto& entry : fs::directory_iterator(sourceDir)) {
            if (fs::is_regular_file(entry.status())) {  // 确保是文件
                // 构建目标路径
                fs::path destPath = destDir / entry.path().filename();
                // 移动文件
                fs::rename(entry.path(), destPath);
                std::cout << "Moved: " << entry.path() << " to " << destPath << std::endl;
            }
        }
    } catch (fs::filesystem_error& e) {
        std::cerr << e.what() << std::endl;
    }
}
 
int main() {
    fs::path sourceDir = "path/to/source";  // 源文件夹路径
    fs::path destDir = "path/to/destination";  // 目标文件夹路径
    moveFilesToNewDirectory(sourceDir, destDir);
    return 0;
}

 

posted @ 2025-03-11 17:16  漠里  阅读(154)  评论(0)    收藏  举报