Your code fragment need not be syntactically correct C++ code, however it should recognizable as quasi-C++ code without too much work. In particular, the functions called, the arguments used, and the actions taken should be clearly evident in your code fragment. If you don't understand this paragraph, just express your answer in syntactically correct C++ code.
If we assume the file pointer for ins
is pointing to the last byte in the
file, the following code fragment will do the job:
// Move the file pointer to just after the last byte ins.read(data, 1) cerr << "ins.eof() = " if (ins.eof()) cerr << "true" else cerr << "false" cerr << ".\n" // Read the non-existent next byte, detecting the eof condition. ins.read(data, 1) cerr << "ins.eof() = " if (ins.eof()) cerr << "true" else cerr << "false" cerr << ".\n"
ins.eof()
returns false in this
case. The second read detects and sets the eof condition, and ins.eof()
returns true.
For completeness, here's the whole demonstration program
#include <fstream> #include <cstdlib> #include <string> int main() { const string fname = "/tmp/junk"; // Create a one-byte file: open the file for writing. ofstream outs; outs.open(fname.c_str()); if (!outs.good()) { cerr << "Can't open " << fname << ".\n"; exit(EXIT_FAILURE); } // Write one byte and close the file. char data[1] = { 0 }; outs.write(data, 1); if (!outs.good()) { cerr << "Can't write " << fname << ".\n"; exit(EXIT_FAILURE); } outs.close(); // Open the one-byte file for reading. ifstream ins; ins.open(fname.c_str()); if (!ins.good()) { cerr << "Can't open " << fname << ".\n"; exit(EXIT_FAILURE); } // Read the one byte and report the eof condition. ins.read(data, 1); cerr << "ins.eof() = "; if (ins.eof()) cerr << "true"; else cerr << "false"; cerr << ".\n"; // Read the non-existent byte and report the eof condition in an alternative // way. ins.read(data, 1); cerr << "ins.eof() = " << (ins.eof() ? "true" : "false") << ".\n"; // That's it. ins.close(); }
$ g++ -o q3ans -ansi -pedantic -Wall q3ans.cc $ q3ans ins.eof() = false. ins.eof() = true. $
This page last modified on 27 July 2001.