icon안동민 개발노트

텍스트 파일 쓰기


파일 열기

 텍스트 파일에 쓰기 위해서는 먼저 파일을 열어야 합니다. C++에서는 ofstream 클래스를 사용하여 파일을 쓰기 모드로 열 수 있습니다.

#include <iostream>
#include <fstream>
 
int main() {
    std::ofstream file("output.txt");
    
    if (!file.is_open()) {
        std::cerr << "파일을 열 수 없습니다." << std::endl;
        return 1;
    }
 
    // 파일 사용...
 
    file.close();
    return 0;
}

기본 쓰기 연산

 << 연산자를 사용하여 파일에 데이터를 쓸 수 있습니다.

file << "Hello, World!" << std::endl;
file << 42 << " " << 3.14 << std::endl;

파일 모드

 파일을 열 때 다양한 모드를 지정할 수 있습니다.

std::ofstream file("output.txt", std::ios::out | std::ios::app);
  • ios::out : 쓰기 모드 (기본)
  • ios::app : 파일 끝에 추가
  • ios::trunc : 파일 내용 삭제 후 쓰기 (기본)
  • ios::binary : 이진 모드

포맷팅

 iomanip 헤더를 사용하여 출력 형식을 지정할 수 있습니다.

#include <iostream>
#include <fstream>
#include <iomanip>
 
int main() {
    std::ofstream file("formatted.txt");
    
    file << std::setw(10) << std::left << "Name";
    file << std::setw(5) << std::right << "Age" << std::endl;
    file << std::setw(10) << std::left << "John";
    file << std::setw(5) << std::right << 25 << std::endl;
    file << std::fixed << std::setprecision(2);
    file << std::setw(10) << std::left << "Balance:";
    file << std::setw(10) << std::right << 1234.56 << std::endl;
 
    file.close();
    return 0;
}

에러 처리

 파일 쓰기 중 발생할 수 있는 에러를 처리해야 합니다.

if (file.fail()) {
    std::cerr << "파일 쓰기 오류" << std::endl;
    file.clear();  // 오류 상태 초기화
}

파일 포인터 조작

 seekp()tellp() 함수를 사용하여 파일 포인터를 조작할 수 있습니다.

file.seekp(0, std::ios::end);  // 파일의 끝으로 이동
std::streampos size = file.tellp();  // 현재 위치(파일 크기) 확인
std::cout << "파일 크기: " << size << " 바이트" << std::endl;

문자열 스트림 활용

 stringstream을 사용하여 복잡한 문자열을 구성한 후 파일에 쓸 수 있습니다.

#include <sstream>
#include <fstream>
 
int main() {
    std::ofstream file("output.txt");
    std::stringstream ss;
    
    std::string name = "Alice";
    int age = 30;
    
    ss << "Name: " << name << ", Age: " << age;
    file << ss.str() << std::endl;
 
    file.close();
    return 0;
}

CSV 파일 쓰기

 쉼표로 구분된 값(CSV) 파일을 작성하는 방법을 알아봅시다.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
 
int main() {
    std::ofstream file("data.csv");
    std::vector<std::vector<std::string>> data = {
        {"Name", "Age", "City"},
        {"John", "25", "New York"},
        {"Alice", "30", "London"},
        {"Bob", "22", "Paris"}
    };
 
    for (const auto& row : data) {
        for (size_t i = 0; i < row.size(); ++i) {
            file << row[i];
            if (i < row.size() - 1) file << ",";
        }
        file << std::endl;
    }
 
    file.close();
    return 0;
}

주의사항

  • 파일을 열고 난 후 반드시 닫아야 합니다.
  • 파일 쓰기 권한을 확인하세요.
  • 동시에 여러 프로세스가 같은 파일에 쓰는 상황을 고려해야 합니다.
  • 대용량 데이터를 다룰 때는 메모리 사용에 주의해야 합니다.
  • 중요한 데이터를 다룰 때는 백업 메커니즘을 고려하세요.

연습 문제

  1. 사용자로부터 입력받은 데이터를 파일에 저장하는 간단한 메모장 프로그램을 작성하세요.
  2. 학생 정보(이름, 나이, 성적)를 입력받아 CSV 형식으로 파일에 저장하는 프로그램을 구현하세요.
  3. 기존 텍스트 파일의 모든 소문자를 대문자로 변환하여 새 파일에 저장하는 프로그램을 작성하세요.


참고 자료

  • C++ 공식 문서의 파일 스트림 섹션 : File streams
  • "C++ Primer" by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo (Chapter 8 : The IO Library)
  • "Effective C++" by Scott Meyers (항목 52 : 파일 쓰기에 대해 자세히 알아보기)
  • C++ Core Guidelines의 파일 I/O 관련 규칙 : I/O rule summary
  • "The C++ Programming Language" by Bjarne Stroustrup (Chapter 38 : I/O Streams)