C++/C++ ifstream, ofstream

ifstream, ofstream

재윤 2023. 12. 1. 13:45
반응형
  • C++의 <fstream> 헤더는 파일 입출력을 위한 클래스들을 제공함. 이 헤더는 ifstreamofstream 클래스를 포함하고 있다.

ifstream (Input File Stream): ifstream 클래스는 파일에서 데이터를 읽기 위해 사용된다. 즉, 파일을 열어서 데이터를 읽을 때 사용된다. 파일을 열고 읽기 전용으로 사용된다.

쉽게 말해서 원래 있는 파일을 열어서 데이터를 읽어오는 것.

ifstream를 사용하여 파일을 열고 데이터를 읽는 예제:

#include <fstream>
#include <iostream>

int main() {
    std::ifstream inputFile("input.txt"); // input.txt 파일을 읽기 위해 엽니다

    if (inputFile.is_open()) { // 파일이 정상적으로 열렸는지 확인
        std::string line;
        while (std::getline(inputFile, line)) { // 파일에서 한 줄씩 읽어옴
            std::cout << line << std::endl; // 읽은 데이터를 화면에 출력
        }
        inputFile.close(); // 파일 닫기
    } else {
        std::cout << "Unable to open file" << std::endl;
    }

    return 0;
}

input.txt

hello world

 

결과

./a.out           
hello world

ofstream (Output File Stream): ofstream 클래스는 파일에 데이터를 쓰기 위해 사용된다. 파일을 열고 쓰기 전용으로 사용된다.

쉽게 말해서 파일을 생성하고 그 안에 데이터를 작성.

ofstream를 사용하여 파일을 열고 데이터를 쓰는 예제:

#include <fstream>
#include <iostream>

int main() {
    std::ofstream outputFile("output.txt"); // output.txt 파일을 쓰기 위해 엽니다

    if (outputFile.is_open()) { // 파일이 정상적으로 열렸는지 확인
        outputFile << "Hello, World!" << std::endl; // 파일에 데이터 쓰기
        outputFile.close(); // 파일 닫기
    } else {
        std::cout << "Unable to open file" << std::endl;
    }

    return 0;
}

결과

./a.out 
C++ % cat output.txt 
Hello, World!
반응형

'C++ > C++ ifstream, ofstream' 카테고리의 다른 글

ifstream, ofstream C++98, C++11  (0) 2023.12.02