C++ 파일 입출력 | "파일 읽기/쓰기" 완벽 가이드 [ifstream/ofstream]

C++ 파일 입출력 | "파일 읽기/쓰기" 완벽 가이드 [ifstream/ofstream]

이 글의 핵심

C++ 파일 입출력에 대해 정리한 개발 블로그 글입니다. #include <fstream> #include <iostream> using namespace std;

파일 쓰기 (ofstream)

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

int main() {
    ofstream file("output.txt");
    
    if (!file.is_open()) {
        cout << "파일 열기 실패" << endl;
        return 1;
    }
    
    file << "Hello, World!" << endl;
    file << "C++ 파일 입출력" << endl;
    
    file.close();
    cout << "파일 저장 완료" << endl;
    
    return 0;
}

파일 읽기 (ifstream)

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

int main() {
    ifstream file("input.txt");
    
    if (!file.is_open()) {
        cout << "파일 열기 실패" << endl;
        return 1;
    }
    
    string line;
    while (getline(file, line)) {
        cout << line << endl;
    }
    
    file.close();
    
    return 0;
}

파일 모드

// 쓰기 (덮어쓰기)
ofstream file1("file.txt");

// 추가 모드
ofstream file2("file.txt", ios::app);

// 읽기
ifstream file3("file.txt");

// 읽기+쓰기
fstream file4("file.txt", ios::in | ios::out);

// 바이너리 모드
ofstream file5("file.bin", ios::binary);

실전 예시

예시 1: CSV 파일 읽기

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

struct Student {
    string name;
    int age;
    double score;
};

vector<Student> readCSV(const string& filename) {
    vector<Student> students;
    ifstream file(filename);
    
    if (!file.is_open()) {
        cout << "파일 열기 실패" << endl;
        return students;
    }
    
    string line;
    getline(file, line);  // 헤더 건너뛰기
    
    while (getline(file, line)) {
        stringstream ss(line);
        Student s;
        string token;
        
        getline(ss, s.name, ',');
        getline(ss, token, ',');
        s.age = stoi(token);
        getline(ss, token, ',');
        s.score = stod(token);
        
        students.push_back(s);
    }
    
    file.close();
    return students;
}

int main() {
    vector<Student> students = readCSV("students.csv");
    
    for (const auto& s : students) {
        cout << s.name << ", " << s.age << "살, " 
             << s.score << "점" << endl;
    }
    
    return 0;
}

설명: CSV 파일 파싱은 실무에서 매우 자주 사용됩니다.

예시 2: 로그 파일 작성

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

class Logger {
private:
    ofstream logFile;
    
    string getCurrentTime() {
        time_t now = time(0);
        char buf[80];
        strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", localtime(&now));
        return string(buf);
    }
    
public:
    Logger(const string& filename) {
        logFile.open(filename, ios::app);
    }
    
    ~Logger() {
        if (logFile.is_open()) {
            logFile.close();
        }
    }
    
    void info(const string& message) {
        logFile << "[" << getCurrentTime() << "] [INFO] " 
                << message << endl;
    }
    
    void error(const string& message) {
        logFile << "[" << getCurrentTime() << "] [ERROR] " 
                << message << endl;
    }
};

int main() {
    Logger logger("app.log");
    
    logger.info("프로그램 시작");
    logger.info("데이터 로드 중...");
    logger.error("파일을 찾을 수 없음");
    logger.info("프로그램 종료");
    
    return 0;
}

설명: 로그 파일 작성은 모든 애플리케이션에서 필수입니다.

예시 3: 바이너리 파일 처리

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

struct GameSave {
    int level;
    int score;
    int lives;
    char playerName[50];
};

void saveGame(const string& filename, const GameSave& save) {
    ofstream file(filename, ios::binary);
    file.write(reinterpret_cast<const char*>(&save), sizeof(GameSave));
    file.close();
    cout << "게임 저장 완료" << endl;
}

GameSave loadGame(const string& filename) {
    GameSave save;
    ifstream file(filename, ios::binary);
    
    if (file.is_open()) {
        file.read(reinterpret_cast<char*>(&save), sizeof(GameSave));
        file.close();
        cout << "게임 로드 완료" << endl;
    }
    
    return save;
}

int main() {
    GameSave save;
    save.level = 10;
    save.score = 5000;
    save.lives = 3;
    strcpy(save.playerName, "Player1");
    
    saveGame("save.dat", save);
    
    GameSave loaded = loadGame("save.dat");
    cout << "레벨: " << loaded.level << endl;
    cout << "점수: " << loaded.score << endl;
    cout << "생명: " << loaded.lives << endl;
    cout << "이름: " << loaded.playerName << endl;
    
    return 0;
}

설명: 바이너리 파일로 구조체를 저장하고 불러오는 게임 세이브 시스템입니다.

자주 발생하는 문제

문제 1: 파일 열기 실패 체크 안함

증상: 파일이 없는데 읽기 시도하여 빈 결과

원인: is_open() 체크 누락

해결법:

// ❌ 위험한 코드
ifstream file("nonexistent.txt");
string line;
getline(file, line);  // 실패해도 계속 진행

// ✅ 올바른 코드
ifstream file("nonexistent.txt");
if (!file.is_open()) {
    cerr << "파일 열기 실패" << endl;
    return 1;
}

문제 2: 파일 닫기 누락

증상: 파일 내용이 제대로 저장 안됨

원인: close() 호출 안함 또는 프로그램 비정상 종료

해결법:

// ❌ 문제 가능
ofstream file("output.txt");
file << "data";
// close() 없음

// ✅ 명시적 close
ofstream file("output.txt");
file << "data";
file.close();

// ✅ RAII (자동 close)
{
    ofstream file("output.txt");
    file << "data";
}  // 여기서 자동으로 close

문제 3: 텍스트 vs 바이너리 모드 혼동

증상: 바이너리 데이터가 깨짐

원인: 텍스트 모드에서 바이너리 데이터 처리

해결법:

// ❌ 텍스트 모드로 바이너리 쓰기
ofstream file("data.bin");
int data = 12345;
file.write(reinterpret_cast<char*>(&data), sizeof(data));

// ✅ 바이너리 모드
ofstream file("data.bin", ios::binary);
int data = 12345;
file.write(reinterpret_cast<char*>(&data), sizeof(data));

FAQ

Q1: 파일이 존재하는지 확인하려면?

A: 파일을 열어보고 is_open()으로 확인합니다.

bool fileExists(const string& filename) {
    ifstream file(filename);
    return file.is_open();
}

Q2: 파일 전체를 string으로 읽으려면?

A: stringstream을 사용합니다.

#include <fstream>
#include <sstream>

string readFile(const string& filename) {
    ifstream file(filename);
    stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

Q3: 파일 크기는 어떻게 확인하나요?

A: seekg와 tellg를 사용합니다.

ifstream file("file.txt", ios::binary);
file.seekg(0, ios::end);
size_t size = file.tellg();
file.seekg(0, ios::beg);

Q4: 대용량 파일은 어떻게 처리하나요?

A: 한 줄씩 읽어서 처리합니다.

ifstream file("large.txt");
string line;
while (getline(file, line)) {
    // 한 줄씩 처리
}

Q5: 파일 경로에 한글이 있으면?

A: C++17의 filesystem 또는 wstring을 사용합니다.

#include <filesystem>
namespace fs = std::filesystem;

fs::path p = "한글경로/파일.txt";

Q6: 여러 파일을 동시에 열 수 있나요?

A: 네, 여러 스트림 객체를 만들면 됩니다.

ifstream file1("input1.txt");
ifstream file2("input2.txt");
ofstream output("output.txt");

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ 파일 연산 완벽 가이드 | ifstream·바이너리 I/O·mmap·io_uring·원자적 쓰기까지
  • C++ 파일 입출력 | ifstream·ofstream으로 “파일 열기 실패” 에러 처리까지
  • C++ 연산자 오버로딩 | ”+, -, *, <<” 재정의 가이드

관련 글

  • C++ 시리즈 전체 보기
  • C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
  • C++ ADL |
  • C++ Aggregate Initialization |