* lib/stdio_.h [REPLACE_FFLUSH]: Declare rpl_fflush.
[gnulib.git] / m4 / fflush.m4
1 #serial 1
2
3 # Copyright (C) 2007 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, rather than C99 undefined semantics.  fpurge is not
12 dnl standardized, but has the desired properties.
13
14 AC_DEFUN([gl_FUNC_FFLUSH],
15 [
16   AC_CACHE_CHECK([whether fflush works on input streams],
17     [gl_cv_func_fflush_stdin],
18     [echo hello world > conftest.txt
19      AC_RUN_IFELSE([AC_LANG_PROGRAM(
20        [[
21 #include <stdio.h>
22 #include <unistd.h>
23        ]], [[FILE *f = fopen ("conftest.txt", "r");
24          char buffer[10];
25          int fd = fileno (f);
26          if (!f || 0 > fd || fread (buffer, 1, 5, f) != 5)
27            return 2;
28          /* For deterministic results, ensure f read a bigger buffer.  */
29          if (lseek (fd, 0, SEEK_CUR) == 5)
30            return 3;
31          /* POSIX requires fflush-fseek to set file offset of fd.  */
32          if (fflush (f) != 0 || fseek (f, 0, SEEK_CUR) != 0)
33            return 4;
34          return !(lseek (fd, 0, SEEK_CUR) == 5);
35        ]])], [gl_cv_func_fflush_stdin=yes], [gl_cv_func_fflush_stdin=no],
36      [dnl Pessimistically assume fflush is broken.  This is wrong for
37       dnl at least glibc and cygwin; but lib/fflush.c takes this into account.
38       gl_cv_func_fflush_stdin=no])
39      rm conftest.txt
40     ])
41   if test $gl_cv_func_fflush_stdin = no; then
42     gl_REPLACE_FFLUSH
43   fi
44 ])
45
46 AC_DEFUN([gl_REPLACE_FFLUSH],
47 [
48   AC_CHECK_HEADERS_ONCE([stdio_ext.h])
49   AC_CHECK_FUNCS_ONCE([fpurge __fpurge])
50 dnl Linux documents int fpurge(), but only declares void __fpurge().
51   AC_CHECK_DECLS([fpurge], [], [], [[
52 #include <stdio.h>
53 #if HAVE_STDIO_EXT_H
54 # include <stdio_ext.h>
55 #endif
56 ]])
57   AC_LIBOBJ([fflush])
58   AC_REQUIRE([gl_STDIO_H_DEFAULTS])
59   REPLACE_FFLUSH=1
60 ])