ifstream으로 파일 읽기
텍스트와 데이터 읽기
ifstream으로 파일 읽기은(는) CoddyKit의 무료 C++ Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C++ Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
입력 파일 스트림이란 무엇인가요
std::ifstream(입력 파일 스트림)은 파일에서 데이터를 읽습니다. std::cin처럼 동작하지만 데이터의 출처가 디스크의 파일입니다.
<fstream>에 정의되어 있습니다.- 생성자에서 파일 이름을 받아 파일을 엽니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("demo.txt") << "hello\n";
std::ifstream in("demo.txt");
std::string word;
in >> word;
std::cout << word << '\n';
return 0;
}파일 열기
파일 이름으로 ifstream을 생성한 다음, 파일을 찾았는지 is_open()으로 확인하십시오.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("data.txt") << "42\n";
std::ifstream in("data.txt");
std::cout << (in.is_open() ? "opened" : "failed") << '\n';
return 0;
}단어 읽기
>> 연산자는 cin과 마찬가지로 공백으로 구분된 토큰을 읽습니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("words.txt") << "alpha beta gamma\n";
std::ifstream in("words.txt");
std::string w;
while (in >> w) std::cout << w << '\n';
return 0;
}숫자 읽기
숫자 형식은 직접 추출할 수 있습니다. 스트림 추출은 텍스트를 올바른 형식의 값으로 분석합니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("nums.txt") << "10 20 30\n";
std::ifstream in("nums.txt");
int sum = 0, x;
while (in >> x) sum += x;
std::cout << "sum = " << sum << '\n';
return 0;
}줄 전체 읽기
std::getline()을 사용하면 줄 바꿈이 나올 때까지 공백을 포함한 한 줄 전체를 읽을 수 있습니다.
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream("lines.txt") << "first line\nsecond line\n";
std::ifstream in("lines.txt");
std::string line;
while (std::getline(in, line)) std::cout << "[" << line << "]\n";
return 0;
}파일 전체 읽기
파일 전체를 한꺼번에 읽으려면 스트림 버퍼 반복자를 사용해 문자열로 읽어 들이십시오.
#include <iostream>
#include <fstream>
#include <sstream>
int main() {
std::ofstream("all.txt") << "line1\nline2\n";
std::ifstream in("all.txt");
std::stringstream ss;
ss << in.rdbuf();
std::cout << ss.str();
return 0;
}파일 끝 감지
읽기 반복문은 추출에 실패하면 종료되며, 일반적으로 파일 끝에서 이런 일이 발생합니다. 조건식에서 스트림을 검사하면 이를 확인할 수 있습니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("eof.txt") << "1 2 3\n";
std::ifstream in("eof.txt");
int x, count = 0;
while (in >> x) ++count;
std::cout << "read " << count << " numbers\n";
std::cout << "eof: " << std::boolalpha << in.eof() << '\n';
return 0;
}없는 파일 처리
파일이 존재하지 않으면 스트림은 실패 상태가 되고 is_open()은 false가 됩니다. 읽기 전에 항상 확인하십시오.
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("does_not_exist_12345.txt");
if (!in) {
std::cout << "could not open file\n";
}
return 0;
}구조화된 줄 분석
getline과 istringstream을 함께 사용하면 각 줄에서 필드를 분석해 추출할 수 있습니다.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
std::ofstream("people.txt") << "Alice 30\nBob 25\n";
std::ifstream in("people.txt");
std::string line;
while (std::getline(in, line)) {
std::istringstream ss(line);
std::string name; int age;
ss >> name >> age;
std::cout << name << " is " << age << '\n';
}
return 0;
}명시적인 open 및 close
기본 생성자로 만든 스트림은 나중에 open()으로 열고 close()로 해제할 수 있습니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("oc.txt") << "data\n";
std::ifstream in;
in.open("oc.txt");
std::string s; in >> s;
in.close();
std::cout << s << '\n';
return 0;
}RAII가 자동으로 close 수행
ifstream이 범위를 벗어나면 소멸자가 파일을 자동으로 닫습니다. 수동으로 close()를 호출할 필요는 거의 없습니다.
#include <iostream>
#include <fstream>
int main() {
std::ofstream("raii.txt") << "x\n";
{
std::ifstream in("raii.txt");
std::string s; in >> s;
std::cout << s << '\n';
} // file closed here automatically
std::cout << "closed\n";
return 0;
}빠른 확인
줄 읽기에 대한 이해도를 확인해 보십시오.
복습
std::ifstream이 다음과 같이 동작한다는 것을 배웠습니다.
>>와std::getline을 사용해 파일에서 읽습니다is_open()을 호출하거나 스트림을 검사하여 상태를 확인해야 합니다- 범위를 벗어나면 RAII를 통해 자동으로 닫힙니다
다음에는 ofstream으로 파일을 작성합니다.
자주 묻는 질문
“ifstream으로 파일 읽기” 강의는 무료인가요?
네 — “ifstream으로 파일 읽기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C++ Academy 강의 전체를 잠금 해제할 수 있습니다. C++ Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“ifstream으로 파일 읽기”에서 뭘 배우나요?
텍스트와 데이터 읽기 브라우저에서 직접 실행하는 실습 코드로 C++ Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C++ Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C++ Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“ifstream으로 파일 읽기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C++ Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C++ Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- ifstream으로 파일 읽기
- ofstream으로 파일 쓰기
- 바이너리 파일 입출력
- 오류 처리와 상태