0Pricing
C++ Academy · 강의

ofstream으로 파일 쓰기

출력 파일 작성하기

ofstream으로 파일 쓰기은(는) CoddyKit의 무료 C++ Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C++ Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

출력 파일 스트림이란 무엇인가요

std::ofstream(출력 파일 스트림)은 파일에 데이터를 씁니다. std::cout처럼 동작하지만 출력 대상이 파일입니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("hello.txt");
    out << "Hello, file!\n";
    std::cout << "wrote file\n";
    return 0;
}

텍스트 쓰기

<< 연산자를 사용하면 콘솔에 출력할 때와 똑같이 문자열과 숫자를 쓸 수 있습니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("report.txt");
    out << "Score: " << 95 << '\n';
    out << "Grade: A\n";
    std::cout << "done\n";
    return 0;
}

기본 동작은 내용 삭제

기존 파일을 ofstream으로 열면 이전 내용이 삭제됩니다. 실행할 때마다 빈 상태에서 시작합니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("t.txt") << "old content\n";
    std::ofstream out("t.txt");
    out << "new content\n";
    std::ifstream in("t.txt");
    std::string line; std::getline(in, line);
    std::cout << line << '\n';
    return 0;
}

app 모드로 이어 쓰기

std::ios::app을 전달하면 기존 내용을 유지하고 끝에 새 데이터를 추가할 수 있습니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream("log.txt") << "line1\n";
    std::ofstream out("log.txt", std::ios::app);
    out << "line2\n";
    out.close();
    std::ifstream in("log.txt");
    std::string l; int n = 0;
    while (std::getline(in, l)) ++n;
    std::cout << n << " lines\n";
    return 0;
}

쓰기 성공 여부 확인

연 후에 스트림을 검사하십시오. 스트림이 bad 상태이면 쓰기 작업이 조용히 실패합니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("ok.txt");
    if (!out) {
        std::cout << "failed to open\n";
        return 1;
    }
    out << "safe write\n";
    std::cout << "write ok\n";
    return 0;
}

숫자 쓰기와 형식 지정

std::fixed와 std::setprecision 같은 입출력 조작자는 파일 스트림에도 적용됩니다.

#include <iostream>
#include <fstream>
#include <iomanip>

int main() {
    std::ofstream out("pi.txt");
    out << std::fixed << std::setprecision(3) << 3.14159 << '\n';
    out.close();
    std::ifstream in("pi.txt");
    std::string s; in >> s;
    std::cout << s << '\n';
    return 0;
}

반복문으로 데이터 쓰기

반복문을 사용하면 여러 줄을 쓸 수 있습니다. 각 반복에서 하나의 레코드를 파일로 보냅니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("squares.txt");
    for (int i = 1; i <= 5; ++i) out << i << ' ' << i * i << '\n';
    out.close();
    std::cout << "wrote 5 rows\n";
    return 0;
}

버퍼 비우기

출력은 버퍼에 저장됩니다. std::flush 또는 std::endl은 버퍼의 내용을 즉시 디스크로 보내며, 스트림을 닫을 때도 버퍼가 비워집니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("flush.txt");
    out << "important" << std::flush;
    std::cout << "flushed to disk\n";
    return 0;
}

endl과 줄 바꿈 비교

'\n'은 줄 바꿈만 추가합니다. std::endl은 줄 바꿈을 추가하고 버퍼도 비우므로, 반복문 안에서 사용하면 느려집니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("nl.txt");
    out << "fast\n";          // newline only
    out << "slow" << std::endl; // newline + flush
    std::cout << "both written\n";
    return 0;
}

쓰기 후 읽기로 왕복하기

일반적인 방식은 데이터를 쓰고, close한 다음, 다시 열어 읽는 것입니다.

#include <iostream>
#include <fstream>

int main() {
    {
        std::ofstream out("rt.txt");
        out << 7 << ' ' << 8 << '\n';
    }
    std::ifstream in("rt.txt");
    int a, b; in >> a >> b;
    std::cout << a + b << '\n';
    return 0;
}

열기 모드 선택

|로 플래그를 결합하십시오. 일반적인 모드는 ios::out(기본값), ios::app(추가), ios::trunc(삭제)입니다.

#include <iostream>
#include <fstream>

int main() {
    std::ofstream out("modes.txt", std::ios::out | std::ios::trunc);
    out << "fresh\n";
    std::cout << "opened with explicit modes\n";
    return 0;
}

빠른 확인

ofstream 모드에 대한 이해도를 확인해 보십시오.

복습

std::ofstream이 다음과 같이 동작한다는 것을 배웠습니다.

  • <<로 쓰며, 기본적으로 기존 내용을 삭제합니다
  • std::ios::app으로 내용을 추가합니다
  • 출력을 버퍼에 저장하며, std::flush/std::endl/스트림 닫기를 통해 디스크로 보냅니다

다음에는 이진 파일 입출력으로 원시 바이트를 처리합니다.

자주 묻는 질문

“ofstream으로 파일 쓰기” 강의는 무료인가요?

네 — “ofstream으로 파일 쓰기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C++ Academy 강의 전체를 잠금 해제할 수 있습니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“ofstream으로 파일 쓰기”에서 뭘 배우나요?

출력 파일 작성하기 브라우저에서 직접 실행하는 실습 코드로 C++ Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

C++ Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 C++ Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“ofstream으로 파일 쓰기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 C++ Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 C++ Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. ifstream으로 파일 읽기
  2. ofstream으로 파일 쓰기
  3. 바이너리 파일 입출력
  4. 오류 처리와 상태
← C++ Academy(으)로 돌아가기