반응형

C++ 텍스트 파일 입출력 예제

 

글. 오상문 sualchi@daum.net

 

#include <iostream>

#include <fstream>

 

using namespace std;

 

int main()

{

  ifstream fi;     // 읽기용 파일 

  ofstream fo;   // 쓰기용 파일 

 

  fo.open("test.txt"); // 쓰기용 파일 열기 

  

  if (!fo) {   // if(fo.fail())

    cerr << "쓰기용 파일 오픈에 실패했습니다!" << endl;

    exit(1);

  }

 

  for (int i = 0; i < 10; i++)  // 0~9 숫자를 한 줄에 하나씩 저장 

  fo << i << endl;

 

  fo.close();                   // 쓰기용 파일 닫기

 

  fi.open("test.txt");          // 읽기용 파일 열기

  if (!fi) {                       // if(fi.fail())

    cerr << "읽기용 파일 오픈에 실패했습니다!" << endl;

    exit(1);

  }

 

  int line = 1;                 // 줄 번호 출력용 

  char c;

  cout << line << ": ";    // 줄 번호 출력 

 

  do {

    fi.get(c);                 // c = fi.get();  한 문자씩 읽기

    cout << c;

    if (c == '\n') {        // 다음 줄이면, 줄번호 번호 증가하고 출력

      line++;

      cout << line << ": ";

    }

  } while (!fi.eof());      // 파일 끝일 때까지 반복

 

  fi.close();                // 읽기용 파일 닫기

  return 0;

}

 

<이상>

 

 

반응형

+ Recent posts