diff --git a/libio/fileops.c b/libio/fileops.c
index 9348d7c3a1..a614e7c528 100644
--- a/libio/fileops.c
+++ b/libio/fileops.c
@@ -1290,15 +1290,11 @@ _IO_new_file_xsputn (FILE *f, const void *data, size_t n)
       count = f->_IO_buf_end - f->_IO_write_ptr;
       if (count >= n)
 	{
-	  const char *p;
-	  for (p = s + n; p > s; )
+	  const char *p = memrchr (s, '\n', n);
+	  if (p != NULL)
 	    {
-	      if (*--p == '\n')
-		{
-		  count = p - s + 1;
-		  must_flush = 1;
-		  break;
-		}
+ 	      count = p - s + 1;
+	      must_flush = 1;
 	    }
 	}
     }
