[c++] 파일 읽기 오류 처리
파일을 읽는 동안 발생할 수 있는 오류를 처리하는 것은 중요합니다. 아래에서는 C++로 파일을 읽을 때 발생하는 오류를 처리하는 방법을 설명합니다.
파일 열기
파일을 열 때 오류가 발생할 수 있습니다. 파일을 열 때 오류가 발생하면, 에러 메시지와 함께 프로그램이 종료될 수 있습니다. 이를 피하기 위해 파일을 열 때 오류를 처리하는 것이 중요합니다.
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt");
if (!file.is_open()) {
std::cerr << "파일을 열 수 없습니다." << std::endl;
return 1;
}
// 파일 읽기 코드
// ...
file.close();
return 0;
}
파일을 열 때 오류가 발생하면, 파일이 열리지 않았음을 사용자에게 알리고 프로그램을 종료합니다.
읽기 오류 처리
파일을 열었지만 읽기 도중 오류가 발생할 수 있습니다. 이를 처리하기 위해 파일에서 읽을 때 오류를 확인해야 합니다.
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("example.txt");
if (!file.is_open()) {
std::cerr << "파일을 열 수 없습니다." << std::endl;
return 1;
}
std::string content;
if (!(file >> content)) {
std::cerr << "파일을 읽을 수 없습니다." << std::endl;
return 1;
}
std::cout << content << std::endl;
file.close();
return 0;
}
읽을 때 오류가 발생하면, 사용자에게 알리고 프로그램을 종료합니다.
참조
- C++ 파일 읽기: https://www.cplusplus.com/reference/fstream/ifstream/