[c++] 파일 이동하기

먼저 파일을 복사하고 원본 파일을 삭제하는 방법부터 살펴보겠습니다.

#include <iostream>
#include <fstream>

int main() {
    std::ifstream source("source.txt", std::ios::binary);
    std::ofstream destination("destination.txt", std::ios::binary);
    
    destination << source.rdbuf();

    source.close();
    destination.close();

    std::remove("source.txt");

    return 0;
}

위 코드에서는 source.txt 파일을 읽어와 destination.txt로 복사한 뒤, source.txt 파일을 삭제합니다.

다음으로 파일 시스템의 이동 함수를 사용하는 방법을 알아보겠습니다. C++17부터 <filesystem> 헤더를 사용하여 파일을 이동할 수 있습니다.

#include <iostream>
#include <filesystem>

int main() {
    std::filesystem::path source = "source.txt";
    std::filesystem::path destination = "destination.txt";

    std::filesystem::rename(source, destination);

    return 0;
}

위 코드에서는 std::filesystem::rename 함수를 사용하여 source.txt 파일을 destination.txt로 이동합니다.

파일 이동은 파일 시스템에 직접적인 변경을 일으키므로 주의가 필요합니다. 올바른 권한 및 경로를 지정하여 안전하게 파일을 이동해야 합니다.