C++ I/O

File I/O

Read and write files with fstream
#include <fstream>
#include <string>

// Write to file
std::ofstream out("output.txt");
if (out.is_open()) {
    out << "line 1" << std::endl;
    out << "line 2" << std::endl;
}  // RAII — file closed on scope exit

// Read entire file
std::ifstream in("input.txt");
std::string content(
    (std::istreambuf_iterator<char>(in)),
    std::istreambuf_iterator<char>()
);

// Read line by line
std::ifstream file("/etc/hosts");
std::string line;
while (std::getline(file, line)) {
    if (!line.empty() && line[0] != '#') {
        std::cout << line << std::endl;
    }
}

File streams use RAII — the destructor closes the file. No need for explicit close() unless you need to check for write errors.

String Streams

Parse strings as streams
#include <sstream>

// Parse a line into fields
std::string data = "10.50.1.10 22 ssh";
std::istringstream iss(data);
std::string ip, service;
int port;
iss >> ip >> port >> service;

// Build a string
std::ostringstream oss;
oss << "Host: " << ip << " Port: " << port;
std::string result = oss.str();

String streams are useful for parsing and formatting when you need stream-style operations on strings.

Error Handling in I/O

Check stream state
std::ifstream file("config.txt");
if (!file) {
    std::cerr << "Failed to open config.txt" << std::endl;
    return 1;
}

// Check after reading
int value;
if (file >> value) {
    std::cout << "Read: " << value << std::endl;
} else {
    std::cerr << "Parse error" << std::endl;
}

// Throw on errors
file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
    file >> value;
} catch (const std::ios_base::failure& e) {
    std::cerr << "I/O error: " << e.what() << std::endl;
}

Command-Line Arguments

argc/argv and modern alternatives
// Traditional
int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <host>" << std::endl;
        return 1;
    }
    std::string host = argv[1];

    // Convert to vector for easier handling
    std::vector<std::string> args(argv, argv + argc);
    for (const auto& arg : args) {
        std::cout << arg << std::endl;
    }
    return 0;
}

For real CLI argument parsing, use a library like CLI11 or Boost.Program_options rather than hand-rolling argc/argv parsing.