[C++] 텍스트 파일 입출력

chxxrin·2024년 7월 25일
0

C++

목록 보기
17/22

헤더파일 선언

#include <fstream> 
  • 파일 입출력에 필요한 ofstream, ifstream 사용가능

전체코드

/*
    홍정모 연구소 https://honglab.co.kr/
*/

#include <iostream>
#include <fstream> // 파일 입출력에 필요한 ofstream, ifstream 사용가능

using namespace std;

int main()
{
    // 파일 출력

        ofstream ofile;

        ofile.open("my_contacts.txt");
        ofile << "안녕하세요? 반갑습니다.\n";
        ofile << "두 번째 줄입니다.\n";
        ofile << "세 번째 줄입니다.\n";
        ofile.close();


    // 파일 입력
    {
        char line[100]; // 한줄한줄 임시로 저장할 공간 (100은 임의로 설정, 최대 길이가 100글자라고 가정)

        ifstream ifile;
        ifile.open("my_contacts.txt");

        int line_number = 0;

        // 더이상 읽어들일 수 없을 때까지 진행
        while (ifile.getline(line, sizeof(line)))
        {
            cout << line_number << " : ";
            cout << line << endl;

            line_number += 1; // 라인넘버 한줄한줄 증가
        }

        ifile.close(); // 파일 닫기
    }

    return 0;
}

출처 : 홍정모 유튜브

0개의 댓글

관련 채용 정보