본문 바로가기

Software/C/C++

File IO Example

  • Cout object 다음과 같은 manipulator 사용할 있다.
    • endl : newline 문자를 삽입한 , 버퍼를 flush한다.
    • ends : null문자를 삽입한다
    • flush : 출력 버퍼를 flush한다
  • 폭지정 (width)
    • 출력되는 항목에 폭을 지정하기 위해서는 setw 조작자를 << 함께 사용하거나, width 멤버함수를 호출한다.
  • #include <iostream.h>


    int main(void)

    {

        double values[] = {1.23, 35.36, 653.7, 4358.24};

        cout << "|";

        for(int i=0; i<10; i++)

            cout << i;

        for(i=0;i<4;i++)

        {

            cout<<"|";

            cout.width(10);

            cout.fill('*');

            cout << values[i]<<endl;

        }

    }

    |0123456789
    |******1.23
    |*****35.36
    |*****653.7
    |***4358.24



    File IO Class

    • ifstream : file stream class for input
    • ofstream : file stream class for output
    • fstream : file stream input output

    File Open

    ofstream outfile("test.dat");

    ofstream outfile;
    outfile.open("test.dat");

    Check file Open

    If(!outfile)
         //fail open file
    else
       //success

    If(!outfile.is_open())
       //fail to open file
    else
      //success

    File Close

    Outfile.close()

    ifstream infile("test.dat");
    if(!inflie) cout << "Not opended test.dat";
    else cout << "Opened test.dat";

    Example : this program open test.txt file input mode, and read the file, display the result to stdout and save to test.out

    #include <iostreamh.>

    #include <fstream.h>

    #include <iomanip.h>

    #define SIZE 256

     

    int main(void)

    {

    int nCntChars, nCntWords, nCntLines;

    char buffer[SIZE], ch;

     

    //create input file stream

    ifstream infile("test.txt", ios::in|ios::nocreate);

     

    //create output file stream

    ofstream outfile("test.out");

    if(!infile || !outfile){

    cerr << "Fail to open!!\n";

    return -1;

    }

     

    //count input character numbers

    for(nCntChars = 0; infile.get(ch); ++nCntChars); //nCntChars -> number of total characters

     

    infile.clear();        //EOF reset

    infile.seekg(0L, ios::beg);        //move to beginning of file

     

    //count of input words

    nCntWords = 0;

    while(infile >> buffer)        ++nCntWords;

     

    infile.clear();        //EOF reset

    infile.seekg(0L, ios::beg);        //move to beginning of file

     

    //copy

    for(nCntLines = 1; infile.getline(buffer, SIZE); ++nCntLines)        //nCntLines-1 -->total line

    {

    cout.width(3);

    cout << nCntLines << "  ";

    cout << buffer << endl;

    outfile << buffer << endl;

    }

    cout << "Total" << --nCntLines << "line, " << nCntWords << " words, " << nCntChars << endl;

     

    infile.close();

    outfile.close();

    return 0;

    }