icon안동민 개발노트

텍스트 파일 읽기


파일 열기

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

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

한 줄씩 읽기

 getline() 함수를 사용하여 파일의 내용을 한 줄씩 읽을 수 있습니다.

std::string line;
while (std::getline(file, line)) {
    std::cout << line << std::endl;
}

단어 단위로 읽기

 공백을 구분자로 사용하여 파일의 내용을 단어 단위로 읽을 수 있습니다.

std::string word;
while (file >> word) {
    std::cout << word << std::endl;
}

문자 단위로 읽기

 get() 함수를 사용하여 파일의 내용을 문자 단위로 읽을 수 있습니다.

char ch;
while (file.get(ch)) {
    std::cout << ch;
}

파일 끝 확인

 eof() 함수를 사용하여 파일의 끝에 도달했는지 확인할 수 있습니다.

while (!file.eof()) {
    std::getline(file, line);
    if (!file.fail()) {
        std::cout << line << std::endl;
    }
}

 주의 : eof()만으로 루프 조건을 확인하는 것은 권장되지 않습니다. 마지막 줄을 두 번 읽을 수 있는 문제가 있습니다.

에러 처리

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

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

파일 포인터 조작

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

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

파일 내용 한 번에 읽기

 전체 파일 내용을 문자열로 읽을 수 있습니다.

#include <sstream>
 
std::ifstream file("example.txt");
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
std::cout << content << std::endl;

CSV 파일 읽기

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

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
 
int main() {
    std::ifstream file("data.csv");
    std::vector<std::vector<std::string>> data;
    std::string line;
 
    while (std::getline(file, line)) {
        std::vector<std::string> row;
        std::stringstream ss(line);
        std::string cell;
 
        while (std::getline(ss, cell, ',')) {
            row.push_back(cell);
        }
 
        data.push_back(row);
    }
 
    // 데이터 출력
    for (const auto& row : data) {
        for (const auto& cell : row) {
            std::cout << cell << "\t";
        }
        std::cout << std::endl;
    }
 
    return 0;
}

연습 문제

  1. 텍스트 파일에서 특정 단어의 출현 빈도를 계산하는 프로그램을 작성하세요.
  2. 주어진 텍스트 파일에서 가장 긴 단어와 가장 짧은 단어를 찾는 프로그램을 작성하세요.
  3. CSV 파일을 읽어 각 열의 평균값을 계산하는 프로그램을 구현하세요.


참고 자료

  • 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)