I came across the following program in TCPPPL by Stroustrup:
int main()
{
string from, to;
cin >> from >> to; // get source and target file names
ifstream is {from}; // input stream for file "from"
istream_iterator<string> ii {is}; // input iterator for stream
istream_iterator<string> eos {}; // input sentinel
ofstream os{to}; // output stream for file "to"
ostream_iterator<string> oo {os,"\n"}; // output iterator for stream
vector<string> b {ii,eos}; // b is a vector initialized from input [ii:eos)
sort(b.begin(),b.end()); // sor t the buffer
unique_copy(b.begin(),b.end(),oo);// copy buffer to output, discard //replicated values
return !is.eof() || !os; // return error state (§2.2.1, §38.3)
}
My questions is what is the last line, i.e. return !is.eof() ||!os;
doing. I know that if main returns non-zero value then it means an error but what is being returned here?
!is.eof()
returns whether you aren't at the end of the file you are reading (so true
for not being at the end and false
for being at the end) and
!os
returns whether or not your output file is not writable. In other words, this program returns:
true
for when you haven't reached the end of your input file (regardless of 2.)true
for when the output file is not writable (regardless of 1.)false
for when you are at the end of the file and the output file is writable.