Taene's

[C++] 파일 입출력(fstream) 본문

C++ 개념 공부/STL

[C++] 파일 입출력(fstream)

taene_ 2024. 4. 2. 14:32

- 헤더파일

#include <fstream>

 

- ofstream: output file stream, 파일로 데이터를 출력할 때 사용하는 클래스(파일에 내용을 적음, write)

- ifstream: input file stream, 파일 입력할 때 사용하는 클래스(파일에서 내용을 읽음, read)

- fstream: ofstream과 ifstream을 합친, 둘 다 사용가능한 클래스

ofstream ofile("log.txt");	//ofstream형 ofile변수선언, log.txt 생성(초기화)
/*
ofstream ofile;
ofile.open("log.txt");	//open()함수로 초기화 하는 법
*/

ofile << size << ", " << count << '\n';	//log.txt에 내용 삽입

ofile.close();	//log.txt 닫기

 

- 주의: 이미 존재하는 파일을 처음 열고 파일 출력을 하면 원래 있던 내용이 덮어진다.

최초로 파일을 열면 커서는 맨앞에 위치하고, getline으로 한줄을 읽거나 파일에 내용을 쓰면 커서는 다음줄을 가르킨다.

( ex) test.txt 파일에 123이라는 내용이 있고 fout<<"a"<<endl; 하면 내용이 a23으로 바뀐다. )

- 이를 위해 seekg, seekp와 같은 커서를 옮기는 메서드가 있다.

 

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

int main()
{
	ofstream fout;
	ifstream fin;

	//ofstream으로 파일 쓰기
	fout.open("test.txt");

	for (int i = 0; i < 5; i++)
	{
		fout << "file output stream test" << endl;
	}

	fout.close();

	//ifstream으로 파일 읽기
	fin.open("test.txt");

	while (!fin.eof())
	{
		char newline[255];
		fin.getline(newline, 255);
		cout << newline << endl;
	}

	fin.close();


	//fstream으로 쓰고 읽기 모두 가능
	fstream fio;

	fio.open("test.txt");

	fio.seekg(0, ios::end);	//파일 마지막에 커서를 두고 씀
	fio << "fstream input test" << endl;

	fio.seekp(0);	//다 쓰고 처음부터 읽기 위해 커서를 맨앞으로 갖다 놓음
	while (!fio.eof())
	{
		char newline[255];
		fio.getline(newline, 255);
		cout << newline << endl;
	}

	fio.close();

	return 0;
}

'C++ 개념 공부 > STL' 카테고리의 다른 글

[C++] std::vector  (0) 2024.05.15
[C++] 동적 크기 배열 구현하기(dynamic_array)  (0) 2024.05.13
[C++] std::memset  (0) 2024.03.15
[C++] std::map  (0) 2023.09.11
[C++] std::stack  (0) 2023.09.04