Beginner's Guide
    First Steps
    Input & Output
    Basic Custom Types
    Diagnostics
    Standard Library
    Code Organization
    Powerful Custom Types
    Generic Programming
    Memory Management
    Software Design Basics

    File Input & OutputFile I/OFile I/O

    Write Text File Writing

    with  std::ofstream  (output file stream)
    #include <fstream>  // file stream header
    
    int main() {
      std::ofstream os {"squares.txt"};  // open file
    
      // if stream OK = can write to file 
      if( os.good() ) {
        double x, y;
    
        for(int x = 1; x <= 6; ++x) { 
          // write x {spacenew line}
          os << x << ' ' << (x*x) << '\n';
        }
      }
    }  // file is automatically closed

    Read Text File Reading

    with  std::ifstream  (input file stream)
    #include <fstream>  // file stream header
    
    int main() {
      std::ifstream is {"squares.txt"};  // open file
    
      // if stream OK = file readable
      if( is.good() ) {
        double x, y;
        // as long as any 2 values readable
        while( is >> x >> y ) {
          // print pairs (x,y) 
          cout << x << "² = " << y << "\n"; 
        }
      }
    }  // file is automatically closed

    Open/Close Files Open/Close

    File Open Modes Open Modes

    • ifstream is {"in.txt", ios::in};
    • ofstream os {"out.txt", ios::out};   (overwrite existing file)
    • ofstream os {"log.txt", ios::app};
    • ifstream is {"in.jpg", ios::binary};
    • ofstream os {"out.jpg", ios::binary};
    // we'll learn later what all this means…
    std::uint64_t i = 0;
    // read binary
    is.read(reinterpret_cast<char*>(i), sizeof(i));
    // write binary
    os.write(reinterpret_cast<char const*>(i), sizeof(i));