97f12843d4f1f111580cf616d0ac1b6afed3c0ef
[gnulib.git] / m4 / fflush.m4
1 # fflush.m4 serial 6
2
3 # Copyright (C) 2007-2008 Free Software Foundation, Inc.
4 # This file is free software; the Free Software Foundation
5 # gives unlimited permission to copy and/or distribute it,
6 # with or without modifications, as long as this notice is preserved.
7
8 dnl From Eric Blake
9
10 dnl Find out how to obey POSIX semantics of fflush(stdin) discarding
11 dnl unread input on seekable streams, rather than C99 undefined semantics.
12
13 AC_DEFUN([gl_FUNC_FFLUSH],
14 [
15   AC_CACHE_CHECK([whether fflush works on input streams],
16     [gl_cv_func_fflush_stdin],
17     [echo hello world > conftest.txt
18      AC_RUN_IFELSE([AC_LANG_PROGRAM(
19        [[
20 #include <stdio.h>
21 #include <unistd.h>
22        ]], [[FILE *f = fopen ("conftest.txt", "r");
23          char buffer[10];
24          int fd;
25          if (f == NULL)
26            return 1;
27          fd = fileno (f);
28          if (fd < 0 || fread (buffer, 1, 5, f) != 5)
29            return 2;
30          /* For deterministic results, ensure f read a bigger buffer.  */
31          if (lseek (fd, 0, SEEK_CUR) == 5)
32            return 3;
33          /* POSIX requires fflush-fseek to set file offset of fd.  */
34          if (fflush (f) != 0 || fseek (f, 0, SEEK_CUR) != 0)
35            return 4;
36          if (lseek (fd, 0, SEEK_CUR) != 5)
37            return 5;
38          /* TODO: Verify behaviour of fflush after ungetc, see
39             <http://lists.gnu.org/archive/html/bug-gnulib/2008-03/msg00131.html>.  */
40          return 0;
41        ]])], [gl_cv_func_fflush_stdin=yes], [gl_cv_func_fflush_stdin=no],
42      [dnl Pessimistically assume fflush is broken.  This is wrong for
43       dnl at least glibc and cygwin; but lib/fflush.c takes this into account.
44       gl_cv_func_fflush_stdin=no])
45      rm conftest.txt
46     ])
47   if test $gl_cv_func_fflush_stdin = no; then
48     gl_REPLACE_FFLUSH
49   fi
50 ])
51
52 AC_DEFUN([gl_REPLACE_FFLUSH],
53 [
54   AC_LIBOBJ([fflush])
55   AC_LIBOBJ([fseeko])
56   AC_REQUIRE([gl_STDIO_H_DEFAULTS])
57   REPLACE_FFLUSH=1
58   REPLACE_FSEEKO=1
59   gl_PREREQ_FFLUSH
60 ])
61
62 # Prerequisites of lib/fflush.c.
63 AC_DEFUN([gl_PREREQ_FFLUSH],
64 [
65   AC_REQUIRE([AC_C_INLINE])
66   :
67 ])