C++. 파일 입출력 알아보기

최대 1 분 소요

🌟 fstream

C++에서 파일을 입출력 할 때에는, fstream 라이브러리를 사용한다. 여기서 데이터를 읽을 때 ifstream을, 입력할 때 ofstream을 사용함!

ifstream ifs;
ifs("test.txt"); //test 파일 불러오기
ofstream ofs;
ofs("test.txt");

사용법은 간단!

🌟 사용법

파일 출력하기

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream ifs("test.txt");
    if(ifs.fail())
    {
        cerr << "파일이 없습니다." <<endl;
    }
    //파일의 문자 읽기
    char c;
    while(ifs.get(c))
        cout << c;
    
    ifs.close(); //파일 연결 해제
    return 0;
}

파일을 부르고 출력하는 코드! fail 함수로 파일을 올바르게 불렀는지 확인해야 한다. 그리고 C++은 알아서 파일스트림을 닫아줘서 굳이 close 함수를 쓸 필요는 없다.

char를 통해 한 글자씩 가져와 모두 출력했다. getline이나 다른 방법도 있는듯!

파일 입력하기

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ofstream ofs("test.txt");
    ofs << "안녕하세요.";
    return 0;
}

이렇게 하면 바로 test 파일에 “안녕하세요”가 들어간다.

댓글남기기