파일 쓰기

이동규·2025년 1월 12일

C++

목록 보기
16/16

파일을 txt 쓰기


#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char const *argv[])
{
    ofstream fout;
    fout.open("HelloWorld.txt");//쓰기 스트림열기

    string line;
    getline(cin, line);
    
    if (!cin.fail())
    {
        fout << line << endl;
        /* code */
    }

    fout.close();

    /* code */
    return 0;
}

바이너리 파일 쓰고 읽기

#include <iostream>
#include <fstream>

using namespace std;

struct Record
{
    char text[512];
    int id;
};

int main(int argc, char const *argv[])
{
    ifstream fin("studentRecords.dat", ios_base::in | ios_base::binary);

    if (fin.is_open())
    {
        Record record;
        fin.read((char *)&record, sizeof(Record));// Record크기만큼 읽기
        cout << record.text << endl;
        cout << record.id << endl;
    }
    
    return 0;
}

파일 뒤에 덮어쓰기

#include <fstream>
#include <iostream>
using namespace std;

int main(int argc, char const *argv[]) {
    ofstream fout;
    fout.open("HelloWorld.txt",
              ios::app);  // app은 뒤에 데이터 추가 trunc 는 덮어쓰기

    string line;
    getline(cin, line);

    if (!cin.fail()) {
        fout << line << endl;
        /* code */
    }

    fout.close();

    return 0;
}

탐색(seek) 유형

절대적
예) 특정한 위치로 감
보통 tellp()/tellg()를 사용해서 기억해 놨던 위치로 돌아갈 때 사용

상대적
예) 특정한 위치로 감
보통 tellp()/tellg()를 사용해서 기억해 놨던 위치로 돌아갈 때 사용

파일 쓰기 위치 읽기 및 변경

ios_base 네임스페이스를 사용한다.

0개의 댓글