250x250
Notice
Recent Posts
«   2024/07   »
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 31
관리 메뉴

일상 코딩

[C++/CPP] 18.07. Random Accessing File, read / write 본문

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

[C++/CPP] 18.07. Random Accessing File, read / write

polarcompass 2021. 12. 22. 02:08
728x90
#include<iostream>
#include<fstream>
#include<string>
#include<cstdlib>
#include<sstream>

using namespace std;

int main()
{
    const string filename = "my_file.txt";

    // make a file
    {
        ofstream ofs(filename);
        for (char i = 'a'; i <= 'z'; i++)           
            ofs << i;
        ofs << endl;
    }

    // read the file
    {
        ifstream ifs("my_file.txt");

        // 시작점에서 커서 5칸 이동 후 커서 뒤의 글자 읽기
        ifs.seekg(5); // ifs.seekg(5, ios::beg);
        cout << (char)ifs.get() << endl;

        ifs.seekg(5, ios::cur);
        cout << (char)ifs.get() << endl;

        // 처음부터 끝까지 읽고 
        ifs.seekg(0, ios::end);
        // 커서의 현재 위치 반환
        cout << ifs.tellg() << endl;

        string str;
        getline(ifs, str);

        cout << str << endl;
    }

    // file을 한번 열어서 읽기 / 쓰기 둘다하는 방법
    {   
        //                            입출력 flag
        // fstream iofs(filename, ios::in | ios::out);
        fstream iofs(filename);

        // 시작점에서 5칸 이동
        iofs.seekg(5);
        cout << (char)iofs.get() << endl; // read

        // 다시 시작점에서 5칸 이동 후 덮어쓰기
        iofs.seekg(5);
        iofs.put('A'); // write
    }


    return 0;
}
728x90