ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) writes:
[...]
The C standard *allows* implementations to not produce the last
line of a text stream when the last line is not terminated with \n .
This is the case whether or not the stream is fflush()'d, and
is the case whether or not the stream is explicitly close()'d.
I don't think the C standard is even that specific.
C99 7.19.2p2 says:
A text stream is an ordered sequence of characters composed into
_lines_, each line consisting of zero or more characters plus a
terminating new-line character. Whether the last line requires a
terminating new-line character is implementation-defined.
As far as I can tell, the standard gives no hint about what happens if
the last line "requires" a terminating new-line and the program
doesn't provide one. The worst thing that's *likely* happen on most
implementations is that the last line doesn't appear, but I think it's
actually undefined behavior. I can imagine scenarios where you'd get
only part of the last line, or even where the resulting text file is
malformed. (Think about systems where a text file is represented as a
sequence of records rather than as a stream of characters.)
The standard *could* have nailed this down more precisely. For
example, it could have said something like this:
... Whether the last line requires a terminating new-line
character is implementation-defined. If it does, closing the file
writes a new-line to the stream if the last character written to
the stream was not a new-line.
This would allow a text file with no terminating new-line to be
created on systems that don't require it, while guaranteeing (barring
errors) a properly terminated file on systems that do require it.
In fact, I'd be (mildly) surprised if there were any real-world
implementations that don't already follow this suggested requirement.
But since it's not in the standard, we can't depend on it if we want
maximally portable code.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.