250x250
Notice
Recent Posts
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
관리 메뉴

일상 코딩

[C++/CPP] 18.06. basic file i/o 본문

C++/따배C++ 18강 입력과 출력

[C++/CPP] 18.06. basic file i/o

polarcompass 2021. 12. 21. 03:45
728x90
#include<iostream>
#include<fstream> // file I/O library
#include<string>
#include<cstdlib>
#include<sstream>

using namespace std;

int main()
{
    // writing
    if(true)
    {
        ofstream ofs("my_first_file.dat", ios::binary); // ios::app - append mode, ios::binary
        // ofs.open("my_first_file.dat")

        if (!ofs)
        {
            cerr << "Couldn't open file " << endl;
            exit(1);
        }

        // ASCII로 저장하는 line
        // string st("Line ");
        // for (int i = 1; i < 6; ++i)
        //     ofs << st + std::to_string(i) << endl;
        
        // binary write
        // 현업에선 binary만씀.
        const unsigned num_data = 10;
        ofs.write((char*)&num_data, sizeof(num_data));

        for (int i = 0; i < num_data ; ++i)
            ofs.write((char*)&i, sizeof(i));
    }

    // reading
    if(true)
    {
        ifstream ifs("my_first_file.dat", ios::binary); //, ios::binary);

        if(!ifs)
        {
            cerr << "Cannot open file" << endl;
            exit(1);
        }
        // ASCII read
        // while(ifs)
        // {
        //     std::string str;
        //     getline(ifs, str);

        //     std::cout << str << endl;
        // }

        // binary read
        unsigned num_data = 0;
        ifs.read((char*)&num_data, sizeof(num_data));

        for (unsigned i = 0; i < num_data; ++i)
        {
            int num;
            ifs.read((char*)&num, sizeof(num));

            cout << num << endl;
        }
    }


    return 0;
}
728x90