// stringstream example // // This program contains a function to determine the size of a file. // If the file can’t be opened, the function throws a std::string // that describes the problem. It uses a stringstream to construct // a useful error message, in accordance with Heckendorn’s Law. // // Can you spot the flaws in this program? // The flaws are (ROT13): // • Jul fubhyq /rgp/funqbj orvat vanpprffvoyr cerirag gur /rgp/ubfgf qngn? // • reeab zvtug punatr orsber jr hfr vg #include // for errno #include // for strerror #include // for ifstream #include // for cout, cerr #include // for ostringstream using namespace std; // Return the size of the given file, or throw a std::string // that explains why we couldn’t. // // Could more easily construct the error string just using +, // but I’m using ostringstream for pedagogical purposes. int size(const string &filename) { if (ifstream in{filename}) return in.seekg(0,in.end).tellg(); // size of file else { // Couldn’t open the file. Why? ostringstream oss; oss << "can’t open " << filename << ": " << strerror(errno); throw oss.str(); } } int main() { try { // Why isn’t this just one giant cout expression? cout << "/bin/sync is " << size("/bin/sync") << " bytes.\n"; cout << "/etc/shadow is " << size("/etc/shadow") << " bytes.\n"; cout << "/etc/hosts is " << size("/etc/hosts") << " bytes.\n"; } catch (const string &complaint) { cerr << complaint << '\n'; return 1; } return 0; }