C++ 파일 내용 복사

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 언어의 파일 처리를 사용하여 한 파일의 내용을 다른 파일로 복사하는 방법을 배웁니다.

헤더 파일 및 네임스페이스 포함

첫 번째 단계에서는 코드를 진행하기 위해 필요한 헤더 파일과 네임스페이스를 포함합니다.

#include <iostream>
#include <fstream>

using namespace std;

파일 복사: 한 파일에서 다른 파일로

이 단계에서는 다음 작업을 수행합니다.

  1. ifstreamofstream 클래스의 객체를 생성합니다.
  2. 해당 파일에 연결되었는지 확인합니다. 연결된 경우 계속 진행하고, 그렇지 않은 경우 파일 이름을 두 번 확인합니다. getline() 메서드를 사용하여 소스 파일의 내용을 읽고, << 연산자를 사용하여 대상 파일에 씁니다 (즉, ifstream 객체에서 ofstream 객체로 각 줄을 복사합니다).
  3. close() 메서드를 사용하여 복사 후 파일을 닫습니다.
void copyFile(string sourceFile, string destinationFile){

    string line;

    // creating ifstream and ofstream objects
    ifstream sourceFileStream(sourceFile);
    ofstream destinationFileStream(destinationFile);

    // Reading from source file and writing to destination file
    if(sourceFileStream.is_open() && destinationFileStream.is_open()){
        while(getline(sourceFileStream, line)){
            destinationFileStream << line << "\n";
        }
        cout<<"Copy Finished"<<endl;
    }
    else{
        printf("Cannot read File");
    }

    //closing file
    sourceFileStream.close();
    destinationFileStream.close();
}

메인 함수 (Main Function) 정의

이 단계에서는 copyFile() 함수를 호출하여 파일 복사 작업을 수행하는 main 함수를 생성합니다.

int main(){

    string sourceFile = "original.txt";
    string destinationFile = "copy.txt";

    copyFile(sourceFile, destinationFile);

    return 0;
}

컴파일 및 실행 (Compile & Run) 방법

이 단계에서는 코드 파일이 ~/project/main.cpp에 저장되어 있으므로, 현재 디렉토리를 ~/project 로 변경하고 터미널에서 다음 명령을 실행할 수 있습니다.

g++ main.cpp -o main
./main

이렇게 하면 프로그램이 컴파일 및 실행되고 다음과 같은 출력이 생성됩니다.

Copy Finished

최종 코드 (Final Code) 확인

#include <iostream>
#include <fstream>

using namespace std;

void copyFile(string sourceFile, string destinationFile){

    string line;

    // creating ifstream and ofstream objects
    ifstream sourceFileStream(sourceFile);
    ofstream destinationFileStream(destinationFile);

    // Reading from source file and writing to destination file
    if(sourceFileStream.is_open() && destinationFileStream.is_open()){
        while(getline(sourceFileStream, line)){
            destinationFileStream << line << "\n";
        }
        cout<<"Copy Finished"<<endl;
    }
    else{
        printf("Cannot read File");
    }

    //closing file
    sourceFileStream.close();
    destinationFileStream.close();
}

int main(){

    string sourceFile = "original.txt";
    string destinationFile = "copy.txt";

    copyFile(sourceFile, destinationFile);

    return 0;
}

요약

이 랩에서는 C++ 언어의 파일 처리 (file handling) 방법을 사용하여 사용자가 한 파일의 내용을 다른 파일로 복사할 수 있는 애플리케이션을 만들었습니다.