Liste des Groupes | Revenir à l c |
On Sat 2/8/2025 9:59 PM, Janis Papanagnou wrote:To get the last line of a text file I'm using
>
char buf[BUFSIZ];
while (fgets (buf, BUFSIZ, fd) != NULL)
; // read to last line
>
If the end of the file is reached my test shows that the previous
contents of 'buf' are still existing (not cleared or overwritten).
>
But the man page does not say anything whether this is guaranteed;
it says: "Reading stops after an EOF or a newline.", but it says
nothing about [not] writing to or [not] resetting the buffer.
>
Is that simple construct safe to get the last line of a text file?
>
What situation exactly are you talking about? When end-of-file is
encountered _immediately_, before reading the very first character? Of
when end-of-file is encountered after reading something (i.e. when the
last line in the file does not end with new-line character)?
The former situation is covered by the spec: "If end-of-file is
encountered and no characters have been read into the array, the
contents of the array remain unchanged and a null pointer is returned".
The second situation does not need additional clarifications. Per
general spec as many characters as available before the end-of-file will
be read and then terminated with '\0'. In such case there will be no
new-line character in the buffer.
So, in both cases we are perfectly safe when reading the last line of a
text file, if you don't forget to check the return value of `fgets`.
(This is all under assumption that size limit does not kick in. I
believe your question is not about that.)
Note also that `fgets` is not permitted to assume that the limit value
(the second parameter) correctly describes the accessible size of the
buffer. E.g. for this reason it is not permitted to zero-out the buffer
before reading. For example, this code is valid and has defined behavior
char buffer[10];
fgets(buffer, 1000, f);
provided the current line of the file fits into `char[10]`. I.e. even
though we "lied" to `fgets` about the limit, it is still required to
work correctly if the actual data fits into the actual buffer.
So, why do you care that "the previous contents of 'buf' are still
existing"?
Les messages affichés proviennent d'usenet.