Advertisement
junghu1124

Untitled

Sep 15th, 2023
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | Source Code | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. void write() {
  7.     ofstream ofs("data.txt"); // RAII 패턴을 적용하고 있어 리소스 해제가 스택을 통해 이루어짐
  8.     ofs << 0.0 << ' ' << -0.4 << '\n';
  9.     ofs << -0.5 << ' ' << 0.2 << '\n';
  10.     ofs << 0.5 << ' ' << 0.8 << flush;
  11. }
  12.  
  13. void read1() {
  14.     ifstream ifs1("data.txt"); // RAII
  15.     float val1;
  16.     while (ifs1 >> val1, !ifs1.eof()) // 마지막 0.8 읽으면서 eof 읽고 무시(eofbit on) -> 0.8은 출력 안됨
  17.         cout << val1 << " ";
  18.     std::cout << std::endl;
  19. }
  20.  
  21. void read2() {
  22.     ifstream ifs2("data.txt");
  23.     float val2;
  24.     while (ifs2 >> val2) // ifs2가 평가됨(마지막 0.8 읽으면서 eof 읽고 무시, fail이 아니므로 (bool)ifs2 = false, 다음 턴에 fail)
  25.         cout << val2 << " ";
  26.     std::cout << std::endl;
  27. }
  28.  
  29. void read3() {
  30.     ifstream ifs3("data.txt");
  31.     float val3;
  32.     while (ifs3) { // fail 될 때만 false 됨(eof 넘어서 읽으려 할 때)
  33.         ifs3 >> val3; // 마지막 0.8 읽으면서 eof 읽고 무시(eofbit on) -> 0.8은 출력 안됨
  34.         if (ifs3.eof()) // eof 비트까지 읽고 나서야 eofbit on
  35.             break;
  36.         cout << val3 << " ";
  37.     }
  38.     std::cout << std::endl;
  39. }
  40.  
  41. void read4() {
  42.     ifstream ifs4("data.txt");
  43.     char val4;
  44.     while (ifs4) {
  45.         val4 = ifs4.get(); // 한 바이트씩 읽어오기(eof 읽는 순간 eofbit, failbit on)
  46.         if (ifs4.eof()) break;
  47.         std::cout << val4;
  48.     }
  49.     std::cout << std::endl;
  50. }
  51.  
  52. void read5() {
  53.     ifstream ifs5("data.txt");
  54.     char val5;
  55.     while (ifs5.get(val5)) { // eof 읽는 순간 eofbit, failbit 켜짐, val5 변경 X
  56.         std::cout << val5;
  57.     }
  58.     std::cout << std::endl;
  59. }
  60.  
  61. int main() {
  62.     write();
  63.  
  64.     std::cout << "read1" << std::endl;
  65.     read1();
  66.  
  67.     std::cout << "read2" << std::endl;
  68.     read2();
  69.  
  70.     std::cout << "read3" << std::endl;
  71.     read3();
  72.  
  73.     std::cout << "read4" << std::endl;
  74.     read4();
  75.  
  76.     std::cout << "read5" << std::endl;
  77.     read5();
  78.  
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement