Author: gbe (doc committer)
Date: Thu Jun 18 13:13:04 2020
New Revision: 362326
URL: https://svnweb.freebsd.org/changeset/base/362326

Log:
  fgetln(3): Add a Caveats Section
  
  Reviewed by:  yuripv, bcr (mentor)
  Approved by:  bcr (mentror)
  Obtained from:        OpenBSD
  MFC after:    7 days
  Differential Revision:        https://reviews.freebsd.org/D24916

Modified:
  head/lib/libc/stdio/fgetln.3

Modified: head/lib/libc/stdio/fgetln.3
==============================================================================
--- head/lib/libc/stdio/fgetln.3        Thu Jun 18 12:29:24 2020        
(r362325)
+++ head/lib/libc/stdio/fgetln.3        Thu Jun 18 13:13:04 2020        
(r362326)
@@ -28,7 +28,7 @@
 .\"     @(#)fgetln.3   8.3 (Berkeley) 4/19/94
 .\" $FreeBSD$
 .\"
-.Dd February 15, 2016
+.Dd June 11, 2020
 .Dt FGETLN 3
 .Os
 .Sh NAME
@@ -126,3 +126,33 @@ The
 .Fn fgetln
 function first appeared in
 .Bx 4.4 .
+.Sh CAVEATS
+Since the returned buffer is not a C string (it is not NUL terminated), a
+common practice is to replace the newline character with
+.Sq \e0 .
+However, if the last line in a file does not contain a newline,
+the returned text won't contain a newline either.
+The following code demonstrates how to deal with this problem by allocating a
+temporary buffer:
+.Bd -literal
+       char *buf, *lbuf;
+       size_t len;
+
+       lbuf = NULL;
+       while ((buf = fgetln(fp, &len)) != NULL) {
+               if (buf[len - 1] == '\en')
+                       buf[len - 1] = '\e0';
+               else {
+                       /* EOF without EOL, copy and add the NUL */
+                       if ((lbuf = malloc(len + 1)) == NULL)
+                               err(1, NULL);
+                       memcpy(lbuf, buf, len);
+                       lbuf[len] = '\e0';
+                       buf = lbuf;
+               }
+               printf("%s\en", buf);
+       }
+       free(lbuf);
+       if (ferror(fp))
+               err(1, "fgetln");
+.Ed
_______________________________________________
[email protected] mailing list
https://lists.freebsd.org/mailman/listinfo/svn-src-head
To unsubscribe, send any mail to "[email protected]"

Reply via email to