Reputation: 69
Can anybody explain how this while condition works while accessing files in C++. In the while condition, employeeLine
is a string.
while ( !inFile.getline( employeeLine, MAX_LINE, ‘\n’ ).eof( ) )
{
//some code here
}
If the file contains data like this then will the code process the last line data or not as there is no newline character
Tomb33bb9.75<\n>
bbMarybb26bb10.15 (eof)
Upvotes: 0
Views: 1574
Reputation: 154025
First of, inFile.getline(...)
return the stream, i.e., a reference to inFile
. When the stream reaches the end of file, the flag std::ios_base::eofbit
gets set and inFile.eof()
returns true
. While there is any input, this flag won't be set. If the last line is incomplete, i.e., is lacking a newline character, it won't be processed!
Note, however, that the end of file may not necessarily be reached: if something goes wrong, std::ios_base::failbit
is set and the stream won't response to any further attempts to read something: you'd have an infinite loop. std::istream::getline()
does set std::ios_base::failbit
when the line is too long to fit into the buffer (i.e., there are more than MAX_LINE - 1
characters). Another potential situation where the stream may go into failure mode without setting std::ios_base::eofbit
is when an exception is thrown from the used stream buffer.
In general a better approach is to rely on the conversion to bool
for a stream, i.e., to use
while (inFile.getline(employeeLine, MAX_LINE)) {
// ...
}
There is no need to pass '\n'
as last parameter as it is the default. There is also no harm.
Note, that the above code won't deal with lines longer than MAX_LINE
. That may be intentional, e.g., to avoid a denial of service attack based on infinitely large lines. Typically, it is preferable to use std::string
, however:
for (std::string line; std::getline(inFile, line); ) {
// ...
}
Upvotes: 3