如何在C++中更改文本文件的名称

Jai*_*ail 10 c++ file

我想更改txt文件名,但我找不到如何做到这一点.

例如,我要重命名foo.txtboo.txt我的C++程序.

Jer*_*fin 22

#include <stdio.h>(或<cstdio>)和使用rename(或std::rename):

rename("oldname.txt", "newname.txt");
Run Code Online (Sandbox Code Playgroud)

与流行的看法相反,它包含在标准库中,并且可以移动到一定程度 - 当然,字符串的允许内容将随目标系统而变化.


JeJ*_*eJo 7

C++17 的<filesystem>更新!

多年后,我们有了<filesystem>C++ 标准。因此,另一篇帖子和评论中提到的“C++不直接支持文件系统”的投诉不再有效!

或更高版本的编译器,现在我们可以使用std::filesystem::rename并执行以下操作:

#include <filesystem>  // std::filesystem::rename
#include <string_view> // std::string_view
using namespace std::literals;

int main()
{
    const std::filesystem::path path{ "D:/...complete directory" };
    std::filesystem::rename(path / "foo.txt"sv, path / "bar.txt"sv);
}
Run Code Online (Sandbox Code Playgroud)

如果我们需要在某些条件下或针对特定扩展名重命名目录中的一组文件该怎么办?那么,让我们将逻辑包装到一个类中。

#include <filesystem>  // std::filesystem::rename
#include <regex>       // std::regex_replace
#include <iostream>
#include <string>
using namespace std::string_literals;
namespace fs = std::filesystem;

class FileRenamer /* final */
{
private:
    const fs::path mPath;
    const fs::path mExtension;

private:
    template<typename LogicFunc>
    bool renameImpli(const LogicFunc& func, const fs::path& extension = {}) noexcept
    {
        bool result = true;
        const fs::path extToCheck = extension.empty() ? this->mExtension : extension;

        // iterate through all the files in the given directory
        for (const auto& dirEntry : fs::directory_iterator(mPath))
        {
            if (fs::is_regular_file(dirEntry)  && dirEntry.path().extension() == extToCheck)
            {
                const std::string currentFileName = dirEntry.path().filename().string();
                const std::string newFileName = std::invoke(func, currentFileName);
                try
                {
                    fs::rename(mPath / currentFileName, mPath / newFileName);
                }
                catch (fs::filesystem_error& error) // if the renaming was unsuccessful
                {
                    std::cout << error.code() << "\n" << error.what() << "\n";
                    result = false; // at least one of the renaming was unsuccessful!
                }
            }
        }
        return result;
    }

public:
    explicit FileRenamer(fs::path path, fs::path extension = { ".txt" }) noexcept
        : mPath{ std::move(path) }
        , mExtension{ std::move(extension) }
    {}
    // other constructors as per!

    bool findAndReplace(const std::string& findWhat, const std::string& replaceWith, const fs::path& extension = {})
    {
        const auto logic = [&](const std::string& currentFileName) noexcept {
            return std::regex_replace(currentFileName, std::regex{ findWhat }, replaceWith);
        };
        return renameImpli(logic, extension);
    }

    bool renameAll(const std::string& fileName, fs::path extension = {})
    {
        auto index{ 1u };
        const auto logic = [&](const std::string&) noexcept { 
            return std::to_string(index++) + " - "s + fileName + extension.string(); 
        };
        return renameImpli(logic, extension);
    }
};

int main()
{
    FileRenamer fileRenamer{  "D:/"}; // ...complete directory

    /*! Rename the files in the given directory with specific extension (.txt by default)
     * in such a way that, filename contained the passed string (i.e. here "foo") will be
     * replaced to what mentioned (i.e. here "bar").
     * Ex:    foo.txt           -->  bar.txt
     *        pre_foo_post.txt  -->  File of bar.txt
     *        File of foo.txt   -->  pre_bar_post.txt
     */
    fileRenamer.findAndReplace("foo"s, "bar"s);

    /*! All the files in the given directory with specific extension (.txt by default)
     * will be replaced to specific filename provided, additional with an index.
     * Ex:    foo.txt           -->  1 - foo.txt
     *        pre_foo_post.txt  -->  2 - foo.txt
     *        File of foo.txt   -->  3 - foo.txt
     */
    fileRenamer.renameAll("foo", ".txt");
}
Run Code Online (Sandbox Code Playgroud)