C++

[C++] 파일 입출력 (.txt 파일)

polibo 2025. 5. 5. 21:46

파일 출력

  • fstream 헤더 파일 사용
  • 파일 열기 : open() 메소드
  • 파일 닫기 : close() 메소드
  • 파일 닫기를 안해주면, 프로그램이 끝날 시 자동으로 닫아줌
#include <iostream>
#include <fstream>

int main()
{
    using namespace std;

    char name[20];
    int year;
    double birth;

    ofstream outFile; // 출력을 위한 객체 생성
    outFile.open("user_info.txt"); // 파일에 연결 ==> 파일이 생성됨

    cout << "이름을 입력하시오 : ";
    cin.getline(name, 20);
    cout << "태어난 연도를 입력하시오 : ";
    cin >> year;
    cout << "생일을 입력하시오 (12.25) : ";
    cin >> birth;

    cout << fixed;
    cout.precision(2); // 소수점 2째자리 까지 나타냄
    cout.setf(ios_base::showpoint); // 끝에 0을 추가해줌. (1.1 입력시 --> 1.10으로 출력)
    cout << "이름 : " << name << endl;
    cout << "태어난 연도 : " << year << endl;
    cout << "생일 : " << birth << endl;

    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "이름 : " << name << endl;
    outFile << "태어난 연도 : " << year << endl;
    outFile << "생일 : " << birth << endl;

    outFile.close();
    return 0;
}

 

 

[파일 출력 기본 절차]
1. fstream 헤더 파일 포함
2. ofstream 객체 생성. (ex) ofstream outFile; )
3. ofstream 객체를 파일에 연결 (ex) outFile.open("test.txt"); )
4. ofstream 객체를 cout과 같은 방식으로 사용

 

 

 

파일 입력

  • fstream 헤더 파일 사용
#include <iostream>
#include <fstream>

int main()
{
    using namespace std;

    ifstream FILE("user_info.txt");

    if (!FILE) 
    {
        cerr << "파일을 열 수 없습니다.\n";
        return 1;
    }

    string line;
    while(getline(FILE, line))
    {
        cout << line << endl;
    }

    FILE.close();
    return 0;
}

 

[파일 입력 기본 절차]
1. fstream 헤더 파일 포함
2. ifstream 객체 생성 및 파일에 연결 (ex) ifstream FILE("user_info.txt); )
3. 한 줄씩 읽기

 

 

 

파일 읽고 기존 파일 끝에 내용 추가

  • std::ios::app 를 사용해서 기존 파일 끝에 append 가능~!~!
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    using namespace std;

    ////// 파일 읽기 //////
    ifstream FILE("user_info.txt");

    if (!FILE) 
    {
        cerr << "파일을 열 수 없습니다.\n";
        return 1;
    }

    string line;
    while(getline(FILE, line))
    {
        cout << line << endl;
    }
    FILE.close();

    ////// 내용 추가하기 //////
    ofstream FILE2("user_info.txt", ios::app); // append 모드로 파일 열기 (끝에 내용 추가)
    string app_info; // 추가할 문자열

    cout << "추가할 내용을 입력하세요 (종료: q) : ";

    while(getline(cin, app_info) && app_info != "q")
    {
        FILE2 << app_info << endl;
        cout << "입력되었습니다. 다음 내용을 이어서 입력하세요. (종료: q) : ";
    }


    FILE2.close();
    return 0;
}

 

 

 

여러 가지 옵션

모드 설명
ios::in 읽기 모드 (기본: ifstream)
ios::out 쓰기 모드 (기본: ofstream)
ios::app 덧붙이기 모드 (append) – 기존 내용 유지, 파일 끝에만 씀
ios::trunc 파일 내용 제거 후 새로 씀 (쓰기 모드 기본 동작)
ios::ate 파일을 열자마자 커서를 파일 끝으로 이동, 읽기/쓰기 둘 다 가능
ios::binary 바이너리 모드로 파일 처리 (텍스트 아닌 이진 데이터 저장 시 사용)