'프로그래밍/C++'에 해당되는 글 1건

  1. 2015.03.09 [C++] 텍스트파일 줄 단위 읽기, 쓰기
2015. 3. 9. 11:59




파일 읽기 - 라인단위, 텍스트 파일

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    ifstream ifile;

    char line[200]; // 한 줄씩 읽어서 임시로 저장할 공간
       
    ifile.open("input.txt");  // 파일 열기

    if (ifile.is_open())
    {
        while (ifile.getline(line, sizeof(line))) // 한 줄씩 읽어 처리를 시작한다.
        {
            cout << line << endl; // 내용 출력
        }
    }

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

    return 0;
}




파일 쓰기 - 라인단위, 텍스트 파일

#include <iostream>
#include <fstream>

using namespace std;

int main(void)
{
    ofstream ofile;
    ofile.open("output.txt");

    // 파일 쓰기
    for (int x = 0; x < 10; x++)
    {
        ofile << x << endl;
    }

    ofile.close(); // 파일닫기

    return 0;
}







Posted by 해비