[c++] 파일 이름 바꾸기

먼저, 헤더 파일을 포함하고 있는지 확인합니다.

#include <iostream>
#include <fstream>

다음으로, 파일 이름을 변경할 함수를 만듭니다.

void renameFile(const std::string& oldName, const std::string& newName) {
    if (std::rename(oldName.c_str(), newName.c_str()) != 0) {
        std::perror("Error renaming file");
    } else {
        std::cout << "File renamed successfully";
    }
}

위의 함수는 현재 파일 이름과 새 파일 이름을 받아들여서 std::rename 함수를 사용하여 파일 이름을 변경합니다. 오류가 발생하면 perror 함수를 사용하여 오류 메시지를 표시합니다.

이러한 방식으로 파일 이름을 변경할 수 있습니다.

그러나 C++17 이후로는 <filesystem> 라이브러리를 사용하여 파일 이름을 변경하는 것이 더 권장됩니다. 아래는 <filesystem>를 사용한 예시 코드입니다.

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

void renameFile(const std::string& oldName, const std::string& newName) {
    try {
        fs::rename(oldName, newName);
        std::cout << "File renamed successfully";
    } catch (const std::filesystem::filesystem_error& e) {
        std::cerr << "Error renaming file: " << e.what() << '\n';
    }
}

위 코드에서 std::filesystem::rename 함수를 사용하여 파일 이름을 변경합니다. 예외 처리를 통해 오류를 처리합니다.

따라서, C++에서 파일 이름을 변경하는 방법에는 기본 표준 라이브러리를 이용한 방법과 C++17 이후의 <filesystem> 라이브러리를 사용하는 방법 등이 있습니다.

참고 자료:

  1. https://en.cppreference.com/w/cpp/header/filesystem
  2. https://www.modernescpp.com/index.php/c17-filesystem-creation-and-deletion-of-directories-and-files