# C++ std::fstream state flags cheat sheet

Out stream - no file is open:

Out stream - file open but not read/written:

Out stream - file opened and then closed:

Out stream - invalid filename:

In/Out stream - file open but not read/written:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58  #include #include void print_state(const std::ios& stream) { std::cout << " good()=" << stream.good(); std::cout << " eof()=" << stream.eof(); std::cout << " fail()=" << stream.fail(); std::cout << " bad()=" << stream.bad(); std::cout << std::endl; } int main() { std::cout << "Out stream - no file open " << std::endl; std::ofstream outfile_nofile; std::cout << " is_open()=" << outfile_nofile.is_open(); print_state(outfile_nofile); std::cout << "Out stream - no reads"<< std::endl; std::ofstream outfile( "myfile.txt", std::ios_base::out, std::ios_base::trunc ); std::cout << " is_open()=" << outfile.is_open(); print_state(outfile); outfile.close(); std::cout << "Out stream - open and then closed" << std::endl; std::cout << " is_open()=" << outfile.is_open(); print_state(outfile); std::cout << "Out stream - invalid char-dir in filename" << std::endl; std::ofstream outfile_inv( "myinexistantedir/myfile.txt", std::ios_base::out | std::ios_base::trunc ); std::cout << " is_open()=" << outfile_inv.is_open(); print_state(outfile_inv); std::cout << "In/Out stream - no reads but no chars left either" << std::endl; std::fstream inoutfile( "myfile2.txt", std::ios_base::out | std::ios_base::out | std::ios_base::trunc ); std::cout << " is_open()=" << inoutfile.is_open(); print_state(inoutfile); std::cout << "In/Out stream - trying to read a char" << std::endl; char inchar; inoutfile.get(inchar); std::cout << " is_open()=" << inoutfile.is_open(); print_state(inoutfile); inoutfile.close(); }