Beginner's Guide
    First Steps
    Input & Output
    Custom Types – Part 1
    Diagnostics
    Standard Library – Part 1
    Function Objects
    Standard Library – Part 2
    Code Organization
    Custom Types – Part 2
    Generic Programming
    Memory Management
    Software Design Basics

    File Input & Output File I/O File 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()) {
        for (int x = 1; x <= 6; ++x) { 
          // write x spacenewline
          os << x << ' ' << (x*x) << '\n';
        }
      }
    }  // file is automatically closed

    Read Text File Reading

    with  std::ifstream  (input file stream)
    #include <iostream>
    #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));
    #include <iostream>
    #include <fstream>
    #include <cstdint>
    
    int main (int argc, char* argv[]) {
        if (argc < 3) {
            std::cerr << "usage: " << argv[0] << " <integer> <filename>\n";
            return 0;
        }
        std::string filename {argv[2]};
        {   // write binary
            std::uint64_t i = atoi(argv[1]);
            std::cout << "writing: " << i << " to " << filename << "\n";
            std::ofstream os {filename, std::ios::binary};
            if (os.good()) {
                os.write(reinterpret_cast<char const*>(&i), sizeof(i));
            }
        }
        {   // read binary
            std::uint64_t i = 0;
            std::ifstream is {filename, std::ios::binary};
            if (is.good()) {
                is.read(reinterpret_cast<char*>(&i), sizeof(i));
                std::cout << "read as: " << i << "\n";
            }
        }
    }