소개
이 랩에서는 C++ 언어의 파일 처리를 사용하여 한 파일의 내용을 다른 파일로 복사하는 방법을 배웁니다.
이 랩에서는 C++ 언어의 파일 처리를 사용하여 한 파일의 내용을 다른 파일로 복사하는 방법을 배웁니다.
첫 번째 단계에서는 코드를 진행하기 위해 필요한 헤더 파일과 네임스페이스를 포함합니다.
#include <iostream>
#include <fstream>
using namespace std;
이 단계에서는 다음 작업을 수행합니다.
ifstream 및 ofstream 클래스의 객체를 생성합니다.getline() 메서드를 사용하여 소스 파일의 내용을 읽고, << 연산자를 사용하여 대상 파일에 씁니다 (즉, ifstream 객체에서 ofstream 객체로 각 줄을 복사합니다).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();
}
이 단계에서는 copyFile() 함수를 호출하여 파일 복사 작업을 수행하는 main 함수를 생성합니다.
int main(){
string sourceFile = "original.txt";
string destinationFile = "copy.txt";
copyFile(sourceFile, destinationFile);
return 0;
}
이 단계에서는 코드 파일이 ~/project/main.cpp에 저장되어 있으므로, 현재 디렉토리를 ~/project 로 변경하고 터미널에서 다음 명령을 실행할 수 있습니다.
g++ main.cpp -o main
./main
이렇게 하면 프로그램이 컴파일 및 실행되고 다음과 같은 출력이 생성됩니다.
Copy Finished
#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) 방법을 사용하여 사용자가 한 파일의 내용을 다른 파일로 복사할 수 있는 애플리케이션을 만들었습니다.