Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- using namespace std;
- void write() {
- ofstream ofs("data.txt"); // RAII 패턴을 적용하고 있어 리소스 해제가 스택을 통해 이루어짐
- ofs << 0.0 << ' ' << -0.4 << '\n';
- ofs << -0.5 << ' ' << 0.2 << '\n';
- ofs << 0.5 << ' ' << 0.8 << flush;
- }
- void read1() {
- ifstream ifs1("data.txt"); // RAII
- float val1;
- while (ifs1 >> val1, !ifs1.eof()) // 마지막 0.8 읽으면서 eof 읽고 무시(eofbit on) -> 0.8은 출력 안됨
- cout << val1 << " ";
- std::cout << std::endl;
- }
- void read2() {
- ifstream ifs2("data.txt");
- float val2;
- while (ifs2 >> val2) // ifs2가 평가됨(마지막 0.8 읽으면서 eof 읽고 무시, fail이 아니므로 (bool)ifs2 = false, 다음 턴에 fail)
- cout << val2 << " ";
- std::cout << std::endl;
- }
- void read3() {
- ifstream ifs3("data.txt");
- float val3;
- while (ifs3) { // fail 될 때만 false 됨(eof 넘어서 읽으려 할 때)
- ifs3 >> val3; // 마지막 0.8 읽으면서 eof 읽고 무시(eofbit on) -> 0.8은 출력 안됨
- if (ifs3.eof()) // eof 비트까지 읽고 나서야 eofbit on
- break;
- cout << val3 << " ";
- }
- std::cout << std::endl;
- }
- void read4() {
- ifstream ifs4("data.txt");
- char val4;
- while (ifs4) {
- val4 = ifs4.get(); // 한 바이트씩 읽어오기(eof 읽는 순간 eofbit, failbit on)
- if (ifs4.eof()) break;
- std::cout << val4;
- }
- std::cout << std::endl;
- }
- void read5() {
- ifstream ifs5("data.txt");
- char val5;
- while (ifs5.get(val5)) { // eof 읽는 순간 eofbit, failbit 켜짐, val5 변경 X
- std::cout << val5;
- }
- std::cout << std::endl;
- }
- int main() {
- write();
- std::cout << "read1" << std::endl;
- read1();
- std::cout << "read2" << std::endl;
- read2();
- std::cout << "read3" << std::endl;
- read3();
- std::cout << "read4" << std::endl;
- read4();
- std::cout << "read5" << std::endl;
- read5();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement