본문 바로가기

Programming language/C++

[C++] 파일 복사 유틸리티 구현

"파일 복사 유틸리티" 프로그램의 목적은 한 파일(소스 파일)의 내용을 다른 파일(대상 파일)에 복사하는 것입니다. 이 유틸리티는 컴퓨터 프로그래밍 및 일상적인 컴퓨팅 작업에서 다음과 같은 다양한 목적으로 일반적으로 사용됩니다

  • 백업: 중요한 파일의 복사본을 만들어 파일 손상이나 실수로 삭제할 경우 데이터 손실을 방지합니다.
  • 파일 배포: 소프트웨어 설치 관리자, 업데이트 또는 패치 배포 등 배포를 위한 파일 복제.
  • 데이터 마이그레이션: 한 위치에서 다른 위치로 파일을 이동하여 파일 디렉토리를 재구성하거나 저장 장치 간에 데이터를 전송할 때 유용합니다.
  • 파일 동기화: 서로 다른 장치 또는 위치에서 파일을 동기화하여 최신 상태인지 확인합니다.
  • 데이터 복구: 복사본을 만들고 복사본에 대한 복구를 시도하여 손상되거나 손상된 파일에서 데이터를 복구합니다.
  • 아카이빙: 장기 저장을 위해 문서 또는 데이터의 아카이브 복사본을 만듭니다.
  • 파일 공유: 문서, 이미지 또는 멀티미디어 파일 공유 등 다른 사용자와 공유할 파일을 준비합니다.

제공되는 C++ 프로그램에서 사용자는 소스 파일(복사할 파일)과 대상 파일(복사를 생성할 위치)을 지정하고, 이후 파일 복사 작업을 수행하여 대상 위치에 소스 파일의 복제물을 생성하며, 복사 작업의 성공 여부에 대한 피드백을 사용자에게 제공합니다.

 

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    string sourceFileName, destinationFileName;
    
    cout << "File Copy Utility" << endl;
    
    // Input source and destination file names
    cout << "Enter the source file name: ";
    cin >> sourceFileName;
    cout << "Enter the destination file name: ";
    cin >> destinationFileName;
    
    // Open the source file for reading
    ifstream sourceFile(sourceFileName, ios::binary);
    
    if (!sourceFile) {
        cerr << "Error: Unable to open the source file." << endl;
        return 1; // Exit with an error code
    }
    
    // Open the destination file for writing
    ofstream destinationFile(destinationFileName, ios::binary);
    
    if (!destinationFile) {
        cerr << "Error: Unable to open the destination file." << endl;
        sourceFile.close();
        return 1; // Exit with an error code
    }
    
    // Copy the contents from source to destination
    char buffer[1024];
    while (!sourceFile.eof()) {
        sourceFile.read(buffer, sizeof(buffer));
        destinationFile.write(buffer, sourceFile.gcount());
    }
    
    // Close both files
    sourceFile.close();
    destinationFile.close();
    
    cout << "File copy completed successfully." << endl;
    
    return 0; // Exit successfully
}

사용방법
1. C++ 컴파일러를 사용하여 프로그램을 컴파일합니다(예: g++ file_copy.cpp -o file_copy).
2. 프로그램을 실행하면 원본 파일 이름과 대상 파일 이름을 입력하라는 메시지가 나타납니다.
3. 파일 이름을 입력하면 원본 파일의 내용이 대상 파일로 복사됩니다.
4. 작업이 성공하면 "File copy completed successfully"(파일 복사 완료됨)이라고 표시됩니다

 

출력 결과

1. Successful Copy

File Copy Utility
Enter the source file name: source.txt
Enter the destination file name: destination.txt
File copy completed successfully.

이 경우 source.txt의 내용을 destination.txt에 성공적으로 복사하여 "File copy successfully copy successfully"라는 메시지가 표시됩니다

 

2. Error - Source File Not Found

File Copy Utility
Enter the source file name: non_existent_file.txt
Enter the destination file name: destination.txt
Error: Unable to open the source file.

사용자가 지정한 소스 파일(이 경우 non_existent_file.txt)을 찾을 수 없으면 해당 소스 파일을 열 수 없음을 나타내는 오류 메시지가 표시됩니다.

 

3. Error - Destination File Permission Denied

File Copy Utility
Enter the source file name: source.txt
Enter the destination file name: /root/destination.txt
Error: Unable to open the destination file.

사용 권한 문제로 인해 대상 파일을 열 수 없거나 파일 경로가 잘못된 경우(/root/destination.txt인 경우) 프로그램에서 대상 파일을 열 수 없음을 나타내는 오류 메시지가 표시됩니다.