C++ fstream

2021. 3. 29. 23:59·SW개발/C++
반응형

fstream

  • <fstream> 라이브러리

  • 기본 옵션은 ASCII 포맷으로 덮어쓰기이다.

    • 옵션에 대한 플래그는 다음과 같다.

      xiosbase

      static constexpr _Openmode in         = static_cast<_Openmode>(0x01);
      static constexpr _Openmode out        = static_cast<_Openmode>(0x02);
      static constexpr _Openmode ate        = static_cast<_Openmode>(0x04);
      static constexpr _Openmode app        = static_cast<_Openmode>(0x08);
      static constexpr _Openmode trunc      = static_cast<_Openmode>(0x10);
      static constexpr _Openmode _Nocreate  = static_cast<_Openmode>(0x40);
      static constexpr _Openmode _Noreplace = static_cast<_Openmode>(0x80);
      static constexpr _Openmode binary     = static_cast<_Openmode>(0x20);
  • 옵션으로 이어쓰기, binary 포맷으로 열기가 가능하다.

  • 클래스의 소멸자에서 파일을 닫아주기 때문에 굳이 fstream.close()를 할 필요가 없다. (RAII)

    • 하지만 가독성 등의 이유로 명시하는게 낫다고 생각한다.
  • 비주얼 스튜디오에서 Ctrl + K를 누르고 R을 누르면(컨트롤 없이) 작업 중인 폴더가 익스플로러로 열린다.


예제

  • ASCII 포맷으로 저장 후 불러오는 예제

    #include <iostream>
    #include <string>
    #include <fstream>
    
    int         main()
    {
        using namespace std;
    
        string filename = "my_first_file.txt";
    
        {
            ofstream ofs(filename);
    
            if (!ofs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            ofs << "Line 1\n";
            ofs << "Line 2\n";
    
            ofs.close();
        }
    
        {
            ifstream ifs(filename);
    
            if (!ifs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            while (ifs)
            {
                string str;
                getline(ifs, str);
                cout << str << endl;
            }
    
            ifs.close();
        }
    }
    
    /* stdout stderr
    Line 1
    Line 2
    */

  • ios::app 사용

    #include <iostream>
    #include <string>
    #include <fstream>
    
    int         main()
    {
        using namespace std;
    
        string filename = "my_first_file.txt";
    
        {
            ofstream ofs(filename, ios::app);
    
            if (!ofs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            ofs << "Line 1\n";
            ofs << "Line 2\n";
    
            ofs.close();
        }
    
        {
            ifstream ifs(filename);
    
            if (!ifs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            while (ifs)
            {
                string str;
                getline(ifs, str);
                cout << str << endl;
            }
    
            ifs.close();
        }
    }
    
    /* stdout stderr (3번 반복 실행 시)
    Line 1
    Line 2
    Line 1
    Line 2
    Line 1
    Line 2
    */

  • binary 포맷 예제

    #include <iostream>
    #include <string>
    #include <fstream>
    
    int         main()
    {
        using namespace std;
    
        string filename = "my_first_file.txt";
    
        {
            ofstream ofs(filename, ios::binary);
    
            if (!ofs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            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));
    
            ofs.close();
        }
    
        {
            ifstream ifs(filename, ios::binary);
    
            if (!ifs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            unsigned num_data = 0;
            ifs.read((char*)&num_data, sizeof(num_data));
            cout << "Number of data : " << num_data << endl;
            for (unsigned i = 0; i < num_data; ++i)
            {
                int num;
                ifs.read((char*)&num, sizeof(num));
                cout << num << endl;
            }
    
            ifs.close();
        }
    }
    
    /* stdout stderr
    Number of data : 10
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    */

  • stringstream 사용

    #include <iostream>
    #include <string>
    #include <fstream>
    #include <sstream>
    
    int         main()
    {
        using namespace std;
    
        string filename = "my_first_file.txt";
    
        {
            ofstream ofs(filename, ios::binary);
    
            if (!ofs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            stringstream ss;
            ss << "Line 1\n";
            ss << "Line 2\n";
            string str = ss.str();
    
            unsigned str_length = str.size();
            ofs.write((char*)&str_length, sizeof(str_length));
            ofs.write(str.c_str(), str_length);
    
            ofs.close();
        }
    
        {
            ifstream ifs(filename, ios::binary);
    
            if (!ifs)
            {
                cerr << "Fail to open file\n";
                exit(1);
            }
    
            unsigned str_length = 0;
            ifs.read((char*)&str_length, sizeof(str_length));
            cout << "Size of string: " << str_length << endl;
            string str;
            str.resize(str_length);
            ifs.read(&str[0], str_length);
            cout << str << endl;
    
            ifs.close();
        }
    }
    
    /* stdout stderr
    Size of string: 14
    Line 1
    Line 2
    */
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

따라하며 배우는 C++ 19장  (0) 2021.03.30
C++ 파일 임의 위치 접근  (0) 2021.03.29
C++ 정규 표현식 (Regular Expressions)  (0) 2021.03.29
C++ 흐름 상태 (Stream States)  (0) 2021.03.29
C++ cout  (0) 2021.03.29
'SW개발/C++' 카테고리의 다른 글
  • 따라하며 배우는 C++ 19장
  • C++ 파일 임의 위치 접근
  • C++ 정규 표현식 (Regular Expressions)
  • C++ 흐름 상태 (Stream States)
Caniro
Caniro
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    제외
    Solaris 10
    스프링 프레임워크 핵심 기술
    vscode
    KakaoTalk
    알림
    SunOS 5.1
    logi options
    dism
    윈도우 명령어
    citrix workspace
    Workspace
    SFC
    맥북 카카오톡 알림 안뜸
    스프링
    Windows 11
    MacOS
    윈도우
    mspaint
    EXCLUDE
    spring
    windows
    백기선
    java
    로지텍 마우스 제스처
    그림판
    시스템 복구
    unix
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ fstream
상단으로

티스토리툴바