This is libc.info, produced by makeinfo version 5.2 from libc.texinfo.
|
|
This file documents the GNU C Library.
|
|
This is ‘The GNU C Library Reference Manual’, for version 2.25.
|
|
Copyright © 1993–2017 Free Software Foundation, Inc.
|
|
Permission is granted to copy, distribute and/or modify this document
|
under the terms of the GNU Free Documentation License, Version 1.3 or
|
any later version published by the Free Software Foundation; with the
|
Invariant Sections being “Free Software Needs Free Documentation” and
|
“GNU Lesser General Public License”, the Front-Cover texts being “A GNU
|
Manual”, and with the Back-Cover Texts as in (a) below. A copy of the
|
license is included in the section entitled "GNU Free Documentation
|
License".
|
|
(a) The FSF’s Back-Cover Text is: “You have the freedom to copy and
|
modify this GNU manual. Buying copies from the FSF supports it in
|
developing GNU and promoting software freedom.”
|
INFO-DIR-SECTION Software libraries
|
START-INFO-DIR-ENTRY
|
* Libc: (libc). C library.
|
END-INFO-DIR-ENTRY
|
|
INFO-DIR-SECTION GNU C library functions and macros
|
START-INFO-DIR-ENTRY
|
* ALTWERASE: (libc)Local Modes.
|
* ARGP_ERR_UNKNOWN: (libc)Argp Parser Functions.
|
* ARG_MAX: (libc)General Limits.
|
* BC_BASE_MAX: (libc)Utility Limits.
|
* BC_DIM_MAX: (libc)Utility Limits.
|
* BC_SCALE_MAX: (libc)Utility Limits.
|
* BC_STRING_MAX: (libc)Utility Limits.
|
* BRKINT: (libc)Input Modes.
|
* BUFSIZ: (libc)Controlling Buffering.
|
* CCTS_OFLOW: (libc)Control Modes.
|
* CHILD_MAX: (libc)General Limits.
|
* CIGNORE: (libc)Control Modes.
|
* CLK_TCK: (libc)Processor Time.
|
* CLOCAL: (libc)Control Modes.
|
* CLOCKS_PER_SEC: (libc)CPU Time.
|
* COLL_WEIGHTS_MAX: (libc)Utility Limits.
|
* CPU_CLR: (libc)CPU Affinity.
|
* CPU_ISSET: (libc)CPU Affinity.
|
* CPU_SET: (libc)CPU Affinity.
|
* CPU_SETSIZE: (libc)CPU Affinity.
|
* CPU_ZERO: (libc)CPU Affinity.
|
* CREAD: (libc)Control Modes.
|
* CRTS_IFLOW: (libc)Control Modes.
|
* CS5: (libc)Control Modes.
|
* CS6: (libc)Control Modes.
|
* CS7: (libc)Control Modes.
|
* CS8: (libc)Control Modes.
|
* CSIZE: (libc)Control Modes.
|
* CSTOPB: (libc)Control Modes.
|
* DES_FAILED: (libc)DES Encryption.
|
* DTTOIF: (libc)Directory Entries.
|
* E2BIG: (libc)Error Codes.
|
* EACCES: (libc)Error Codes.
|
* EADDRINUSE: (libc)Error Codes.
|
* EADDRNOTAVAIL: (libc)Error Codes.
|
* EADV: (libc)Error Codes.
|
* EAFNOSUPPORT: (libc)Error Codes.
|
* EAGAIN: (libc)Error Codes.
|
* EALREADY: (libc)Error Codes.
|
* EAUTH: (libc)Error Codes.
|
* EBACKGROUND: (libc)Error Codes.
|
* EBADE: (libc)Error Codes.
|
* EBADF: (libc)Error Codes.
|
* EBADFD: (libc)Error Codes.
|
* EBADMSG: (libc)Error Codes.
|
* EBADR: (libc)Error Codes.
|
* EBADRPC: (libc)Error Codes.
|
* EBADRQC: (libc)Error Codes.
|
* EBADSLT: (libc)Error Codes.
|
* EBFONT: (libc)Error Codes.
|
* EBUSY: (libc)Error Codes.
|
* ECANCELED: (libc)Error Codes.
|
* ECHILD: (libc)Error Codes.
|
* ECHO: (libc)Local Modes.
|
* ECHOCTL: (libc)Local Modes.
|
* ECHOE: (libc)Local Modes.
|
* ECHOK: (libc)Local Modes.
|
* ECHOKE: (libc)Local Modes.
|
* ECHONL: (libc)Local Modes.
|
* ECHOPRT: (libc)Local Modes.
|
* ECHRNG: (libc)Error Codes.
|
* ECOMM: (libc)Error Codes.
|
* ECONNABORTED: (libc)Error Codes.
|
* ECONNREFUSED: (libc)Error Codes.
|
* ECONNRESET: (libc)Error Codes.
|
* ED: (libc)Error Codes.
|
* EDEADLK: (libc)Error Codes.
|
* EDEADLOCK: (libc)Error Codes.
|
* EDESTADDRREQ: (libc)Error Codes.
|
* EDIED: (libc)Error Codes.
|
* EDOM: (libc)Error Codes.
|
* EDOTDOT: (libc)Error Codes.
|
* EDQUOT: (libc)Error Codes.
|
* EEXIST: (libc)Error Codes.
|
* EFAULT: (libc)Error Codes.
|
* EFBIG: (libc)Error Codes.
|
* EFTYPE: (libc)Error Codes.
|
* EGRATUITOUS: (libc)Error Codes.
|
* EGREGIOUS: (libc)Error Codes.
|
* EHOSTDOWN: (libc)Error Codes.
|
* EHOSTUNREACH: (libc)Error Codes.
|
* EHWPOISON: (libc)Error Codes.
|
* EIDRM: (libc)Error Codes.
|
* EIEIO: (libc)Error Codes.
|
* EILSEQ: (libc)Error Codes.
|
* EINPROGRESS: (libc)Error Codes.
|
* EINTR: (libc)Error Codes.
|
* EINVAL: (libc)Error Codes.
|
* EIO: (libc)Error Codes.
|
* EISCONN: (libc)Error Codes.
|
* EISDIR: (libc)Error Codes.
|
* EISNAM: (libc)Error Codes.
|
* EKEYEXPIRED: (libc)Error Codes.
|
* EKEYREJECTED: (libc)Error Codes.
|
* EKEYREVOKED: (libc)Error Codes.
|
* EL2HLT: (libc)Error Codes.
|
* EL2NSYNC: (libc)Error Codes.
|
* EL3HLT: (libc)Error Codes.
|
* EL3RST: (libc)Error Codes.
|
* ELIBACC: (libc)Error Codes.
|
* ELIBBAD: (libc)Error Codes.
|
* ELIBEXEC: (libc)Error Codes.
|
* ELIBMAX: (libc)Error Codes.
|
* ELIBSCN: (libc)Error Codes.
|
* ELNRNG: (libc)Error Codes.
|
* ELOOP: (libc)Error Codes.
|
* EMEDIUMTYPE: (libc)Error Codes.
|
* EMFILE: (libc)Error Codes.
|
* EMLINK: (libc)Error Codes.
|
* EMSGSIZE: (libc)Error Codes.
|
* EMULTIHOP: (libc)Error Codes.
|
* ENAMETOOLONG: (libc)Error Codes.
|
* ENAVAIL: (libc)Error Codes.
|
* ENEEDAUTH: (libc)Error Codes.
|
* ENETDOWN: (libc)Error Codes.
|
* ENETRESET: (libc)Error Codes.
|
* ENETUNREACH: (libc)Error Codes.
|
* ENFILE: (libc)Error Codes.
|
* ENOANO: (libc)Error Codes.
|
* ENOBUFS: (libc)Error Codes.
|
* ENOCSI: (libc)Error Codes.
|
* ENODATA: (libc)Error Codes.
|
* ENODEV: (libc)Error Codes.
|
* ENOENT: (libc)Error Codes.
|
* ENOEXEC: (libc)Error Codes.
|
* ENOKEY: (libc)Error Codes.
|
* ENOLCK: (libc)Error Codes.
|
* ENOLINK: (libc)Error Codes.
|
* ENOMEDIUM: (libc)Error Codes.
|
* ENOMEM: (libc)Error Codes.
|
* ENOMSG: (libc)Error Codes.
|
* ENONET: (libc)Error Codes.
|
* ENOPKG: (libc)Error Codes.
|
* ENOPROTOOPT: (libc)Error Codes.
|
* ENOSPC: (libc)Error Codes.
|
* ENOSR: (libc)Error Codes.
|
* ENOSTR: (libc)Error Codes.
|
* ENOSYS: (libc)Error Codes.
|
* ENOTBLK: (libc)Error Codes.
|
* ENOTCONN: (libc)Error Codes.
|
* ENOTDIR: (libc)Error Codes.
|
* ENOTEMPTY: (libc)Error Codes.
|
* ENOTNAM: (libc)Error Codes.
|
* ENOTRECOVERABLE: (libc)Error Codes.
|
* ENOTSOCK: (libc)Error Codes.
|
* ENOTSUP: (libc)Error Codes.
|
* ENOTTY: (libc)Error Codes.
|
* ENOTUNIQ: (libc)Error Codes.
|
* ENXIO: (libc)Error Codes.
|
* EOF: (libc)EOF and Errors.
|
* EOPNOTSUPP: (libc)Error Codes.
|
* EOVERFLOW: (libc)Error Codes.
|
* EOWNERDEAD: (libc)Error Codes.
|
* EPERM: (libc)Error Codes.
|
* EPFNOSUPPORT: (libc)Error Codes.
|
* EPIPE: (libc)Error Codes.
|
* EPROCLIM: (libc)Error Codes.
|
* EPROCUNAVAIL: (libc)Error Codes.
|
* EPROGMISMATCH: (libc)Error Codes.
|
* EPROGUNAVAIL: (libc)Error Codes.
|
* EPROTO: (libc)Error Codes.
|
* EPROTONOSUPPORT: (libc)Error Codes.
|
* EPROTOTYPE: (libc)Error Codes.
|
* EQUIV_CLASS_MAX: (libc)Utility Limits.
|
* ERANGE: (libc)Error Codes.
|
* EREMCHG: (libc)Error Codes.
|
* EREMOTE: (libc)Error Codes.
|
* EREMOTEIO: (libc)Error Codes.
|
* ERESTART: (libc)Error Codes.
|
* ERFKILL: (libc)Error Codes.
|
* EROFS: (libc)Error Codes.
|
* ERPCMISMATCH: (libc)Error Codes.
|
* ESHUTDOWN: (libc)Error Codes.
|
* ESOCKTNOSUPPORT: (libc)Error Codes.
|
* ESPIPE: (libc)Error Codes.
|
* ESRCH: (libc)Error Codes.
|
* ESRMNT: (libc)Error Codes.
|
* ESTALE: (libc)Error Codes.
|
* ESTRPIPE: (libc)Error Codes.
|
* ETIME: (libc)Error Codes.
|
* ETIMEDOUT: (libc)Error Codes.
|
* ETOOMANYREFS: (libc)Error Codes.
|
* ETXTBSY: (libc)Error Codes.
|
* EUCLEAN: (libc)Error Codes.
|
* EUNATCH: (libc)Error Codes.
|
* EUSERS: (libc)Error Codes.
|
* EWOULDBLOCK: (libc)Error Codes.
|
* EXDEV: (libc)Error Codes.
|
* EXFULL: (libc)Error Codes.
|
* EXIT_FAILURE: (libc)Exit Status.
|
* EXIT_SUCCESS: (libc)Exit Status.
|
* EXPR_NEST_MAX: (libc)Utility Limits.
|
* FD_CLOEXEC: (libc)Descriptor Flags.
|
* FD_CLR: (libc)Waiting for I/O.
|
* FD_ISSET: (libc)Waiting for I/O.
|
* FD_SET: (libc)Waiting for I/O.
|
* FD_SETSIZE: (libc)Waiting for I/O.
|
* FD_ZERO: (libc)Waiting for I/O.
|
* FE_SNANS_ALWAYS_SIGNAL: (libc)Infinity and NaN.
|
* FILENAME_MAX: (libc)Limits for Files.
|
* FLUSHO: (libc)Local Modes.
|
* FOPEN_MAX: (libc)Opening Streams.
|
* FP_ILOGB0: (libc)Exponents and Logarithms.
|
* FP_ILOGBNAN: (libc)Exponents and Logarithms.
|
* FP_LLOGB0: (libc)Exponents and Logarithms.
|
* FP_LLOGBNAN: (libc)Exponents and Logarithms.
|
* F_DUPFD: (libc)Duplicating Descriptors.
|
* F_GETFD: (libc)Descriptor Flags.
|
* F_GETFL: (libc)Getting File Status Flags.
|
* F_GETLK: (libc)File Locks.
|
* F_GETOWN: (libc)Interrupt Input.
|
* F_OFD_GETLK: (libc)Open File Description Locks.
|
* F_OFD_SETLK: (libc)Open File Description Locks.
|
* F_OFD_SETLKW: (libc)Open File Description Locks.
|
* F_OK: (libc)Testing File Access.
|
* F_SETFD: (libc)Descriptor Flags.
|
* F_SETFL: (libc)Getting File Status Flags.
|
* F_SETLK: (libc)File Locks.
|
* F_SETLKW: (libc)File Locks.
|
* F_SETOWN: (libc)Interrupt Input.
|
* HUGE_VAL: (libc)Math Error Reporting.
|
* HUGE_VALF: (libc)Math Error Reporting.
|
* HUGE_VALL: (libc)Math Error Reporting.
|
* HUPCL: (libc)Control Modes.
|
* I: (libc)Complex Numbers.
|
* ICANON: (libc)Local Modes.
|
* ICRNL: (libc)Input Modes.
|
* IEXTEN: (libc)Local Modes.
|
* IFNAMSIZ: (libc)Interface Naming.
|
* IFTODT: (libc)Directory Entries.
|
* IGNBRK: (libc)Input Modes.
|
* IGNCR: (libc)Input Modes.
|
* IGNPAR: (libc)Input Modes.
|
* IMAXBEL: (libc)Input Modes.
|
* INADDR_ANY: (libc)Host Address Data Type.
|
* INADDR_BROADCAST: (libc)Host Address Data Type.
|
* INADDR_LOOPBACK: (libc)Host Address Data Type.
|
* INADDR_NONE: (libc)Host Address Data Type.
|
* INFINITY: (libc)Infinity and NaN.
|
* INLCR: (libc)Input Modes.
|
* INPCK: (libc)Input Modes.
|
* IPPORT_RESERVED: (libc)Ports.
|
* IPPORT_USERRESERVED: (libc)Ports.
|
* ISIG: (libc)Local Modes.
|
* ISTRIP: (libc)Input Modes.
|
* IXANY: (libc)Input Modes.
|
* IXOFF: (libc)Input Modes.
|
* IXON: (libc)Input Modes.
|
* LINE_MAX: (libc)Utility Limits.
|
* LINK_MAX: (libc)Limits for Files.
|
* L_ctermid: (libc)Identifying the Terminal.
|
* L_cuserid: (libc)Who Logged In.
|
* L_tmpnam: (libc)Temporary Files.
|
* MAXNAMLEN: (libc)Limits for Files.
|
* MAXSYMLINKS: (libc)Symbolic Links.
|
* MAX_CANON: (libc)Limits for Files.
|
* MAX_INPUT: (libc)Limits for Files.
|
* MB_CUR_MAX: (libc)Selecting the Conversion.
|
* MB_LEN_MAX: (libc)Selecting the Conversion.
|
* MDMBUF: (libc)Control Modes.
|
* MSG_DONTROUTE: (libc)Socket Data Options.
|
* MSG_OOB: (libc)Socket Data Options.
|
* MSG_PEEK: (libc)Socket Data Options.
|
* NAME_MAX: (libc)Limits for Files.
|
* NAN: (libc)Infinity and NaN.
|
* NCCS: (libc)Mode Data Types.
|
* NGROUPS_MAX: (libc)General Limits.
|
* NOFLSH: (libc)Local Modes.
|
* NOKERNINFO: (libc)Local Modes.
|
* NSIG: (libc)Standard Signals.
|
* NULL: (libc)Null Pointer Constant.
|
* ONLCR: (libc)Output Modes.
|
* ONOEOT: (libc)Output Modes.
|
* OPEN_MAX: (libc)General Limits.
|
* OPOST: (libc)Output Modes.
|
* OXTABS: (libc)Output Modes.
|
* O_ACCMODE: (libc)Access Modes.
|
* O_APPEND: (libc)Operating Modes.
|
* O_ASYNC: (libc)Operating Modes.
|
* O_CREAT: (libc)Open-time Flags.
|
* O_EXCL: (libc)Open-time Flags.
|
* O_EXEC: (libc)Access Modes.
|
* O_EXLOCK: (libc)Open-time Flags.
|
* O_FSYNC: (libc)Operating Modes.
|
* O_IGNORE_CTTY: (libc)Open-time Flags.
|
* O_NDELAY: (libc)Operating Modes.
|
* O_NOATIME: (libc)Operating Modes.
|
* O_NOCTTY: (libc)Open-time Flags.
|
* O_NOLINK: (libc)Open-time Flags.
|
* O_NONBLOCK: (libc)Open-time Flags.
|
* O_NONBLOCK: (libc)Operating Modes.
|
* O_NOTRANS: (libc)Open-time Flags.
|
* O_RDONLY: (libc)Access Modes.
|
* O_RDWR: (libc)Access Modes.
|
* O_READ: (libc)Access Modes.
|
* O_SHLOCK: (libc)Open-time Flags.
|
* O_SYNC: (libc)Operating Modes.
|
* O_TRUNC: (libc)Open-time Flags.
|
* O_WRITE: (libc)Access Modes.
|
* O_WRONLY: (libc)Access Modes.
|
* PARENB: (libc)Control Modes.
|
* PARMRK: (libc)Input Modes.
|
* PARODD: (libc)Control Modes.
|
* PATH_MAX: (libc)Limits for Files.
|
* PA_FLAG_MASK: (libc)Parsing a Template String.
|
* PENDIN: (libc)Local Modes.
|
* PF_FILE: (libc)Local Namespace Details.
|
* PF_INET6: (libc)Internet Namespace.
|
* PF_INET: (libc)Internet Namespace.
|
* PF_LOCAL: (libc)Local Namespace Details.
|
* PF_UNIX: (libc)Local Namespace Details.
|
* PIPE_BUF: (libc)Limits for Files.
|
* P_tmpdir: (libc)Temporary Files.
|
* RAND_MAX: (libc)ISO Random.
|
* RE_DUP_MAX: (libc)General Limits.
|
* RLIM_INFINITY: (libc)Limits on Resources.
|
* R_OK: (libc)Testing File Access.
|
* SA_NOCLDSTOP: (libc)Flags for Sigaction.
|
* SA_ONSTACK: (libc)Flags for Sigaction.
|
* SA_RESTART: (libc)Flags for Sigaction.
|
* SEEK_CUR: (libc)File Positioning.
|
* SEEK_END: (libc)File Positioning.
|
* SEEK_SET: (libc)File Positioning.
|
* SIGABRT: (libc)Program Error Signals.
|
* SIGALRM: (libc)Alarm Signals.
|
* SIGBUS: (libc)Program Error Signals.
|
* SIGCHLD: (libc)Job Control Signals.
|
* SIGCLD: (libc)Job Control Signals.
|
* SIGCONT: (libc)Job Control Signals.
|
* SIGEMT: (libc)Program Error Signals.
|
* SIGFPE: (libc)Program Error Signals.
|
* SIGHUP: (libc)Termination Signals.
|
* SIGILL: (libc)Program Error Signals.
|
* SIGINFO: (libc)Miscellaneous Signals.
|
* SIGINT: (libc)Termination Signals.
|
* SIGIO: (libc)Asynchronous I/O Signals.
|
* SIGIOT: (libc)Program Error Signals.
|
* SIGKILL: (libc)Termination Signals.
|
* SIGLOST: (libc)Operation Error Signals.
|
* SIGPIPE: (libc)Operation Error Signals.
|
* SIGPOLL: (libc)Asynchronous I/O Signals.
|
* SIGPROF: (libc)Alarm Signals.
|
* SIGQUIT: (libc)Termination Signals.
|
* SIGSEGV: (libc)Program Error Signals.
|
* SIGSTOP: (libc)Job Control Signals.
|
* SIGSYS: (libc)Program Error Signals.
|
* SIGTERM: (libc)Termination Signals.
|
* SIGTRAP: (libc)Program Error Signals.
|
* SIGTSTP: (libc)Job Control Signals.
|
* SIGTTIN: (libc)Job Control Signals.
|
* SIGTTOU: (libc)Job Control Signals.
|
* SIGURG: (libc)Asynchronous I/O Signals.
|
* SIGUSR1: (libc)Miscellaneous Signals.
|
* SIGUSR2: (libc)Miscellaneous Signals.
|
* SIGVTALRM: (libc)Alarm Signals.
|
* SIGWINCH: (libc)Miscellaneous Signals.
|
* SIGXCPU: (libc)Operation Error Signals.
|
* SIGXFSZ: (libc)Operation Error Signals.
|
* SIG_ERR: (libc)Basic Signal Handling.
|
* SNAN: (libc)Infinity and NaN.
|
* SNANF: (libc)Infinity and NaN.
|
* SNANL: (libc)Infinity and NaN.
|
* SOCK_DGRAM: (libc)Communication Styles.
|
* SOCK_RAW: (libc)Communication Styles.
|
* SOCK_RDM: (libc)Communication Styles.
|
* SOCK_SEQPACKET: (libc)Communication Styles.
|
* SOCK_STREAM: (libc)Communication Styles.
|
* SOL_SOCKET: (libc)Socket-Level Options.
|
* SSIZE_MAX: (libc)General Limits.
|
* STREAM_MAX: (libc)General Limits.
|
* SUN_LEN: (libc)Local Namespace Details.
|
* S_IFMT: (libc)Testing File Type.
|
* S_ISBLK: (libc)Testing File Type.
|
* S_ISCHR: (libc)Testing File Type.
|
* S_ISDIR: (libc)Testing File Type.
|
* S_ISFIFO: (libc)Testing File Type.
|
* S_ISLNK: (libc)Testing File Type.
|
* S_ISREG: (libc)Testing File Type.
|
* S_ISSOCK: (libc)Testing File Type.
|
* S_TYPEISMQ: (libc)Testing File Type.
|
* S_TYPEISSEM: (libc)Testing File Type.
|
* S_TYPEISSHM: (libc)Testing File Type.
|
* TMP_MAX: (libc)Temporary Files.
|
* TOSTOP: (libc)Local Modes.
|
* TZNAME_MAX: (libc)General Limits.
|
* VDISCARD: (libc)Other Special.
|
* VDSUSP: (libc)Signal Characters.
|
* VEOF: (libc)Editing Characters.
|
* VEOL2: (libc)Editing Characters.
|
* VEOL: (libc)Editing Characters.
|
* VERASE: (libc)Editing Characters.
|
* VINTR: (libc)Signal Characters.
|
* VKILL: (libc)Editing Characters.
|
* VLNEXT: (libc)Other Special.
|
* VMIN: (libc)Noncanonical Input.
|
* VQUIT: (libc)Signal Characters.
|
* VREPRINT: (libc)Editing Characters.
|
* VSTART: (libc)Start/Stop Characters.
|
* VSTATUS: (libc)Other Special.
|
* VSTOP: (libc)Start/Stop Characters.
|
* VSUSP: (libc)Signal Characters.
|
* VTIME: (libc)Noncanonical Input.
|
* VWERASE: (libc)Editing Characters.
|
* WCHAR_MAX: (libc)Extended Char Intro.
|
* WCHAR_MIN: (libc)Extended Char Intro.
|
* WCOREDUMP: (libc)Process Completion Status.
|
* WEOF: (libc)EOF and Errors.
|
* WEOF: (libc)Extended Char Intro.
|
* WEXITSTATUS: (libc)Process Completion Status.
|
* WIFEXITED: (libc)Process Completion Status.
|
* WIFSIGNALED: (libc)Process Completion Status.
|
* WIFSTOPPED: (libc)Process Completion Status.
|
* WSTOPSIG: (libc)Process Completion Status.
|
* WTERMSIG: (libc)Process Completion Status.
|
* W_OK: (libc)Testing File Access.
|
* X_OK: (libc)Testing File Access.
|
* _Complex_I: (libc)Complex Numbers.
|
* _Exit: (libc)Termination Internals.
|
* _IOFBF: (libc)Controlling Buffering.
|
* _IOLBF: (libc)Controlling Buffering.
|
* _IONBF: (libc)Controlling Buffering.
|
* _Imaginary_I: (libc)Complex Numbers.
|
* _PATH_UTMP: (libc)Manipulating the Database.
|
* _PATH_WTMP: (libc)Manipulating the Database.
|
* _POSIX2_C_DEV: (libc)System Options.
|
* _POSIX2_C_VERSION: (libc)Version Supported.
|
* _POSIX2_FORT_DEV: (libc)System Options.
|
* _POSIX2_FORT_RUN: (libc)System Options.
|
* _POSIX2_LOCALEDEF: (libc)System Options.
|
* _POSIX2_SW_DEV: (libc)System Options.
|
* _POSIX_CHOWN_RESTRICTED: (libc)Options for Files.
|
* _POSIX_JOB_CONTROL: (libc)System Options.
|
* _POSIX_NO_TRUNC: (libc)Options for Files.
|
* _POSIX_SAVED_IDS: (libc)System Options.
|
* _POSIX_VDISABLE: (libc)Options for Files.
|
* _POSIX_VERSION: (libc)Version Supported.
|
* __fbufsize: (libc)Controlling Buffering.
|
* __flbf: (libc)Controlling Buffering.
|
* __fpending: (libc)Controlling Buffering.
|
* __fpurge: (libc)Flushing Buffers.
|
* __freadable: (libc)Opening Streams.
|
* __freading: (libc)Opening Streams.
|
* __fsetlocking: (libc)Streams and Threads.
|
* __fwritable: (libc)Opening Streams.
|
* __fwriting: (libc)Opening Streams.
|
* __gconv_end_fct: (libc)glibc iconv Implementation.
|
* __gconv_fct: (libc)glibc iconv Implementation.
|
* __gconv_init_fct: (libc)glibc iconv Implementation.
|
* __ppc_get_timebase: (libc)PowerPC.
|
* __ppc_get_timebase_freq: (libc)PowerPC.
|
* __ppc_mdoio: (libc)PowerPC.
|
* __ppc_mdoom: (libc)PowerPC.
|
* __ppc_set_ppr_low: (libc)PowerPC.
|
* __ppc_set_ppr_med: (libc)PowerPC.
|
* __ppc_set_ppr_med_high: (libc)PowerPC.
|
* __ppc_set_ppr_med_low: (libc)PowerPC.
|
* __ppc_set_ppr_very_low: (libc)PowerPC.
|
* __ppc_yield: (libc)PowerPC.
|
* __va_copy: (libc)Argument Macros.
|
* _exit: (libc)Termination Internals.
|
* _flushlbf: (libc)Flushing Buffers.
|
* _tolower: (libc)Case Conversion.
|
* _toupper: (libc)Case Conversion.
|
* a64l: (libc)Encode Binary Data.
|
* abort: (libc)Aborting a Program.
|
* abs: (libc)Absolute Value.
|
* accept: (libc)Accepting Connections.
|
* access: (libc)Testing File Access.
|
* acos: (libc)Inverse Trig Functions.
|
* acosf: (libc)Inverse Trig Functions.
|
* acosh: (libc)Hyperbolic Functions.
|
* acoshf: (libc)Hyperbolic Functions.
|
* acoshl: (libc)Hyperbolic Functions.
|
* acosl: (libc)Inverse Trig Functions.
|
* addmntent: (libc)mtab.
|
* addseverity: (libc)Adding Severity Classes.
|
* adjtime: (libc)High-Resolution Calendar.
|
* adjtimex: (libc)High-Resolution Calendar.
|
* aio_cancel64: (libc)Cancel AIO Operations.
|
* aio_cancel: (libc)Cancel AIO Operations.
|
* aio_error64: (libc)Status of AIO Operations.
|
* aio_error: (libc)Status of AIO Operations.
|
* aio_fsync64: (libc)Synchronizing AIO Operations.
|
* aio_fsync: (libc)Synchronizing AIO Operations.
|
* aio_init: (libc)Configuration of AIO.
|
* aio_read64: (libc)Asynchronous Reads/Writes.
|
* aio_read: (libc)Asynchronous Reads/Writes.
|
* aio_return64: (libc)Status of AIO Operations.
|
* aio_return: (libc)Status of AIO Operations.
|
* aio_suspend64: (libc)Synchronizing AIO Operations.
|
* aio_suspend: (libc)Synchronizing AIO Operations.
|
* aio_write64: (libc)Asynchronous Reads/Writes.
|
* aio_write: (libc)Asynchronous Reads/Writes.
|
* alarm: (libc)Setting an Alarm.
|
* aligned_alloc: (libc)Aligned Memory Blocks.
|
* alloca: (libc)Variable Size Automatic.
|
* alphasort64: (libc)Scanning Directory Content.
|
* alphasort: (libc)Scanning Directory Content.
|
* argp_error: (libc)Argp Helper Functions.
|
* argp_failure: (libc)Argp Helper Functions.
|
* argp_help: (libc)Argp Help.
|
* argp_parse: (libc)Argp.
|
* argp_state_help: (libc)Argp Helper Functions.
|
* argp_usage: (libc)Argp Helper Functions.
|
* argz_add: (libc)Argz Functions.
|
* argz_add_sep: (libc)Argz Functions.
|
* argz_append: (libc)Argz Functions.
|
* argz_count: (libc)Argz Functions.
|
* argz_create: (libc)Argz Functions.
|
* argz_create_sep: (libc)Argz Functions.
|
* argz_delete: (libc)Argz Functions.
|
* argz_extract: (libc)Argz Functions.
|
* argz_insert: (libc)Argz Functions.
|
* argz_next: (libc)Argz Functions.
|
* argz_replace: (libc)Argz Functions.
|
* argz_stringify: (libc)Argz Functions.
|
* asctime: (libc)Formatting Calendar Time.
|
* asctime_r: (libc)Formatting Calendar Time.
|
* asin: (libc)Inverse Trig Functions.
|
* asinf: (libc)Inverse Trig Functions.
|
* asinh: (libc)Hyperbolic Functions.
|
* asinhf: (libc)Hyperbolic Functions.
|
* asinhl: (libc)Hyperbolic Functions.
|
* asinl: (libc)Inverse Trig Functions.
|
* asprintf: (libc)Dynamic Output.
|
* assert: (libc)Consistency Checking.
|
* assert_perror: (libc)Consistency Checking.
|
* atan2: (libc)Inverse Trig Functions.
|
* atan2f: (libc)Inverse Trig Functions.
|
* atan2l: (libc)Inverse Trig Functions.
|
* atan: (libc)Inverse Trig Functions.
|
* atanf: (libc)Inverse Trig Functions.
|
* atanh: (libc)Hyperbolic Functions.
|
* atanhf: (libc)Hyperbolic Functions.
|
* atanhl: (libc)Hyperbolic Functions.
|
* atanl: (libc)Inverse Trig Functions.
|
* atexit: (libc)Cleanups on Exit.
|
* atof: (libc)Parsing of Floats.
|
* atoi: (libc)Parsing of Integers.
|
* atol: (libc)Parsing of Integers.
|
* atoll: (libc)Parsing of Integers.
|
* backtrace: (libc)Backtraces.
|
* backtrace_symbols: (libc)Backtraces.
|
* backtrace_symbols_fd: (libc)Backtraces.
|
* basename: (libc)Finding Tokens in a String.
|
* basename: (libc)Finding Tokens in a String.
|
* bcmp: (libc)String/Array Comparison.
|
* bcopy: (libc)Copying Strings and Arrays.
|
* bind: (libc)Setting Address.
|
* bind_textdomain_codeset: (libc)Charset conversion in gettext.
|
* bindtextdomain: (libc)Locating gettext catalog.
|
* brk: (libc)Resizing the Data Segment.
|
* bsearch: (libc)Array Search Function.
|
* btowc: (libc)Converting a Character.
|
* bzero: (libc)Copying Strings and Arrays.
|
* cabs: (libc)Absolute Value.
|
* cabsf: (libc)Absolute Value.
|
* cabsl: (libc)Absolute Value.
|
* cacos: (libc)Inverse Trig Functions.
|
* cacosf: (libc)Inverse Trig Functions.
|
* cacosh: (libc)Hyperbolic Functions.
|
* cacoshf: (libc)Hyperbolic Functions.
|
* cacoshl: (libc)Hyperbolic Functions.
|
* cacosl: (libc)Inverse Trig Functions.
|
* calloc: (libc)Allocating Cleared Space.
|
* canonicalize: (libc)FP Bit Twiddling.
|
* canonicalize_file_name: (libc)Symbolic Links.
|
* canonicalizef: (libc)FP Bit Twiddling.
|
* canonicalizel: (libc)FP Bit Twiddling.
|
* carg: (libc)Operations on Complex.
|
* cargf: (libc)Operations on Complex.
|
* cargl: (libc)Operations on Complex.
|
* casin: (libc)Inverse Trig Functions.
|
* casinf: (libc)Inverse Trig Functions.
|
* casinh: (libc)Hyperbolic Functions.
|
* casinhf: (libc)Hyperbolic Functions.
|
* casinhl: (libc)Hyperbolic Functions.
|
* casinl: (libc)Inverse Trig Functions.
|
* catan: (libc)Inverse Trig Functions.
|
* catanf: (libc)Inverse Trig Functions.
|
* catanh: (libc)Hyperbolic Functions.
|
* catanhf: (libc)Hyperbolic Functions.
|
* catanhl: (libc)Hyperbolic Functions.
|
* catanl: (libc)Inverse Trig Functions.
|
* catclose: (libc)The catgets Functions.
|
* catgets: (libc)The catgets Functions.
|
* catopen: (libc)The catgets Functions.
|
* cbc_crypt: (libc)DES Encryption.
|
* cbrt: (libc)Exponents and Logarithms.
|
* cbrtf: (libc)Exponents and Logarithms.
|
* cbrtl: (libc)Exponents and Logarithms.
|
* ccos: (libc)Trig Functions.
|
* ccosf: (libc)Trig Functions.
|
* ccosh: (libc)Hyperbolic Functions.
|
* ccoshf: (libc)Hyperbolic Functions.
|
* ccoshl: (libc)Hyperbolic Functions.
|
* ccosl: (libc)Trig Functions.
|
* ceil: (libc)Rounding Functions.
|
* ceilf: (libc)Rounding Functions.
|
* ceill: (libc)Rounding Functions.
|
* cexp: (libc)Exponents and Logarithms.
|
* cexpf: (libc)Exponents and Logarithms.
|
* cexpl: (libc)Exponents and Logarithms.
|
* cfgetispeed: (libc)Line Speed.
|
* cfgetospeed: (libc)Line Speed.
|
* cfmakeraw: (libc)Noncanonical Input.
|
* cfree: (libc)Freeing after Malloc.
|
* cfsetispeed: (libc)Line Speed.
|
* cfsetospeed: (libc)Line Speed.
|
* cfsetspeed: (libc)Line Speed.
|
* chdir: (libc)Working Directory.
|
* chmod: (libc)Setting Permissions.
|
* chown: (libc)File Owner.
|
* cimag: (libc)Operations on Complex.
|
* cimagf: (libc)Operations on Complex.
|
* cimagl: (libc)Operations on Complex.
|
* clearenv: (libc)Environment Access.
|
* clearerr: (libc)Error Recovery.
|
* clearerr_unlocked: (libc)Error Recovery.
|
* clock: (libc)CPU Time.
|
* clog10: (libc)Exponents and Logarithms.
|
* clog10f: (libc)Exponents and Logarithms.
|
* clog10l: (libc)Exponents and Logarithms.
|
* clog: (libc)Exponents and Logarithms.
|
* clogf: (libc)Exponents and Logarithms.
|
* clogl: (libc)Exponents and Logarithms.
|
* close: (libc)Opening and Closing Files.
|
* closedir: (libc)Reading/Closing Directory.
|
* closelog: (libc)closelog.
|
* confstr: (libc)String Parameters.
|
* conj: (libc)Operations on Complex.
|
* conjf: (libc)Operations on Complex.
|
* conjl: (libc)Operations on Complex.
|
* connect: (libc)Connecting.
|
* copysign: (libc)FP Bit Twiddling.
|
* copysignf: (libc)FP Bit Twiddling.
|
* copysignl: (libc)FP Bit Twiddling.
|
* cos: (libc)Trig Functions.
|
* cosf: (libc)Trig Functions.
|
* cosh: (libc)Hyperbolic Functions.
|
* coshf: (libc)Hyperbolic Functions.
|
* coshl: (libc)Hyperbolic Functions.
|
* cosl: (libc)Trig Functions.
|
* cpow: (libc)Exponents and Logarithms.
|
* cpowf: (libc)Exponents and Logarithms.
|
* cpowl: (libc)Exponents and Logarithms.
|
* cproj: (libc)Operations on Complex.
|
* cprojf: (libc)Operations on Complex.
|
* cprojl: (libc)Operations on Complex.
|
* creal: (libc)Operations on Complex.
|
* crealf: (libc)Operations on Complex.
|
* creall: (libc)Operations on Complex.
|
* creat64: (libc)Opening and Closing Files.
|
* creat: (libc)Opening and Closing Files.
|
* crypt: (libc)crypt.
|
* crypt_r: (libc)crypt.
|
* csin: (libc)Trig Functions.
|
* csinf: (libc)Trig Functions.
|
* csinh: (libc)Hyperbolic Functions.
|
* csinhf: (libc)Hyperbolic Functions.
|
* csinhl: (libc)Hyperbolic Functions.
|
* csinl: (libc)Trig Functions.
|
* csqrt: (libc)Exponents and Logarithms.
|
* csqrtf: (libc)Exponents and Logarithms.
|
* csqrtl: (libc)Exponents and Logarithms.
|
* ctan: (libc)Trig Functions.
|
* ctanf: (libc)Trig Functions.
|
* ctanh: (libc)Hyperbolic Functions.
|
* ctanhf: (libc)Hyperbolic Functions.
|
* ctanhl: (libc)Hyperbolic Functions.
|
* ctanl: (libc)Trig Functions.
|
* ctermid: (libc)Identifying the Terminal.
|
* ctime: (libc)Formatting Calendar Time.
|
* ctime_r: (libc)Formatting Calendar Time.
|
* cuserid: (libc)Who Logged In.
|
* dcgettext: (libc)Translation with gettext.
|
* dcngettext: (libc)Advanced gettext functions.
|
* des_setparity: (libc)DES Encryption.
|
* dgettext: (libc)Translation with gettext.
|
* difftime: (libc)Elapsed Time.
|
* dirfd: (libc)Opening a Directory.
|
* dirname: (libc)Finding Tokens in a String.
|
* div: (libc)Integer Division.
|
* dngettext: (libc)Advanced gettext functions.
|
* drand48: (libc)SVID Random.
|
* drand48_r: (libc)SVID Random.
|
* drem: (libc)Remainder Functions.
|
* dremf: (libc)Remainder Functions.
|
* dreml: (libc)Remainder Functions.
|
* dup2: (libc)Duplicating Descriptors.
|
* dup: (libc)Duplicating Descriptors.
|
* ecb_crypt: (libc)DES Encryption.
|
* ecvt: (libc)System V Number Conversion.
|
* ecvt_r: (libc)System V Number Conversion.
|
* encrypt: (libc)DES Encryption.
|
* encrypt_r: (libc)DES Encryption.
|
* endfsent: (libc)fstab.
|
* endgrent: (libc)Scanning All Groups.
|
* endhostent: (libc)Host Names.
|
* endmntent: (libc)mtab.
|
* endnetent: (libc)Networks Database.
|
* endnetgrent: (libc)Lookup Netgroup.
|
* endprotoent: (libc)Protocols Database.
|
* endpwent: (libc)Scanning All Users.
|
* endservent: (libc)Services Database.
|
* endutent: (libc)Manipulating the Database.
|
* endutxent: (libc)XPG Functions.
|
* envz_add: (libc)Envz Functions.
|
* envz_entry: (libc)Envz Functions.
|
* envz_get: (libc)Envz Functions.
|
* envz_merge: (libc)Envz Functions.
|
* envz_remove: (libc)Envz Functions.
|
* envz_strip: (libc)Envz Functions.
|
* erand48: (libc)SVID Random.
|
* erand48_r: (libc)SVID Random.
|
* erf: (libc)Special Functions.
|
* erfc: (libc)Special Functions.
|
* erfcf: (libc)Special Functions.
|
* erfcl: (libc)Special Functions.
|
* erff: (libc)Special Functions.
|
* erfl: (libc)Special Functions.
|
* err: (libc)Error Messages.
|
* errno: (libc)Checking for Errors.
|
* error: (libc)Error Messages.
|
* error_at_line: (libc)Error Messages.
|
* errx: (libc)Error Messages.
|
* execl: (libc)Executing a File.
|
* execle: (libc)Executing a File.
|
* execlp: (libc)Executing a File.
|
* execv: (libc)Executing a File.
|
* execve: (libc)Executing a File.
|
* execvp: (libc)Executing a File.
|
* exit: (libc)Normal Termination.
|
* exp10: (libc)Exponents and Logarithms.
|
* exp10f: (libc)Exponents and Logarithms.
|
* exp10l: (libc)Exponents and Logarithms.
|
* exp2: (libc)Exponents and Logarithms.
|
* exp2f: (libc)Exponents and Logarithms.
|
* exp2l: (libc)Exponents and Logarithms.
|
* exp: (libc)Exponents and Logarithms.
|
* expf: (libc)Exponents and Logarithms.
|
* expl: (libc)Exponents and Logarithms.
|
* explicit_bzero: (libc)Erasing Sensitive Data.
|
* expm1: (libc)Exponents and Logarithms.
|
* expm1f: (libc)Exponents and Logarithms.
|
* expm1l: (libc)Exponents and Logarithms.
|
* fabs: (libc)Absolute Value.
|
* fabsf: (libc)Absolute Value.
|
* fabsl: (libc)Absolute Value.
|
* fchdir: (libc)Working Directory.
|
* fchmod: (libc)Setting Permissions.
|
* fchown: (libc)File Owner.
|
* fclose: (libc)Closing Streams.
|
* fcloseall: (libc)Closing Streams.
|
* fcntl: (libc)Control Operations.
|
* fcvt: (libc)System V Number Conversion.
|
* fcvt_r: (libc)System V Number Conversion.
|
* fdatasync: (libc)Synchronizing I/O.
|
* fdim: (libc)Misc FP Arithmetic.
|
* fdimf: (libc)Misc FP Arithmetic.
|
* fdiml: (libc)Misc FP Arithmetic.
|
* fdopen: (libc)Descriptors and Streams.
|
* fdopendir: (libc)Opening a Directory.
|
* feclearexcept: (libc)Status bit operations.
|
* fedisableexcept: (libc)Control Functions.
|
* feenableexcept: (libc)Control Functions.
|
* fegetenv: (libc)Control Functions.
|
* fegetexcept: (libc)Control Functions.
|
* fegetexceptflag: (libc)Status bit operations.
|
* fegetmode: (libc)Control Functions.
|
* fegetround: (libc)Rounding.
|
* feholdexcept: (libc)Control Functions.
|
* feof: (libc)EOF and Errors.
|
* feof_unlocked: (libc)EOF and Errors.
|
* feraiseexcept: (libc)Status bit operations.
|
* ferror: (libc)EOF and Errors.
|
* ferror_unlocked: (libc)EOF and Errors.
|
* fesetenv: (libc)Control Functions.
|
* fesetexcept: (libc)Status bit operations.
|
* fesetexceptflag: (libc)Status bit operations.
|
* fesetmode: (libc)Control Functions.
|
* fesetround: (libc)Rounding.
|
* fetestexcept: (libc)Status bit operations.
|
* fetestexceptflag: (libc)Status bit operations.
|
* feupdateenv: (libc)Control Functions.
|
* fflush: (libc)Flushing Buffers.
|
* fflush_unlocked: (libc)Flushing Buffers.
|
* fgetc: (libc)Character Input.
|
* fgetc_unlocked: (libc)Character Input.
|
* fgetgrent: (libc)Scanning All Groups.
|
* fgetgrent_r: (libc)Scanning All Groups.
|
* fgetpos64: (libc)Portable Positioning.
|
* fgetpos: (libc)Portable Positioning.
|
* fgetpwent: (libc)Scanning All Users.
|
* fgetpwent_r: (libc)Scanning All Users.
|
* fgets: (libc)Line Input.
|
* fgets_unlocked: (libc)Line Input.
|
* fgetwc: (libc)Character Input.
|
* fgetwc_unlocked: (libc)Character Input.
|
* fgetws: (libc)Line Input.
|
* fgetws_unlocked: (libc)Line Input.
|
* fileno: (libc)Descriptors and Streams.
|
* fileno_unlocked: (libc)Descriptors and Streams.
|
* finite: (libc)Floating Point Classes.
|
* finitef: (libc)Floating Point Classes.
|
* finitel: (libc)Floating Point Classes.
|
* flockfile: (libc)Streams and Threads.
|
* floor: (libc)Rounding Functions.
|
* floorf: (libc)Rounding Functions.
|
* floorl: (libc)Rounding Functions.
|
* fma: (libc)Misc FP Arithmetic.
|
* fmaf: (libc)Misc FP Arithmetic.
|
* fmal: (libc)Misc FP Arithmetic.
|
* fmax: (libc)Misc FP Arithmetic.
|
* fmaxf: (libc)Misc FP Arithmetic.
|
* fmaxl: (libc)Misc FP Arithmetic.
|
* fmaxmag: (libc)Misc FP Arithmetic.
|
* fmaxmagf: (libc)Misc FP Arithmetic.
|
* fmaxmagl: (libc)Misc FP Arithmetic.
|
* fmemopen: (libc)String Streams.
|
* fmin: (libc)Misc FP Arithmetic.
|
* fminf: (libc)Misc FP Arithmetic.
|
* fminl: (libc)Misc FP Arithmetic.
|
* fminmag: (libc)Misc FP Arithmetic.
|
* fminmagf: (libc)Misc FP Arithmetic.
|
* fminmagl: (libc)Misc FP Arithmetic.
|
* fmod: (libc)Remainder Functions.
|
* fmodf: (libc)Remainder Functions.
|
* fmodl: (libc)Remainder Functions.
|
* fmtmsg: (libc)Printing Formatted Messages.
|
* fnmatch: (libc)Wildcard Matching.
|
* fopen64: (libc)Opening Streams.
|
* fopen: (libc)Opening Streams.
|
* fopencookie: (libc)Streams and Cookies.
|
* fork: (libc)Creating a Process.
|
* forkpty: (libc)Pseudo-Terminal Pairs.
|
* fpathconf: (libc)Pathconf.
|
* fpclassify: (libc)Floating Point Classes.
|
* fprintf: (libc)Formatted Output Functions.
|
* fputc: (libc)Simple Output.
|
* fputc_unlocked: (libc)Simple Output.
|
* fputs: (libc)Simple Output.
|
* fputs_unlocked: (libc)Simple Output.
|
* fputwc: (libc)Simple Output.
|
* fputwc_unlocked: (libc)Simple Output.
|
* fputws: (libc)Simple Output.
|
* fputws_unlocked: (libc)Simple Output.
|
* fread: (libc)Block Input/Output.
|
* fread_unlocked: (libc)Block Input/Output.
|
* free: (libc)Freeing after Malloc.
|
* freopen64: (libc)Opening Streams.
|
* freopen: (libc)Opening Streams.
|
* frexp: (libc)Normalization Functions.
|
* frexpf: (libc)Normalization Functions.
|
* frexpl: (libc)Normalization Functions.
|
* fromfp: (libc)Rounding Functions.
|
* fromfpf: (libc)Rounding Functions.
|
* fromfpl: (libc)Rounding Functions.
|
* fromfpx: (libc)Rounding Functions.
|
* fromfpxf: (libc)Rounding Functions.
|
* fromfpxl: (libc)Rounding Functions.
|
* fscanf: (libc)Formatted Input Functions.
|
* fseek: (libc)File Positioning.
|
* fseeko64: (libc)File Positioning.
|
* fseeko: (libc)File Positioning.
|
* fsetpos64: (libc)Portable Positioning.
|
* fsetpos: (libc)Portable Positioning.
|
* fstat64: (libc)Reading Attributes.
|
* fstat: (libc)Reading Attributes.
|
* fsync: (libc)Synchronizing I/O.
|
* ftell: (libc)File Positioning.
|
* ftello64: (libc)File Positioning.
|
* ftello: (libc)File Positioning.
|
* ftruncate64: (libc)File Size.
|
* ftruncate: (libc)File Size.
|
* ftrylockfile: (libc)Streams and Threads.
|
* ftw64: (libc)Working with Directory Trees.
|
* ftw: (libc)Working with Directory Trees.
|
* funlockfile: (libc)Streams and Threads.
|
* futimes: (libc)File Times.
|
* fwide: (libc)Streams and I18N.
|
* fwprintf: (libc)Formatted Output Functions.
|
* fwrite: (libc)Block Input/Output.
|
* fwrite_unlocked: (libc)Block Input/Output.
|
* fwscanf: (libc)Formatted Input Functions.
|
* gamma: (libc)Special Functions.
|
* gammaf: (libc)Special Functions.
|
* gammal: (libc)Special Functions.
|
* gcvt: (libc)System V Number Conversion.
|
* get_avphys_pages: (libc)Query Memory Parameters.
|
* get_current_dir_name: (libc)Working Directory.
|
* get_nprocs: (libc)Processor Resources.
|
* get_nprocs_conf: (libc)Processor Resources.
|
* get_phys_pages: (libc)Query Memory Parameters.
|
* getauxval: (libc)Auxiliary Vector.
|
* getc: (libc)Character Input.
|
* getc_unlocked: (libc)Character Input.
|
* getchar: (libc)Character Input.
|
* getchar_unlocked: (libc)Character Input.
|
* getcontext: (libc)System V contexts.
|
* getcwd: (libc)Working Directory.
|
* getdate: (libc)General Time String Parsing.
|
* getdate_r: (libc)General Time String Parsing.
|
* getdelim: (libc)Line Input.
|
* getdomainnname: (libc)Host Identification.
|
* getegid: (libc)Reading Persona.
|
* getentropy: (libc)Unpredictable Bytes.
|
* getenv: (libc)Environment Access.
|
* geteuid: (libc)Reading Persona.
|
* getfsent: (libc)fstab.
|
* getfsfile: (libc)fstab.
|
* getfsspec: (libc)fstab.
|
* getgid: (libc)Reading Persona.
|
* getgrent: (libc)Scanning All Groups.
|
* getgrent_r: (libc)Scanning All Groups.
|
* getgrgid: (libc)Lookup Group.
|
* getgrgid_r: (libc)Lookup Group.
|
* getgrnam: (libc)Lookup Group.
|
* getgrnam_r: (libc)Lookup Group.
|
* getgrouplist: (libc)Setting Groups.
|
* getgroups: (libc)Reading Persona.
|
* gethostbyaddr: (libc)Host Names.
|
* gethostbyaddr_r: (libc)Host Names.
|
* gethostbyname2: (libc)Host Names.
|
* gethostbyname2_r: (libc)Host Names.
|
* gethostbyname: (libc)Host Names.
|
* gethostbyname_r: (libc)Host Names.
|
* gethostent: (libc)Host Names.
|
* gethostid: (libc)Host Identification.
|
* gethostname: (libc)Host Identification.
|
* getitimer: (libc)Setting an Alarm.
|
* getline: (libc)Line Input.
|
* getloadavg: (libc)Processor Resources.
|
* getlogin: (libc)Who Logged In.
|
* getmntent: (libc)mtab.
|
* getmntent_r: (libc)mtab.
|
* getnetbyaddr: (libc)Networks Database.
|
* getnetbyname: (libc)Networks Database.
|
* getnetent: (libc)Networks Database.
|
* getnetgrent: (libc)Lookup Netgroup.
|
* getnetgrent_r: (libc)Lookup Netgroup.
|
* getopt: (libc)Using Getopt.
|
* getopt_long: (libc)Getopt Long Options.
|
* getopt_long_only: (libc)Getopt Long Options.
|
* getpagesize: (libc)Query Memory Parameters.
|
* getpass: (libc)getpass.
|
* getpayload: (libc)FP Bit Twiddling.
|
* getpayloadf: (libc)FP Bit Twiddling.
|
* getpayloadl: (libc)FP Bit Twiddling.
|
* getpeername: (libc)Who is Connected.
|
* getpgid: (libc)Process Group Functions.
|
* getpgrp: (libc)Process Group Functions.
|
* getpid: (libc)Process Identification.
|
* getppid: (libc)Process Identification.
|
* getpriority: (libc)Traditional Scheduling Functions.
|
* getprotobyname: (libc)Protocols Database.
|
* getprotobynumber: (libc)Protocols Database.
|
* getprotoent: (libc)Protocols Database.
|
* getpt: (libc)Allocation.
|
* getpwent: (libc)Scanning All Users.
|
* getpwent_r: (libc)Scanning All Users.
|
* getpwnam: (libc)Lookup User.
|
* getpwnam_r: (libc)Lookup User.
|
* getpwuid: (libc)Lookup User.
|
* getpwuid_r: (libc)Lookup User.
|
* getrandom: (libc)Unpredictable Bytes.
|
* getrlimit64: (libc)Limits on Resources.
|
* getrlimit: (libc)Limits on Resources.
|
* getrusage: (libc)Resource Usage.
|
* gets: (libc)Line Input.
|
* getservbyname: (libc)Services Database.
|
* getservbyport: (libc)Services Database.
|
* getservent: (libc)Services Database.
|
* getsid: (libc)Process Group Functions.
|
* getsockname: (libc)Reading Address.
|
* getsockopt: (libc)Socket Option Functions.
|
* getsubopt: (libc)Suboptions.
|
* gettext: (libc)Translation with gettext.
|
* gettimeofday: (libc)High-Resolution Calendar.
|
* getuid: (libc)Reading Persona.
|
* getumask: (libc)Setting Permissions.
|
* getutent: (libc)Manipulating the Database.
|
* getutent_r: (libc)Manipulating the Database.
|
* getutid: (libc)Manipulating the Database.
|
* getutid_r: (libc)Manipulating the Database.
|
* getutline: (libc)Manipulating the Database.
|
* getutline_r: (libc)Manipulating the Database.
|
* getutmp: (libc)XPG Functions.
|
* getutmpx: (libc)XPG Functions.
|
* getutxent: (libc)XPG Functions.
|
* getutxid: (libc)XPG Functions.
|
* getutxline: (libc)XPG Functions.
|
* getw: (libc)Character Input.
|
* getwc: (libc)Character Input.
|
* getwc_unlocked: (libc)Character Input.
|
* getwchar: (libc)Character Input.
|
* getwchar_unlocked: (libc)Character Input.
|
* getwd: (libc)Working Directory.
|
* glob64: (libc)Calling Glob.
|
* glob: (libc)Calling Glob.
|
* globfree64: (libc)More Flags for Globbing.
|
* globfree: (libc)More Flags for Globbing.
|
* gmtime: (libc)Broken-down Time.
|
* gmtime_r: (libc)Broken-down Time.
|
* grantpt: (libc)Allocation.
|
* gsignal: (libc)Signaling Yourself.
|
* gtty: (libc)BSD Terminal Modes.
|
* hasmntopt: (libc)mtab.
|
* hcreate: (libc)Hash Search Function.
|
* hcreate_r: (libc)Hash Search Function.
|
* hdestroy: (libc)Hash Search Function.
|
* hdestroy_r: (libc)Hash Search Function.
|
* hsearch: (libc)Hash Search Function.
|
* hsearch_r: (libc)Hash Search Function.
|
* htonl: (libc)Byte Order.
|
* htons: (libc)Byte Order.
|
* hypot: (libc)Exponents and Logarithms.
|
* hypotf: (libc)Exponents and Logarithms.
|
* hypotl: (libc)Exponents and Logarithms.
|
* iconv: (libc)Generic Conversion Interface.
|
* iconv_close: (libc)Generic Conversion Interface.
|
* iconv_open: (libc)Generic Conversion Interface.
|
* if_freenameindex: (libc)Interface Naming.
|
* if_indextoname: (libc)Interface Naming.
|
* if_nameindex: (libc)Interface Naming.
|
* if_nametoindex: (libc)Interface Naming.
|
* ilogb: (libc)Exponents and Logarithms.
|
* ilogbf: (libc)Exponents and Logarithms.
|
* ilogbl: (libc)Exponents and Logarithms.
|
* imaxabs: (libc)Absolute Value.
|
* imaxdiv: (libc)Integer Division.
|
* in6addr_any: (libc)Host Address Data Type.
|
* in6addr_loopback: (libc)Host Address Data Type.
|
* index: (libc)Search Functions.
|
* inet_addr: (libc)Host Address Functions.
|
* inet_aton: (libc)Host Address Functions.
|
* inet_lnaof: (libc)Host Address Functions.
|
* inet_makeaddr: (libc)Host Address Functions.
|
* inet_netof: (libc)Host Address Functions.
|
* inet_network: (libc)Host Address Functions.
|
* inet_ntoa: (libc)Host Address Functions.
|
* inet_ntop: (libc)Host Address Functions.
|
* inet_pton: (libc)Host Address Functions.
|
* initgroups: (libc)Setting Groups.
|
* initstate: (libc)BSD Random.
|
* initstate_r: (libc)BSD Random.
|
* innetgr: (libc)Netgroup Membership.
|
* ioctl: (libc)IOCTLs.
|
* isalnum: (libc)Classification of Characters.
|
* isalpha: (libc)Classification of Characters.
|
* isascii: (libc)Classification of Characters.
|
* isatty: (libc)Is It a Terminal.
|
* isblank: (libc)Classification of Characters.
|
* iscanonical: (libc)Floating Point Classes.
|
* iscntrl: (libc)Classification of Characters.
|
* isdigit: (libc)Classification of Characters.
|
* iseqsig: (libc)FP Comparison Functions.
|
* isfinite: (libc)Floating Point Classes.
|
* isgraph: (libc)Classification of Characters.
|
* isgreater: (libc)FP Comparison Functions.
|
* isgreaterequal: (libc)FP Comparison Functions.
|
* isinf: (libc)Floating Point Classes.
|
* isinff: (libc)Floating Point Classes.
|
* isinfl: (libc)Floating Point Classes.
|
* isless: (libc)FP Comparison Functions.
|
* islessequal: (libc)FP Comparison Functions.
|
* islessgreater: (libc)FP Comparison Functions.
|
* islower: (libc)Classification of Characters.
|
* isnan: (libc)Floating Point Classes.
|
* isnan: (libc)Floating Point Classes.
|
* isnanf: (libc)Floating Point Classes.
|
* isnanl: (libc)Floating Point Classes.
|
* isnormal: (libc)Floating Point Classes.
|
* isprint: (libc)Classification of Characters.
|
* ispunct: (libc)Classification of Characters.
|
* issignaling: (libc)Floating Point Classes.
|
* isspace: (libc)Classification of Characters.
|
* issubnormal: (libc)Floating Point Classes.
|
* isunordered: (libc)FP Comparison Functions.
|
* isupper: (libc)Classification of Characters.
|
* iswalnum: (libc)Classification of Wide Characters.
|
* iswalpha: (libc)Classification of Wide Characters.
|
* iswblank: (libc)Classification of Wide Characters.
|
* iswcntrl: (libc)Classification of Wide Characters.
|
* iswctype: (libc)Classification of Wide Characters.
|
* iswdigit: (libc)Classification of Wide Characters.
|
* iswgraph: (libc)Classification of Wide Characters.
|
* iswlower: (libc)Classification of Wide Characters.
|
* iswprint: (libc)Classification of Wide Characters.
|
* iswpunct: (libc)Classification of Wide Characters.
|
* iswspace: (libc)Classification of Wide Characters.
|
* iswupper: (libc)Classification of Wide Characters.
|
* iswxdigit: (libc)Classification of Wide Characters.
|
* isxdigit: (libc)Classification of Characters.
|
* iszero: (libc)Floating Point Classes.
|
* j0: (libc)Special Functions.
|
* j0f: (libc)Special Functions.
|
* j0l: (libc)Special Functions.
|
* j1: (libc)Special Functions.
|
* j1f: (libc)Special Functions.
|
* j1l: (libc)Special Functions.
|
* jn: (libc)Special Functions.
|
* jnf: (libc)Special Functions.
|
* jnl: (libc)Special Functions.
|
* jrand48: (libc)SVID Random.
|
* jrand48_r: (libc)SVID Random.
|
* kill: (libc)Signaling Another Process.
|
* killpg: (libc)Signaling Another Process.
|
* l64a: (libc)Encode Binary Data.
|
* labs: (libc)Absolute Value.
|
* lcong48: (libc)SVID Random.
|
* lcong48_r: (libc)SVID Random.
|
* ldexp: (libc)Normalization Functions.
|
* ldexpf: (libc)Normalization Functions.
|
* ldexpl: (libc)Normalization Functions.
|
* ldiv: (libc)Integer Division.
|
* lfind: (libc)Array Search Function.
|
* lgamma: (libc)Special Functions.
|
* lgamma_r: (libc)Special Functions.
|
* lgammaf: (libc)Special Functions.
|
* lgammaf_r: (libc)Special Functions.
|
* lgammal: (libc)Special Functions.
|
* lgammal_r: (libc)Special Functions.
|
* link: (libc)Hard Links.
|
* lio_listio64: (libc)Asynchronous Reads/Writes.
|
* lio_listio: (libc)Asynchronous Reads/Writes.
|
* listen: (libc)Listening.
|
* llabs: (libc)Absolute Value.
|
* lldiv: (libc)Integer Division.
|
* llogb: (libc)Exponents and Logarithms.
|
* llogbf: (libc)Exponents and Logarithms.
|
* llogbl: (libc)Exponents and Logarithms.
|
* llrint: (libc)Rounding Functions.
|
* llrintf: (libc)Rounding Functions.
|
* llrintl: (libc)Rounding Functions.
|
* llround: (libc)Rounding Functions.
|
* llroundf: (libc)Rounding Functions.
|
* llroundl: (libc)Rounding Functions.
|
* localeconv: (libc)The Lame Way to Locale Data.
|
* localtime: (libc)Broken-down Time.
|
* localtime_r: (libc)Broken-down Time.
|
* log10: (libc)Exponents and Logarithms.
|
* log10f: (libc)Exponents and Logarithms.
|
* log10l: (libc)Exponents and Logarithms.
|
* log1p: (libc)Exponents and Logarithms.
|
* log1pf: (libc)Exponents and Logarithms.
|
* log1pl: (libc)Exponents and Logarithms.
|
* log2: (libc)Exponents and Logarithms.
|
* log2f: (libc)Exponents and Logarithms.
|
* log2l: (libc)Exponents and Logarithms.
|
* log: (libc)Exponents and Logarithms.
|
* logb: (libc)Exponents and Logarithms.
|
* logbf: (libc)Exponents and Logarithms.
|
* logbl: (libc)Exponents and Logarithms.
|
* logf: (libc)Exponents and Logarithms.
|
* login: (libc)Logging In and Out.
|
* login_tty: (libc)Logging In and Out.
|
* logl: (libc)Exponents and Logarithms.
|
* logout: (libc)Logging In and Out.
|
* logwtmp: (libc)Logging In and Out.
|
* longjmp: (libc)Non-Local Details.
|
* lrand48: (libc)SVID Random.
|
* lrand48_r: (libc)SVID Random.
|
* lrint: (libc)Rounding Functions.
|
* lrintf: (libc)Rounding Functions.
|
* lrintl: (libc)Rounding Functions.
|
* lround: (libc)Rounding Functions.
|
* lroundf: (libc)Rounding Functions.
|
* lroundl: (libc)Rounding Functions.
|
* lsearch: (libc)Array Search Function.
|
* lseek64: (libc)File Position Primitive.
|
* lseek: (libc)File Position Primitive.
|
* lstat64: (libc)Reading Attributes.
|
* lstat: (libc)Reading Attributes.
|
* lutimes: (libc)File Times.
|
* madvise: (libc)Memory-mapped I/O.
|
* makecontext: (libc)System V contexts.
|
* mallinfo: (libc)Statistics of Malloc.
|
* malloc: (libc)Basic Allocation.
|
* mallopt: (libc)Malloc Tunable Parameters.
|
* mblen: (libc)Non-reentrant Character Conversion.
|
* mbrlen: (libc)Converting a Character.
|
* mbrtowc: (libc)Converting a Character.
|
* mbsinit: (libc)Keeping the state.
|
* mbsnrtowcs: (libc)Converting Strings.
|
* mbsrtowcs: (libc)Converting Strings.
|
* mbstowcs: (libc)Non-reentrant String Conversion.
|
* mbtowc: (libc)Non-reentrant Character Conversion.
|
* mcheck: (libc)Heap Consistency Checking.
|
* memalign: (libc)Aligned Memory Blocks.
|
* memccpy: (libc)Copying Strings and Arrays.
|
* memchr: (libc)Search Functions.
|
* memcmp: (libc)String/Array Comparison.
|
* memcpy: (libc)Copying Strings and Arrays.
|
* memfrob: (libc)Trivial Encryption.
|
* memmem: (libc)Search Functions.
|
* memmove: (libc)Copying Strings and Arrays.
|
* mempcpy: (libc)Copying Strings and Arrays.
|
* memrchr: (libc)Search Functions.
|
* memset: (libc)Copying Strings and Arrays.
|
* mkdir: (libc)Creating Directories.
|
* mkdtemp: (libc)Temporary Files.
|
* mkfifo: (libc)FIFO Special Files.
|
* mknod: (libc)Making Special Files.
|
* mkstemp: (libc)Temporary Files.
|
* mktemp: (libc)Temporary Files.
|
* mktime: (libc)Broken-down Time.
|
* mlock: (libc)Page Lock Functions.
|
* mlockall: (libc)Page Lock Functions.
|
* mmap64: (libc)Memory-mapped I/O.
|
* mmap: (libc)Memory-mapped I/O.
|
* modf: (libc)Rounding Functions.
|
* modff: (libc)Rounding Functions.
|
* modfl: (libc)Rounding Functions.
|
* mount: (libc)Mount-Unmount-Remount.
|
* mprobe: (libc)Heap Consistency Checking.
|
* mrand48: (libc)SVID Random.
|
* mrand48_r: (libc)SVID Random.
|
* mremap: (libc)Memory-mapped I/O.
|
* msync: (libc)Memory-mapped I/O.
|
* mtrace: (libc)Tracing malloc.
|
* munlock: (libc)Page Lock Functions.
|
* munlockall: (libc)Page Lock Functions.
|
* munmap: (libc)Memory-mapped I/O.
|
* muntrace: (libc)Tracing malloc.
|
* nan: (libc)FP Bit Twiddling.
|
* nanf: (libc)FP Bit Twiddling.
|
* nanl: (libc)FP Bit Twiddling.
|
* nanosleep: (libc)Sleeping.
|
* nearbyint: (libc)Rounding Functions.
|
* nearbyintf: (libc)Rounding Functions.
|
* nearbyintl: (libc)Rounding Functions.
|
* nextafter: (libc)FP Bit Twiddling.
|
* nextafterf: (libc)FP Bit Twiddling.
|
* nextafterl: (libc)FP Bit Twiddling.
|
* nextdown: (libc)FP Bit Twiddling.
|
* nextdownf: (libc)FP Bit Twiddling.
|
* nextdownl: (libc)FP Bit Twiddling.
|
* nexttoward: (libc)FP Bit Twiddling.
|
* nexttowardf: (libc)FP Bit Twiddling.
|
* nexttowardl: (libc)FP Bit Twiddling.
|
* nextup: (libc)FP Bit Twiddling.
|
* nextupf: (libc)FP Bit Twiddling.
|
* nextupl: (libc)FP Bit Twiddling.
|
* nftw64: (libc)Working with Directory Trees.
|
* nftw: (libc)Working with Directory Trees.
|
* ngettext: (libc)Advanced gettext functions.
|
* nice: (libc)Traditional Scheduling Functions.
|
* nl_langinfo: (libc)The Elegant and Fast Way.
|
* nrand48: (libc)SVID Random.
|
* nrand48_r: (libc)SVID Random.
|
* ntohl: (libc)Byte Order.
|
* ntohs: (libc)Byte Order.
|
* ntp_adjtime: (libc)High Accuracy Clock.
|
* ntp_gettime: (libc)High Accuracy Clock.
|
* obstack_1grow: (libc)Growing Objects.
|
* obstack_1grow_fast: (libc)Extra Fast Growing.
|
* obstack_alignment_mask: (libc)Obstacks Data Alignment.
|
* obstack_alloc: (libc)Allocation in an Obstack.
|
* obstack_base: (libc)Status of an Obstack.
|
* obstack_blank: (libc)Growing Objects.
|
* obstack_blank_fast: (libc)Extra Fast Growing.
|
* obstack_chunk_size: (libc)Obstack Chunks.
|
* obstack_copy0: (libc)Allocation in an Obstack.
|
* obstack_copy: (libc)Allocation in an Obstack.
|
* obstack_finish: (libc)Growing Objects.
|
* obstack_free: (libc)Freeing Obstack Objects.
|
* obstack_grow0: (libc)Growing Objects.
|
* obstack_grow: (libc)Growing Objects.
|
* obstack_init: (libc)Preparing for Obstacks.
|
* obstack_int_grow: (libc)Growing Objects.
|
* obstack_int_grow_fast: (libc)Extra Fast Growing.
|
* obstack_next_free: (libc)Status of an Obstack.
|
* obstack_object_size: (libc)Growing Objects.
|
* obstack_object_size: (libc)Status of an Obstack.
|
* obstack_printf: (libc)Dynamic Output.
|
* obstack_ptr_grow: (libc)Growing Objects.
|
* obstack_ptr_grow_fast: (libc)Extra Fast Growing.
|
* obstack_room: (libc)Extra Fast Growing.
|
* obstack_vprintf: (libc)Variable Arguments Output.
|
* offsetof: (libc)Structure Measurement.
|
* on_exit: (libc)Cleanups on Exit.
|
* open64: (libc)Opening and Closing Files.
|
* open: (libc)Opening and Closing Files.
|
* open_memstream: (libc)String Streams.
|
* opendir: (libc)Opening a Directory.
|
* openlog: (libc)openlog.
|
* openpty: (libc)Pseudo-Terminal Pairs.
|
* parse_printf_format: (libc)Parsing a Template String.
|
* pathconf: (libc)Pathconf.
|
* pause: (libc)Using Pause.
|
* pclose: (libc)Pipe to a Subprocess.
|
* perror: (libc)Error Messages.
|
* pipe: (libc)Creating a Pipe.
|
* popen: (libc)Pipe to a Subprocess.
|
* posix_fallocate64: (libc)Storage Allocation.
|
* posix_fallocate: (libc)Storage Allocation.
|
* posix_memalign: (libc)Aligned Memory Blocks.
|
* pow10: (libc)Exponents and Logarithms.
|
* pow10f: (libc)Exponents and Logarithms.
|
* pow10l: (libc)Exponents and Logarithms.
|
* pow: (libc)Exponents and Logarithms.
|
* powf: (libc)Exponents and Logarithms.
|
* powl: (libc)Exponents and Logarithms.
|
* pread64: (libc)I/O Primitives.
|
* pread: (libc)I/O Primitives.
|
* printf: (libc)Formatted Output Functions.
|
* printf_size: (libc)Predefined Printf Handlers.
|
* printf_size_info: (libc)Predefined Printf Handlers.
|
* psignal: (libc)Signal Messages.
|
* pthread_getattr_default_np: (libc)Default Thread Attributes.
|
* pthread_getspecific: (libc)Thread-specific Data.
|
* pthread_key_create: (libc)Thread-specific Data.
|
* pthread_key_delete: (libc)Thread-specific Data.
|
* pthread_setattr_default_np: (libc)Default Thread Attributes.
|
* pthread_setspecific: (libc)Thread-specific Data.
|
* ptsname: (libc)Allocation.
|
* ptsname_r: (libc)Allocation.
|
* putc: (libc)Simple Output.
|
* putc_unlocked: (libc)Simple Output.
|
* putchar: (libc)Simple Output.
|
* putchar_unlocked: (libc)Simple Output.
|
* putenv: (libc)Environment Access.
|
* putpwent: (libc)Writing a User Entry.
|
* puts: (libc)Simple Output.
|
* pututline: (libc)Manipulating the Database.
|
* pututxline: (libc)XPG Functions.
|
* putw: (libc)Simple Output.
|
* putwc: (libc)Simple Output.
|
* putwc_unlocked: (libc)Simple Output.
|
* putwchar: (libc)Simple Output.
|
* putwchar_unlocked: (libc)Simple Output.
|
* pwrite64: (libc)I/O Primitives.
|
* pwrite: (libc)I/O Primitives.
|
* qecvt: (libc)System V Number Conversion.
|
* qecvt_r: (libc)System V Number Conversion.
|
* qfcvt: (libc)System V Number Conversion.
|
* qfcvt_r: (libc)System V Number Conversion.
|
* qgcvt: (libc)System V Number Conversion.
|
* qsort: (libc)Array Sort Function.
|
* raise: (libc)Signaling Yourself.
|
* rand: (libc)ISO Random.
|
* rand_r: (libc)ISO Random.
|
* random: (libc)BSD Random.
|
* random_r: (libc)BSD Random.
|
* rawmemchr: (libc)Search Functions.
|
* read: (libc)I/O Primitives.
|
* readdir64: (libc)Reading/Closing Directory.
|
* readdir64_r: (libc)Reading/Closing Directory.
|
* readdir: (libc)Reading/Closing Directory.
|
* readdir_r: (libc)Reading/Closing Directory.
|
* readlink: (libc)Symbolic Links.
|
* readv: (libc)Scatter-Gather.
|
* realloc: (libc)Changing Block Size.
|
* realpath: (libc)Symbolic Links.
|
* recv: (libc)Receiving Data.
|
* recvfrom: (libc)Receiving Datagrams.
|
* recvmsg: (libc)Receiving Datagrams.
|
* regcomp: (libc)POSIX Regexp Compilation.
|
* regerror: (libc)Regexp Cleanup.
|
* regexec: (libc)Matching POSIX Regexps.
|
* regfree: (libc)Regexp Cleanup.
|
* register_printf_function: (libc)Registering New Conversions.
|
* remainder: (libc)Remainder Functions.
|
* remainderf: (libc)Remainder Functions.
|
* remainderl: (libc)Remainder Functions.
|
* remove: (libc)Deleting Files.
|
* rename: (libc)Renaming Files.
|
* rewind: (libc)File Positioning.
|
* rewinddir: (libc)Random Access Directory.
|
* rindex: (libc)Search Functions.
|
* rint: (libc)Rounding Functions.
|
* rintf: (libc)Rounding Functions.
|
* rintl: (libc)Rounding Functions.
|
* rmdir: (libc)Deleting Files.
|
* round: (libc)Rounding Functions.
|
* roundeven: (libc)Rounding Functions.
|
* roundevenf: (libc)Rounding Functions.
|
* roundevenl: (libc)Rounding Functions.
|
* roundf: (libc)Rounding Functions.
|
* roundl: (libc)Rounding Functions.
|
* rpmatch: (libc)Yes-or-No Questions.
|
* sbrk: (libc)Resizing the Data Segment.
|
* scalb: (libc)Normalization Functions.
|
* scalbf: (libc)Normalization Functions.
|
* scalbl: (libc)Normalization Functions.
|
* scalbln: (libc)Normalization Functions.
|
* scalblnf: (libc)Normalization Functions.
|
* scalblnl: (libc)Normalization Functions.
|
* scalbn: (libc)Normalization Functions.
|
* scalbnf: (libc)Normalization Functions.
|
* scalbnl: (libc)Normalization Functions.
|
* scandir64: (libc)Scanning Directory Content.
|
* scandir: (libc)Scanning Directory Content.
|
* scanf: (libc)Formatted Input Functions.
|
* sched_get_priority_max: (libc)Basic Scheduling Functions.
|
* sched_get_priority_min: (libc)Basic Scheduling Functions.
|
* sched_getaffinity: (libc)CPU Affinity.
|
* sched_getparam: (libc)Basic Scheduling Functions.
|
* sched_getscheduler: (libc)Basic Scheduling Functions.
|
* sched_rr_get_interval: (libc)Basic Scheduling Functions.
|
* sched_setaffinity: (libc)CPU Affinity.
|
* sched_setparam: (libc)Basic Scheduling Functions.
|
* sched_setscheduler: (libc)Basic Scheduling Functions.
|
* sched_yield: (libc)Basic Scheduling Functions.
|
* secure_getenv: (libc)Environment Access.
|
* seed48: (libc)SVID Random.
|
* seed48_r: (libc)SVID Random.
|
* seekdir: (libc)Random Access Directory.
|
* select: (libc)Waiting for I/O.
|
* sem_close: (libc)Semaphores.
|
* sem_destroy: (libc)Semaphores.
|
* sem_getvalue: (libc)Semaphores.
|
* sem_init: (libc)Semaphores.
|
* sem_open: (libc)Semaphores.
|
* sem_post: (libc)Semaphores.
|
* sem_timedwait: (libc)Semaphores.
|
* sem_trywait: (libc)Semaphores.
|
* sem_unlink: (libc)Semaphores.
|
* sem_wait: (libc)Semaphores.
|
* semctl: (libc)Semaphores.
|
* semget: (libc)Semaphores.
|
* semop: (libc)Semaphores.
|
* semtimedop: (libc)Semaphores.
|
* send: (libc)Sending Data.
|
* sendmsg: (libc)Receiving Datagrams.
|
* sendto: (libc)Sending Datagrams.
|
* setbuf: (libc)Controlling Buffering.
|
* setbuffer: (libc)Controlling Buffering.
|
* setcontext: (libc)System V contexts.
|
* setdomainname: (libc)Host Identification.
|
* setegid: (libc)Setting Groups.
|
* setenv: (libc)Environment Access.
|
* seteuid: (libc)Setting User ID.
|
* setfsent: (libc)fstab.
|
* setgid: (libc)Setting Groups.
|
* setgrent: (libc)Scanning All Groups.
|
* setgroups: (libc)Setting Groups.
|
* sethostent: (libc)Host Names.
|
* sethostid: (libc)Host Identification.
|
* sethostname: (libc)Host Identification.
|
* setitimer: (libc)Setting an Alarm.
|
* setjmp: (libc)Non-Local Details.
|
* setkey: (libc)DES Encryption.
|
* setkey_r: (libc)DES Encryption.
|
* setlinebuf: (libc)Controlling Buffering.
|
* setlocale: (libc)Setting the Locale.
|
* setlogmask: (libc)setlogmask.
|
* setmntent: (libc)mtab.
|
* setnetent: (libc)Networks Database.
|
* setnetgrent: (libc)Lookup Netgroup.
|
* setpayload: (libc)FP Bit Twiddling.
|
* setpayloadf: (libc)FP Bit Twiddling.
|
* setpayloadl: (libc)FP Bit Twiddling.
|
* setpayloadsig: (libc)FP Bit Twiddling.
|
* setpayloadsigf: (libc)FP Bit Twiddling.
|
* setpayloadsigl: (libc)FP Bit Twiddling.
|
* setpgid: (libc)Process Group Functions.
|
* setpgrp: (libc)Process Group Functions.
|
* setpriority: (libc)Traditional Scheduling Functions.
|
* setprotoent: (libc)Protocols Database.
|
* setpwent: (libc)Scanning All Users.
|
* setregid: (libc)Setting Groups.
|
* setreuid: (libc)Setting User ID.
|
* setrlimit64: (libc)Limits on Resources.
|
* setrlimit: (libc)Limits on Resources.
|
* setservent: (libc)Services Database.
|
* setsid: (libc)Process Group Functions.
|
* setsockopt: (libc)Socket Option Functions.
|
* setstate: (libc)BSD Random.
|
* setstate_r: (libc)BSD Random.
|
* settimeofday: (libc)High-Resolution Calendar.
|
* setuid: (libc)Setting User ID.
|
* setutent: (libc)Manipulating the Database.
|
* setutxent: (libc)XPG Functions.
|
* setvbuf: (libc)Controlling Buffering.
|
* shm_open: (libc)Memory-mapped I/O.
|
* shm_unlink: (libc)Memory-mapped I/O.
|
* shutdown: (libc)Closing a Socket.
|
* sigaction: (libc)Advanced Signal Handling.
|
* sigaddset: (libc)Signal Sets.
|
* sigaltstack: (libc)Signal Stack.
|
* sigblock: (libc)BSD Signal Handling.
|
* sigdelset: (libc)Signal Sets.
|
* sigemptyset: (libc)Signal Sets.
|
* sigfillset: (libc)Signal Sets.
|
* siginterrupt: (libc)BSD Signal Handling.
|
* sigismember: (libc)Signal Sets.
|
* siglongjmp: (libc)Non-Local Exits and Signals.
|
* sigmask: (libc)BSD Signal Handling.
|
* signal: (libc)Basic Signal Handling.
|
* signbit: (libc)FP Bit Twiddling.
|
* significand: (libc)Normalization Functions.
|
* significandf: (libc)Normalization Functions.
|
* significandl: (libc)Normalization Functions.
|
* sigpause: (libc)BSD Signal Handling.
|
* sigpending: (libc)Checking for Pending Signals.
|
* sigprocmask: (libc)Process Signal Mask.
|
* sigsetjmp: (libc)Non-Local Exits and Signals.
|
* sigsetmask: (libc)BSD Signal Handling.
|
* sigstack: (libc)Signal Stack.
|
* sigsuspend: (libc)Sigsuspend.
|
* sin: (libc)Trig Functions.
|
* sincos: (libc)Trig Functions.
|
* sincosf: (libc)Trig Functions.
|
* sincosl: (libc)Trig Functions.
|
* sinf: (libc)Trig Functions.
|
* sinh: (libc)Hyperbolic Functions.
|
* sinhf: (libc)Hyperbolic Functions.
|
* sinhl: (libc)Hyperbolic Functions.
|
* sinl: (libc)Trig Functions.
|
* sleep: (libc)Sleeping.
|
* snprintf: (libc)Formatted Output Functions.
|
* socket: (libc)Creating a Socket.
|
* socketpair: (libc)Socket Pairs.
|
* sprintf: (libc)Formatted Output Functions.
|
* sqrt: (libc)Exponents and Logarithms.
|
* sqrtf: (libc)Exponents and Logarithms.
|
* sqrtl: (libc)Exponents and Logarithms.
|
* srand48: (libc)SVID Random.
|
* srand48_r: (libc)SVID Random.
|
* srand: (libc)ISO Random.
|
* srandom: (libc)BSD Random.
|
* srandom_r: (libc)BSD Random.
|
* sscanf: (libc)Formatted Input Functions.
|
* ssignal: (libc)Basic Signal Handling.
|
* stat64: (libc)Reading Attributes.
|
* stat: (libc)Reading Attributes.
|
* stime: (libc)Simple Calendar Time.
|
* stpcpy: (libc)Copying Strings and Arrays.
|
* stpncpy: (libc)Truncating Strings.
|
* strcasecmp: (libc)String/Array Comparison.
|
* strcasestr: (libc)Search Functions.
|
* strcat: (libc)Concatenating Strings.
|
* strchr: (libc)Search Functions.
|
* strchrnul: (libc)Search Functions.
|
* strcmp: (libc)String/Array Comparison.
|
* strcoll: (libc)Collation Functions.
|
* strcpy: (libc)Copying Strings and Arrays.
|
* strcspn: (libc)Search Functions.
|
* strdup: (libc)Copying Strings and Arrays.
|
* strdupa: (libc)Copying Strings and Arrays.
|
* strerror: (libc)Error Messages.
|
* strerror_r: (libc)Error Messages.
|
* strfmon: (libc)Formatting Numbers.
|
* strfromd: (libc)Printing of Floats.
|
* strfromf: (libc)Printing of Floats.
|
* strfroml: (libc)Printing of Floats.
|
* strfry: (libc)strfry.
|
* strftime: (libc)Formatting Calendar Time.
|
* strlen: (libc)String Length.
|
* strncasecmp: (libc)String/Array Comparison.
|
* strncat: (libc)Truncating Strings.
|
* strncmp: (libc)String/Array Comparison.
|
* strncpy: (libc)Truncating Strings.
|
* strndup: (libc)Truncating Strings.
|
* strndupa: (libc)Truncating Strings.
|
* strnlen: (libc)String Length.
|
* strpbrk: (libc)Search Functions.
|
* strptime: (libc)Low-Level Time String Parsing.
|
* strrchr: (libc)Search Functions.
|
* strsep: (libc)Finding Tokens in a String.
|
* strsignal: (libc)Signal Messages.
|
* strspn: (libc)Search Functions.
|
* strstr: (libc)Search Functions.
|
* strtod: (libc)Parsing of Floats.
|
* strtof: (libc)Parsing of Floats.
|
* strtoimax: (libc)Parsing of Integers.
|
* strtok: (libc)Finding Tokens in a String.
|
* strtok_r: (libc)Finding Tokens in a String.
|
* strtol: (libc)Parsing of Integers.
|
* strtold: (libc)Parsing of Floats.
|
* strtoll: (libc)Parsing of Integers.
|
* strtoq: (libc)Parsing of Integers.
|
* strtoul: (libc)Parsing of Integers.
|
* strtoull: (libc)Parsing of Integers.
|
* strtoumax: (libc)Parsing of Integers.
|
* strtouq: (libc)Parsing of Integers.
|
* strverscmp: (libc)String/Array Comparison.
|
* strxfrm: (libc)Collation Functions.
|
* stty: (libc)BSD Terminal Modes.
|
* swapcontext: (libc)System V contexts.
|
* swprintf: (libc)Formatted Output Functions.
|
* swscanf: (libc)Formatted Input Functions.
|
* symlink: (libc)Symbolic Links.
|
* sync: (libc)Synchronizing I/O.
|
* syscall: (libc)System Calls.
|
* sysconf: (libc)Sysconf Definition.
|
* sysctl: (libc)System Parameters.
|
* syslog: (libc)syslog; vsyslog.
|
* system: (libc)Running a Command.
|
* sysv_signal: (libc)Basic Signal Handling.
|
* tan: (libc)Trig Functions.
|
* tanf: (libc)Trig Functions.
|
* tanh: (libc)Hyperbolic Functions.
|
* tanhf: (libc)Hyperbolic Functions.
|
* tanhl: (libc)Hyperbolic Functions.
|
* tanl: (libc)Trig Functions.
|
* tcdrain: (libc)Line Control.
|
* tcflow: (libc)Line Control.
|
* tcflush: (libc)Line Control.
|
* tcgetattr: (libc)Mode Functions.
|
* tcgetpgrp: (libc)Terminal Access Functions.
|
* tcgetsid: (libc)Terminal Access Functions.
|
* tcsendbreak: (libc)Line Control.
|
* tcsetattr: (libc)Mode Functions.
|
* tcsetpgrp: (libc)Terminal Access Functions.
|
* tdelete: (libc)Tree Search Function.
|
* tdestroy: (libc)Tree Search Function.
|
* telldir: (libc)Random Access Directory.
|
* tempnam: (libc)Temporary Files.
|
* textdomain: (libc)Locating gettext catalog.
|
* tfind: (libc)Tree Search Function.
|
* tgamma: (libc)Special Functions.
|
* tgammaf: (libc)Special Functions.
|
* tgammal: (libc)Special Functions.
|
* time: (libc)Simple Calendar Time.
|
* timegm: (libc)Broken-down Time.
|
* timelocal: (libc)Broken-down Time.
|
* times: (libc)Processor Time.
|
* tmpfile64: (libc)Temporary Files.
|
* tmpfile: (libc)Temporary Files.
|
* tmpnam: (libc)Temporary Files.
|
* tmpnam_r: (libc)Temporary Files.
|
* toascii: (libc)Case Conversion.
|
* tolower: (libc)Case Conversion.
|
* totalorder: (libc)FP Comparison Functions.
|
* totalorderf: (libc)FP Comparison Functions.
|
* totalorderl: (libc)FP Comparison Functions.
|
* totalordermag: (libc)FP Comparison Functions.
|
* totalordermagf: (libc)FP Comparison Functions.
|
* totalordermagl: (libc)FP Comparison Functions.
|
* toupper: (libc)Case Conversion.
|
* towctrans: (libc)Wide Character Case Conversion.
|
* towlower: (libc)Wide Character Case Conversion.
|
* towupper: (libc)Wide Character Case Conversion.
|
* trunc: (libc)Rounding Functions.
|
* truncate64: (libc)File Size.
|
* truncate: (libc)File Size.
|
* truncf: (libc)Rounding Functions.
|
* truncl: (libc)Rounding Functions.
|
* tsearch: (libc)Tree Search Function.
|
* ttyname: (libc)Is It a Terminal.
|
* ttyname_r: (libc)Is It a Terminal.
|
* twalk: (libc)Tree Search Function.
|
* tzset: (libc)Time Zone Functions.
|
* ufromfp: (libc)Rounding Functions.
|
* ufromfpf: (libc)Rounding Functions.
|
* ufromfpl: (libc)Rounding Functions.
|
* ufromfpx: (libc)Rounding Functions.
|
* ufromfpxf: (libc)Rounding Functions.
|
* ufromfpxl: (libc)Rounding Functions.
|
* ulimit: (libc)Limits on Resources.
|
* umask: (libc)Setting Permissions.
|
* umount2: (libc)Mount-Unmount-Remount.
|
* umount: (libc)Mount-Unmount-Remount.
|
* uname: (libc)Platform Type.
|
* ungetc: (libc)How Unread.
|
* ungetwc: (libc)How Unread.
|
* unlink: (libc)Deleting Files.
|
* unlockpt: (libc)Allocation.
|
* unsetenv: (libc)Environment Access.
|
* updwtmp: (libc)Manipulating the Database.
|
* utime: (libc)File Times.
|
* utimes: (libc)File Times.
|
* utmpname: (libc)Manipulating the Database.
|
* utmpxname: (libc)XPG Functions.
|
* va_arg: (libc)Argument Macros.
|
* va_copy: (libc)Argument Macros.
|
* va_end: (libc)Argument Macros.
|
* va_start: (libc)Argument Macros.
|
* valloc: (libc)Aligned Memory Blocks.
|
* vasprintf: (libc)Variable Arguments Output.
|
* verr: (libc)Error Messages.
|
* verrx: (libc)Error Messages.
|
* versionsort64: (libc)Scanning Directory Content.
|
* versionsort: (libc)Scanning Directory Content.
|
* vfork: (libc)Creating a Process.
|
* vfprintf: (libc)Variable Arguments Output.
|
* vfscanf: (libc)Variable Arguments Input.
|
* vfwprintf: (libc)Variable Arguments Output.
|
* vfwscanf: (libc)Variable Arguments Input.
|
* vlimit: (libc)Limits on Resources.
|
* vprintf: (libc)Variable Arguments Output.
|
* vscanf: (libc)Variable Arguments Input.
|
* vsnprintf: (libc)Variable Arguments Output.
|
* vsprintf: (libc)Variable Arguments Output.
|
* vsscanf: (libc)Variable Arguments Input.
|
* vswprintf: (libc)Variable Arguments Output.
|
* vswscanf: (libc)Variable Arguments Input.
|
* vsyslog: (libc)syslog; vsyslog.
|
* vtimes: (libc)Resource Usage.
|
* vwarn: (libc)Error Messages.
|
* vwarnx: (libc)Error Messages.
|
* vwprintf: (libc)Variable Arguments Output.
|
* vwscanf: (libc)Variable Arguments Input.
|
* wait3: (libc)BSD Wait Functions.
|
* wait4: (libc)Process Completion.
|
* wait: (libc)Process Completion.
|
* waitpid: (libc)Process Completion.
|
* warn: (libc)Error Messages.
|
* warnx: (libc)Error Messages.
|
* wcpcpy: (libc)Copying Strings and Arrays.
|
* wcpncpy: (libc)Truncating Strings.
|
* wcrtomb: (libc)Converting a Character.
|
* wcscasecmp: (libc)String/Array Comparison.
|
* wcscat: (libc)Concatenating Strings.
|
* wcschr: (libc)Search Functions.
|
* wcschrnul: (libc)Search Functions.
|
* wcscmp: (libc)String/Array Comparison.
|
* wcscoll: (libc)Collation Functions.
|
* wcscpy: (libc)Copying Strings and Arrays.
|
* wcscspn: (libc)Search Functions.
|
* wcsdup: (libc)Copying Strings and Arrays.
|
* wcsftime: (libc)Formatting Calendar Time.
|
* wcslen: (libc)String Length.
|
* wcsncasecmp: (libc)String/Array Comparison.
|
* wcsncat: (libc)Truncating Strings.
|
* wcsncmp: (libc)String/Array Comparison.
|
* wcsncpy: (libc)Truncating Strings.
|
* wcsnlen: (libc)String Length.
|
* wcsnrtombs: (libc)Converting Strings.
|
* wcspbrk: (libc)Search Functions.
|
* wcsrchr: (libc)Search Functions.
|
* wcsrtombs: (libc)Converting Strings.
|
* wcsspn: (libc)Search Functions.
|
* wcsstr: (libc)Search Functions.
|
* wcstod: (libc)Parsing of Floats.
|
* wcstof: (libc)Parsing of Floats.
|
* wcstoimax: (libc)Parsing of Integers.
|
* wcstok: (libc)Finding Tokens in a String.
|
* wcstol: (libc)Parsing of Integers.
|
* wcstold: (libc)Parsing of Floats.
|
* wcstoll: (libc)Parsing of Integers.
|
* wcstombs: (libc)Non-reentrant String Conversion.
|
* wcstoq: (libc)Parsing of Integers.
|
* wcstoul: (libc)Parsing of Integers.
|
* wcstoull: (libc)Parsing of Integers.
|
* wcstoumax: (libc)Parsing of Integers.
|
* wcstouq: (libc)Parsing of Integers.
|
* wcswcs: (libc)Search Functions.
|
* wcsxfrm: (libc)Collation Functions.
|
* wctob: (libc)Converting a Character.
|
* wctomb: (libc)Non-reentrant Character Conversion.
|
* wctrans: (libc)Wide Character Case Conversion.
|
* wctype: (libc)Classification of Wide Characters.
|
* wmemchr: (libc)Search Functions.
|
* wmemcmp: (libc)String/Array Comparison.
|
* wmemcpy: (libc)Copying Strings and Arrays.
|
* wmemmove: (libc)Copying Strings and Arrays.
|
* wmempcpy: (libc)Copying Strings and Arrays.
|
* wmemset: (libc)Copying Strings and Arrays.
|
* wordexp: (libc)Calling Wordexp.
|
* wordfree: (libc)Calling Wordexp.
|
* wprintf: (libc)Formatted Output Functions.
|
* write: (libc)I/O Primitives.
|
* writev: (libc)Scatter-Gather.
|
* wscanf: (libc)Formatted Input Functions.
|
* y0: (libc)Special Functions.
|
* y0f: (libc)Special Functions.
|
* y0l: (libc)Special Functions.
|
* y1: (libc)Special Functions.
|
* y1f: (libc)Special Functions.
|
* y1l: (libc)Special Functions.
|
* yn: (libc)Special Functions.
|
* ynf: (libc)Special Functions.
|
* ynl: (libc)Special Functions.
|
END-INFO-DIR-ENTRY
|
|
|
|
File: libc.info, Node: Searching and Sorting, Next: Pattern Matching, Prev: Message Translation, Up: Top
|
|
9 Searching and Sorting
|
***********************
|
|
This chapter describes functions for searching and sorting arrays of
|
arbitrary objects. You pass the appropriate comparison function to be
|
applied as an argument, along with the size of the objects in the array
|
and the total number of elements.
|
|
* Menu:
|
|
* Comparison Functions:: Defining how to compare two objects.
|
Since the sort and search facilities
|
are general, you have to specify the
|
ordering.
|
* Array Search Function:: The ‘bsearch’ function.
|
* Array Sort Function:: The ‘qsort’ function.
|
* Search/Sort Example:: An example program.
|
* Hash Search Function:: The ‘hsearch’ function.
|
* Tree Search Function:: The ‘tsearch’ function.
|
|
|
File: libc.info, Node: Comparison Functions, Next: Array Search Function, Up: Searching and Sorting
|
|
9.1 Defining the Comparison Function
|
====================================
|
|
In order to use the sorted array library functions, you have to describe
|
how to compare the elements of the array.
|
|
To do this, you supply a comparison function to compare two elements
|
of the array. The library will call this function, passing as arguments
|
pointers to two array elements to be compared. Your comparison function
|
should return a value the way ‘strcmp’ (*note String/Array Comparison::)
|
does: negative if the first argument is “less” than the second, zero if
|
they are “equal”, and positive if the first argument is “greater”.
|
|
Here is an example of a comparison function which works with an array
|
of numbers of type ‘double’:
|
|
int
|
compare_doubles (const void *a, const void *b)
|
{
|
const double *da = (const double *) a;
|
const double *db = (const double *) b;
|
|
return (*da > *db) - (*da < *db);
|
}
|
|
The header file ‘stdlib.h’ defines a name for the data type of
|
comparison functions. This type is a GNU extension.
|
|
int comparison_fn_t (const void *, const void *);
|
|
|
File: libc.info, Node: Array Search Function, Next: Array Sort Function, Prev: Comparison Functions, Up: Searching and Sorting
|
|
9.2 Array Search Function
|
=========================
|
|
Generally searching for a specific element in an array means that
|
potentially all elements must be checked. The GNU C Library contains
|
functions to perform linear search. The prototypes for the following
|
two functions can be found in ‘search.h’.
|
|
-- Function: void * lfind (const void *KEY, const void *BASE, size_t
|
*NMEMB, size_t SIZE, comparison_fn_t COMPAR)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘lfind’ function searches in the array with ‘*NMEMB’ elements
|
of SIZE bytes pointed to by BASE for an element which matches the
|
one pointed to by KEY. The function pointed to by COMPAR is used
|
to decide whether two elements match.
|
|
The return value is a pointer to the matching element in the array
|
starting at BASE if it is found. If no matching element is
|
available ‘NULL’ is returned.
|
|
The mean runtime of this function is ‘*NMEMB’/2. This function
|
should only be used if elements often get added to or deleted from
|
the array in which case it might not be useful to sort the array
|
before searching.
|
|
-- Function: void * lsearch (const void *KEY, void *BASE, size_t
|
*NMEMB, size_t SIZE, comparison_fn_t COMPAR)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘lsearch’ function is similar to the ‘lfind’ function. It
|
searches the given array for an element and returns it if found.
|
The difference is that if no matching element is found the
|
‘lsearch’ function adds the object pointed to by KEY (with a size
|
of SIZE bytes) at the end of the array and it increments the value
|
of ‘*NMEMB’ to reflect this addition.
|
|
This means for the caller that if it is not sure that the array
|
contains the element one is searching for the memory allocated for
|
the array starting at BASE must have room for at least SIZE more
|
bytes. If one is sure the element is in the array it is better to
|
use ‘lfind’ so having more room in the array is always necessary
|
when calling ‘lsearch’.
|
|
To search a sorted array for an element matching the key, use the
|
‘bsearch’ function. The prototype for this function is in the header
|
file ‘stdlib.h’.
|
|
-- Function: void * bsearch (const void *KEY, const void *ARRAY, size_t
|
COUNT, size_t SIZE, comparison_fn_t COMPARE)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘bsearch’ function searches the sorted array ARRAY for an
|
object that is equivalent to KEY. The array contains COUNT
|
elements, each of which is of size SIZE bytes.
|
|
The COMPARE function is used to perform the comparison. This
|
function is called with two pointer arguments and should return an
|
integer less than, equal to, or greater than zero corresponding to
|
whether its first argument is considered less than, equal to, or
|
greater than its second argument. The elements of the ARRAY must
|
already be sorted in ascending order according to this comparison
|
function.
|
|
The return value is a pointer to the matching array element, or a
|
null pointer if no match is found. If the array contains more than
|
one element that matches, the one that is returned is unspecified.
|
|
This function derives its name from the fact that it is implemented
|
using the binary search algorithm.
|
|
|
File: libc.info, Node: Array Sort Function, Next: Search/Sort Example, Prev: Array Search Function, Up: Searching and Sorting
|
|
9.3 Array Sort Function
|
=======================
|
|
To sort an array using an arbitrary comparison function, use the ‘qsort’
|
function. The prototype for this function is in ‘stdlib.h’.
|
|
-- Function: void qsort (void *ARRAY, size_t COUNT, size_t SIZE,
|
comparison_fn_t COMPARE)
|
Preliminary: | MT-Safe | AS-Safe | AC-Unsafe corrupt | *Note POSIX
|
Safety Concepts::.
|
|
The ‘qsort’ function sorts the array ARRAY. The array contains
|
COUNT elements, each of which is of size SIZE.
|
|
The COMPARE function is used to perform the comparison on the array
|
elements. This function is called with two pointer arguments and
|
should return an integer less than, equal to, or greater than zero
|
corresponding to whether its first argument is considered less
|
than, equal to, or greater than its second argument.
|
|
*Warning:* If two objects compare as equal, their order after
|
sorting is unpredictable. That is to say, the sorting is not
|
stable. This can make a difference when the comparison considers
|
only part of the elements. Two elements with the same sort key may
|
differ in other respects.
|
|
Although the object addresses passed to the comparison function lie
|
within the array, they need not correspond with the original
|
locations of those objects because the sorting algorithm may swap
|
around objects in the array before making some comparisons. The
|
only way to perform a stable sort with ‘qsort’ is to first augment
|
the objects with a monotonic counter of some kind.
|
|
Here is a simple example of sorting an array of doubles in
|
numerical order, using the comparison function defined above (*note
|
Comparison Functions::):
|
|
{
|
double *array;
|
int size;
|
…
|
qsort (array, size, sizeof (double), compare_doubles);
|
}
|
|
The ‘qsort’ function derives its name from the fact that it was
|
originally implemented using the “quick sort” algorithm.
|
|
The implementation of ‘qsort’ in this library might not be an
|
in-place sort and might thereby use an extra amount of memory to
|
store the array.
|
|
|
File: libc.info, Node: Search/Sort Example, Next: Hash Search Function, Prev: Array Sort Function, Up: Searching and Sorting
|
|
9.4 Searching and Sorting Example
|
=================================
|
|
Here is an example showing the use of ‘qsort’ and ‘bsearch’ with an
|
array of structures. The objects in the array are sorted by comparing
|
their ‘name’ fields with the ‘strcmp’ function. Then, we can look up
|
individual objects based on their names.
|
|
|
#include <stdlib.h>
|
#include <stdio.h>
|
#include <string.h>
|
|
/* Define an array of critters to sort. */
|
|
struct critter
|
{
|
const char *name;
|
const char *species;
|
};
|
|
struct critter muppets[] =
|
{
|
{"Kermit", "frog"},
|
{"Piggy", "pig"},
|
{"Gonzo", "whatever"},
|
{"Fozzie", "bear"},
|
{"Sam", "eagle"},
|
{"Robin", "frog"},
|
{"Animal", "animal"},
|
{"Camilla", "chicken"},
|
{"Sweetums", "monster"},
|
{"Dr. Strangepork", "pig"},
|
{"Link Hogthrob", "pig"},
|
{"Zoot", "human"},
|
{"Dr. Bunsen Honeydew", "human"},
|
{"Beaker", "human"},
|
{"Swedish Chef", "human"}
|
};
|
|
int count = sizeof (muppets) / sizeof (struct critter);
|
|
|
|
/* This is the comparison function used for sorting and searching. */
|
|
int
|
critter_cmp (const void *v1, const void *v2)
|
{
|
const struct critter *c1 = v1;
|
const struct critter *c2 = v2;
|
|
return strcmp (c1->name, c2->name);
|
}
|
|
|
/* Print information about a critter. */
|
|
void
|
print_critter (const struct critter *c)
|
{
|
printf ("%s, the %s\n", c->name, c->species);
|
}
|
|
|
/* Do the lookup into the sorted array. */
|
|
void
|
find_critter (const char *name)
|
{
|
struct critter target, *result;
|
target.name = name;
|
result = bsearch (&target, muppets, count, sizeof (struct critter),
|
critter_cmp);
|
if (result)
|
print_critter (result);
|
else
|
printf ("Couldn't find %s.\n", name);
|
}
|
|
/* Main program. */
|
|
int
|
main (void)
|
{
|
int i;
|
|
for (i = 0; i < count; i++)
|
print_critter (&muppets[i]);
|
printf ("\n");
|
|
qsort (muppets, count, sizeof (struct critter), critter_cmp);
|
|
for (i = 0; i < count; i++)
|
print_critter (&muppets[i]);
|
printf ("\n");
|
|
find_critter ("Kermit");
|
find_critter ("Gonzo");
|
find_critter ("Janice");
|
|
return 0;
|
}
|
|
The output from this program looks like:
|
|
Kermit, the frog
|
Piggy, the pig
|
Gonzo, the whatever
|
Fozzie, the bear
|
Sam, the eagle
|
Robin, the frog
|
Animal, the animal
|
Camilla, the chicken
|
Sweetums, the monster
|
Dr. Strangepork, the pig
|
Link Hogthrob, the pig
|
Zoot, the human
|
Dr. Bunsen Honeydew, the human
|
Beaker, the human
|
Swedish Chef, the human
|
|
Animal, the animal
|
Beaker, the human
|
Camilla, the chicken
|
Dr. Bunsen Honeydew, the human
|
Dr. Strangepork, the pig
|
Fozzie, the bear
|
Gonzo, the whatever
|
Kermit, the frog
|
Link Hogthrob, the pig
|
Piggy, the pig
|
Robin, the frog
|
Sam, the eagle
|
Swedish Chef, the human
|
Sweetums, the monster
|
Zoot, the human
|
|
Kermit, the frog
|
Gonzo, the whatever
|
Couldn't find Janice.
|
|
|
File: libc.info, Node: Hash Search Function, Next: Tree Search Function, Prev: Search/Sort Example, Up: Searching and Sorting
|
|
9.5 The ‘hsearch’ function.
|
===========================
|
|
The functions mentioned so far in this chapter are for searching in a
|
sorted or unsorted array. There are other methods to organize
|
information which later should be searched. The costs of insert, delete
|
and search differ. One possible implementation is using hashing tables.
|
The following functions are declared in the header file ‘search.h’.
|
|
-- Function: int hcreate (size_t NEL)
|
Preliminary: | MT-Unsafe race:hsearch | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘hcreate’ function creates a hashing table which can contain at
|
least NEL elements. There is no possibility to grow this table so
|
it is necessary to choose the value for NEL wisely. The method
|
used to implement this function might make it necessary to make the
|
number of elements in the hashing table larger than the expected
|
maximal number of elements. Hashing tables usually work
|
inefficiently if they are filled 80% or more. The constant access
|
time guaranteed by hashing can only be achieved if few collisions
|
exist. See Knuth’s “The Art of Computer Programming, Part 3:
|
Searching and Sorting” for more information.
|
|
The weakest aspect of this function is that there can be at most
|
one hashing table used through the whole program. The table is
|
allocated in local memory out of control of the programmer. As an
|
extension the GNU C Library provides an additional set of functions
|
with a reentrant interface which provides a similar interface but
|
which allows keeping arbitrarily many hashing tables.
|
|
It is possible to use more than one hashing table in the program
|
run if the former table is first destroyed by a call to ‘hdestroy’.
|
|
The function returns a non-zero value if successful. If it returns
|
zero, something went wrong. This could either mean there is
|
already a hashing table in use or the program ran out of memory.
|
|
-- Function: void hdestroy (void)
|
Preliminary: | MT-Unsafe race:hsearch | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘hdestroy’ function can be used to free all the resources
|
allocated in a previous call of ‘hcreate’. After a call to this
|
function it is again possible to call ‘hcreate’ and allocate a new
|
table with possibly different size.
|
|
It is important to remember that the elements contained in the
|
hashing table at the time ‘hdestroy’ is called are _not_ freed by
|
this function. It is the responsibility of the program code to
|
free those strings (if necessary at all). Freeing all the element
|
memory is not possible without extra, separately kept information
|
since there is no function to iterate through all available
|
elements in the hashing table. If it is really necessary to free a
|
table and all elements the programmer has to keep a list of all
|
table elements and before calling ‘hdestroy’ s/he has to free all
|
element’s data using this list. This is a very unpleasant
|
mechanism and it also shows that this kind of hashing table is
|
mainly meant for tables which are created once and used until the
|
end of the program run.
|
|
Entries of the hashing table and keys for the search are defined
|
using this type:
|
|
-- Data type: struct ENTRY
|
Both elements of this structure are pointers to zero-terminated
|
strings. This is a limiting restriction of the functionality of
|
the ‘hsearch’ functions. They can only be used for data sets which
|
use the NUL character always and solely to terminate the records.
|
It is not possible to handle general binary data.
|
|
‘char *key’
|
Pointer to a zero-terminated string of characters describing
|
the key for the search or the element in the hashing table.
|
‘char *data’
|
Pointer to a zero-terminated string of characters describing
|
the data. If the functions will be called only for searching
|
an existing entry this element might stay undefined since it
|
is not used.
|
|
-- Function: ENTRY * hsearch (ENTRY ITEM, ACTION ACTION)
|
Preliminary: | MT-Unsafe race:hsearch | AS-Unsafe | AC-Unsafe
|
corrupt/action==ENTER | *Note POSIX Safety Concepts::.
|
|
To search in a hashing table created using ‘hcreate’ the ‘hsearch’
|
function must be used. This function can perform a simple search
|
for an element (if ACTION has the value ‘FIND’) or it can
|
alternatively insert the key element into the hashing table.
|
Entries are never replaced.
|
|
The key is denoted by a pointer to an object of type ‘ENTRY’. For
|
locating the corresponding position in the hashing table only the
|
‘key’ element of the structure is used.
|
|
If an entry with a matching key is found the ACTION parameter is
|
irrelevant. The found entry is returned. If no matching entry is
|
found and the ACTION parameter has the value ‘FIND’ the function
|
returns a ‘NULL’ pointer. If no entry is found and the ACTION
|
parameter has the value ‘ENTER’ a new entry is added to the hashing
|
table which is initialized with the parameter ITEM. A pointer to
|
the newly added entry is returned.
|
|
As mentioned before, the hashing table used by the functions
|
described so far is global and there can be at any time at most one
|
hashing table in the program. A solution is to use the following
|
functions which are a GNU extension. All have in common that they
|
operate on a hashing table which is described by the content of an
|
object of the type ‘struct hsearch_data’. This type should be treated
|
as opaque, none of its members should be changed directly.
|
|
-- Function: int hcreate_r (size_t NEL, struct hsearch_data *HTAB)
|
Preliminary: | MT-Safe race:htab | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘hcreate_r’ function initializes the object pointed to by HTAB
|
to contain a hashing table with at least NEL elements. So this
|
function is equivalent to the ‘hcreate’ function except that the
|
initialized data structure is controlled by the user.
|
|
This allows having more than one hashing table at one time. The
|
memory necessary for the ‘struct hsearch_data’ object can be
|
allocated dynamically. It must be initialized with zero before
|
calling this function.
|
|
The return value is non-zero if the operation was successful. If
|
the return value is zero, something went wrong, which probably
|
means the program ran out of memory.
|
|
-- Function: void hdestroy_r (struct hsearch_data *HTAB)
|
Preliminary: | MT-Safe race:htab | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘hdestroy_r’ function frees all resources allocated by the
|
‘hcreate_r’ function for this very same object HTAB. As for
|
‘hdestroy’ it is the program’s responsibility to free the strings
|
for the elements of the table.
|
|
-- Function: int hsearch_r (ENTRY ITEM, ACTION ACTION, ENTRY **RETVAL,
|
struct hsearch_data *HTAB)
|
Preliminary: | MT-Safe race:htab | AS-Safe | AC-Unsafe
|
corrupt/action==ENTER | *Note POSIX Safety Concepts::.
|
|
The ‘hsearch_r’ function is equivalent to ‘hsearch’. The meaning
|
of the first two arguments is identical. But instead of operating
|
on a single global hashing table the function works on the table
|
described by the object pointed to by HTAB (which is initialized by
|
a call to ‘hcreate_r’).
|
|
Another difference to ‘hcreate’ is that the pointer to the found
|
entry in the table is not the return value of the function. It is
|
returned by storing it in a pointer variable pointed to by the
|
RETVAL parameter. The return value of the function is an integer
|
value indicating success if it is non-zero and failure if it is
|
zero. In the latter case the global variable ERRNO signals the
|
reason for the failure.
|
|
‘ENOMEM’
|
The table is filled and ‘hsearch_r’ was called with a so far
|
unknown key and ACTION set to ‘ENTER’.
|
‘ESRCH’
|
The ACTION parameter is ‘FIND’ and no corresponding element is
|
found in the table.
|
|
|
File: libc.info, Node: Tree Search Function, Prev: Hash Search Function, Up: Searching and Sorting
|
|
9.6 The ‘tsearch’ function.
|
===========================
|
|
Another common form to organize data for efficient search is to use
|
trees. The ‘tsearch’ function family provides a nice interface to
|
functions to organize possibly large amounts of data by providing a mean
|
access time proportional to the logarithm of the number of elements.
|
The GNU C Library implementation even guarantees that this bound is
|
never exceeded even for input data which cause problems for simple
|
binary tree implementations.
|
|
The functions described in the chapter are all described in the System V
|
and X/Open specifications and are therefore quite portable.
|
|
In contrast to the ‘hsearch’ functions the ‘tsearch’ functions can be
|
used with arbitrary data and not only zero-terminated strings.
|
|
The ‘tsearch’ functions have the advantage that no function to
|
initialize data structures is necessary. A simple pointer of type ‘void
|
*’ initialized to ‘NULL’ is a valid tree and can be extended or
|
searched. The prototypes for these functions can be found in the header
|
file ‘search.h’.
|
|
-- Function: void * tsearch (const void *KEY, void **ROOTP,
|
comparison_fn_t COMPAR)
|
Preliminary: | MT-Safe race:rootp | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘tsearch’ function searches in the tree pointed to by ‘*ROOTP’
|
for an element matching KEY. The function pointed to by COMPAR is
|
used to determine whether two elements match. *Note Comparison
|
Functions::, for a specification of the functions which can be used
|
for the COMPAR parameter.
|
|
If the tree does not contain a matching entry the KEY value will be
|
added to the tree. ‘tsearch’ does not make a copy of the object
|
pointed to by KEY (how could it since the size is unknown).
|
Instead it adds a reference to this object which means the object
|
must be available as long as the tree data structure is used.
|
|
The tree is represented by a pointer to a pointer since it is
|
sometimes necessary to change the root node of the tree. So it
|
must not be assumed that the variable pointed to by ROOTP has the
|
same value after the call. This also shows that it is not safe to
|
call the ‘tsearch’ function more than once at the same time using
|
the same tree. It is no problem to run it more than once at a time
|
on different trees.
|
|
The return value is a pointer to the matching element in the tree.
|
If a new element was created the pointer points to the new data
|
(which is in fact KEY). If an entry had to be created and the
|
program ran out of space ‘NULL’ is returned.
|
|
-- Function: void * tfind (const void *KEY, void *const *ROOTP,
|
comparison_fn_t COMPAR)
|
Preliminary: | MT-Safe race:rootp | AS-Safe | AC-Safe | *Note POSIX
|
Safety Concepts::.
|
|
The ‘tfind’ function is similar to the ‘tsearch’ function. It
|
locates an element matching the one pointed to by KEY and returns a
|
pointer to this element. But if no matching element is available
|
no new element is entered (note that the ROOTP parameter points to
|
a constant pointer). Instead the function returns ‘NULL’.
|
|
Another advantage of the ‘tsearch’ functions in contrast to the
|
‘hsearch’ functions is that there is an easy way to remove elements.
|
|
-- Function: void * tdelete (const void *KEY, void **ROOTP,
|
comparison_fn_t COMPAR)
|
Preliminary: | MT-Safe race:rootp | AS-Unsafe heap | AC-Unsafe
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
To remove a specific element matching KEY from the tree ‘tdelete’
|
can be used. It locates the matching element using the same method
|
as ‘tfind’. The corresponding element is then removed and a
|
pointer to the parent of the deleted node is returned by the
|
function. If there is no matching entry in the tree nothing can be
|
deleted and the function returns ‘NULL’. If the root of the tree
|
is deleted ‘tdelete’ returns some unspecified value not equal to
|
‘NULL’.
|
|
-- Function: void tdestroy (void *VROOT, __free_fn_t FREEFCT)
|
Preliminary: | MT-Safe | AS-Unsafe heap | AC-Unsafe mem | *Note
|
POSIX Safety Concepts::.
|
|
If the complete search tree has to be removed one can use
|
‘tdestroy’. It frees all resources allocated by the ‘tsearch’
|
functions to generate the tree pointed to by VROOT.
|
|
For the data in each tree node the function FREEFCT is called. The
|
pointer to the data is passed as the argument to the function. If
|
no such work is necessary FREEFCT must point to a function doing
|
nothing. It is called in any case.
|
|
This function is a GNU extension and not covered by the System V or
|
X/Open specifications.
|
|
In addition to the functions to create and destroy the tree data
|
structure, there is another function which allows you to apply a
|
function to all elements of the tree. The function must have this type:
|
|
void __action_fn_t (const void *nodep, VISIT value, int level);
|
|
The NODEP is the data value of the current node (once given as the
|
KEY argument to ‘tsearch’). LEVEL is a numeric value which corresponds
|
to the depth of the current node in the tree. The root node has the
|
depth 0 and its children have a depth of 1 and so on. The ‘VISIT’ type
|
is an enumeration type.
|
|
-- Data Type: VISIT
|
The ‘VISIT’ value indicates the status of the current node in the
|
tree and how the function is called. The status of a node is
|
either ‘leaf’ or ‘internal node’. For each leaf node the function
|
is called exactly once, for each internal node it is called three
|
times: before the first child is processed, after the first child
|
is processed and after both children are processed. This makes it
|
possible to handle all three methods of tree traversal (or even a
|
combination of them).
|
|
‘preorder’
|
The current node is an internal node and the function is
|
called before the first child was processed.
|
‘postorder’
|
The current node is an internal node and the function is
|
called after the first child was processed.
|
‘endorder’
|
The current node is an internal node and the function is
|
called after the second child was processed.
|
‘leaf’
|
The current node is a leaf.
|
|
-- Function: void twalk (const void *ROOT, __action_fn_t ACTION)
|
Preliminary: | MT-Safe race:root | AS-Safe | AC-Safe | *Note POSIX
|
Safety Concepts::.
|
|
For each node in the tree with a node pointed to by ROOT, the
|
‘twalk’ function calls the function provided by the parameter
|
ACTION. For leaf nodes the function is called exactly once with
|
VALUE set to ‘leaf’. For internal nodes the function is called
|
three times, setting the VALUE parameter or ACTION to the
|
appropriate value. The LEVEL argument for the ACTION function is
|
computed while descending the tree by increasing the value by one
|
for each descent to a child, starting with the value 0 for the root
|
node.
|
|
Since the functions used for the ACTION parameter to ‘twalk’ must
|
not modify the tree data, it is safe to run ‘twalk’ in more than
|
one thread at the same time, working on the same tree. It is also
|
safe to call ‘tfind’ in parallel. Functions which modify the tree
|
must not be used, otherwise the behavior is undefined.
|
|
|
File: libc.info, Node: Pattern Matching, Next: I/O Overview, Prev: Searching and Sorting, Up: Top
|
|
10 Pattern Matching
|
*******************
|
|
The GNU C Library provides pattern matching facilities for two kinds of
|
patterns: regular expressions and file-name wildcards. The library also
|
provides a facility for expanding variable and command references and
|
parsing text into words in the way the shell does.
|
|
* Menu:
|
|
* Wildcard Matching:: Matching a wildcard pattern against a single string.
|
* Globbing:: Finding the files that match a wildcard pattern.
|
* Regular Expressions:: Matching regular expressions against strings.
|
* Word Expansion:: Expanding shell variables, nested commands,
|
arithmetic, and wildcards.
|
This is what the shell does with shell commands.
|
|
|
File: libc.info, Node: Wildcard Matching, Next: Globbing, Up: Pattern Matching
|
|
10.1 Wildcard Matching
|
======================
|
|
This section describes how to match a wildcard pattern against a
|
particular string. The result is a yes or no answer: does the string
|
fit the pattern or not. The symbols described here are all declared in
|
‘fnmatch.h’.
|
|
-- Function: int fnmatch (const char *PATTERN, const char *STRING, int
|
FLAGS)
|
Preliminary: | MT-Safe env locale | AS-Unsafe heap | AC-Unsafe mem
|
| *Note POSIX Safety Concepts::.
|
|
This function tests whether the string STRING matches the pattern
|
PATTERN. It returns ‘0’ if they do match; otherwise, it returns
|
the nonzero value ‘FNM_NOMATCH’. The arguments PATTERN and STRING
|
are both strings.
|
|
The argument FLAGS is a combination of flag bits that alter the
|
details of matching. See below for a list of the defined flags.
|
|
In the GNU C Library, ‘fnmatch’ might sometimes report “errors” by
|
returning nonzero values that are not equal to ‘FNM_NOMATCH’.
|
|
These are the available flags for the FLAGS argument:
|
|
‘FNM_FILE_NAME’
|
Treat the ‘/’ character specially, for matching file names. If
|
this flag is set, wildcard constructs in PATTERN cannot match ‘/’
|
in STRING. Thus, the only way to match ‘/’ is with an explicit ‘/’
|
in PATTERN.
|
|
‘FNM_PATHNAME’
|
This is an alias for ‘FNM_FILE_NAME’; it comes from POSIX.2. We
|
don’t recommend this name because we don’t use the term “pathname”
|
for file names.
|
|
‘FNM_PERIOD’
|
Treat the ‘.’ character specially if it appears at the beginning of
|
STRING. If this flag is set, wildcard constructs in PATTERN cannot
|
match ‘.’ as the first character of STRING.
|
|
If you set both ‘FNM_PERIOD’ and ‘FNM_FILE_NAME’, then the special
|
treatment applies to ‘.’ following ‘/’ as well as to ‘.’ at the
|
beginning of STRING. (The shell uses the ‘FNM_PERIOD’ and
|
‘FNM_FILE_NAME’ flags together for matching file names.)
|
|
‘FNM_NOESCAPE’
|
Don’t treat the ‘\’ character specially in patterns. Normally, ‘\’
|
quotes the following character, turning off its special meaning (if
|
any) so that it matches only itself. When quoting is enabled, the
|
pattern ‘\?’ matches only the string ‘?’, because the question mark
|
in the pattern acts like an ordinary character.
|
|
If you use ‘FNM_NOESCAPE’, then ‘\’ is an ordinary character.
|
|
‘FNM_LEADING_DIR’
|
Ignore a trailing sequence of characters starting with a ‘/’ in
|
STRING; that is to say, test whether STRING starts with a directory
|
name that PATTERN matches.
|
|
If this flag is set, either ‘foo*’ or ‘foobar’ as a pattern would
|
match the string ‘foobar/frobozz’.
|
|
‘FNM_CASEFOLD’
|
Ignore case in comparing STRING to PATTERN.
|
|
‘FNM_EXTMATCH’
|
Besides the normal patterns, also recognize the extended patterns
|
introduced in ‘ksh’. The patterns are written in the form
|
explained in the following table where PATTERN-LIST is a ‘|’
|
separated list of patterns.
|
|
‘?(PATTERN-LIST)’
|
The pattern matches if zero or one occurrences of any of the
|
patterns in the PATTERN-LIST allow matching the input string.
|
|
‘*(PATTERN-LIST)’
|
The pattern matches if zero or more occurrences of any of the
|
patterns in the PATTERN-LIST allow matching the input string.
|
|
‘+(PATTERN-LIST)’
|
The pattern matches if one or more occurrences of any of the
|
patterns in the PATTERN-LIST allow matching the input string.
|
|
‘@(PATTERN-LIST)’
|
The pattern matches if exactly one occurrence of any of the
|
patterns in the PATTERN-LIST allows matching the input string.
|
|
‘!(PATTERN-LIST)’
|
The pattern matches if the input string cannot be matched with
|
any of the patterns in the PATTERN-LIST.
|
|
|
File: libc.info, Node: Globbing, Next: Regular Expressions, Prev: Wildcard Matching, Up: Pattern Matching
|
|
10.2 Globbing
|
=============
|
|
The archetypal use of wildcards is for matching against the files in a
|
directory, and making a list of all the matches. This is called
|
"globbing".
|
|
You could do this using ‘fnmatch’, by reading the directory entries
|
one by one and testing each one with ‘fnmatch’. But that would be slow
|
(and complex, since you would have to handle subdirectories by hand).
|
|
The library provides a function ‘glob’ to make this particular use of
|
wildcards convenient. ‘glob’ and the other symbols in this section are
|
declared in ‘glob.h’.
|
|
* Menu:
|
|
* Calling Glob:: Basic use of ‘glob’.
|
* Flags for Globbing:: Flags that enable various options in ‘glob’.
|
* More Flags for Globbing:: GNU specific extensions to ‘glob’.
|
|
|
File: libc.info, Node: Calling Glob, Next: Flags for Globbing, Up: Globbing
|
|
10.2.1 Calling ‘glob’
|
---------------------
|
|
The result of globbing is a vector of file names (strings). To return
|
this vector, ‘glob’ uses a special data type, ‘glob_t’, which is a
|
structure. You pass ‘glob’ the address of the structure, and it fills
|
in the structure’s fields to tell you about the results.
|
|
-- Data Type: glob_t
|
This data type holds a pointer to a word vector. More precisely,
|
it records both the address of the word vector and its size. The
|
GNU implementation contains some more fields which are non-standard
|
extensions.
|
|
‘gl_pathc’
|
The number of elements in the vector, excluding the initial
|
null entries if the GLOB_DOOFFS flag is used (see gl_offs
|
below).
|
|
‘gl_pathv’
|
The address of the vector. This field has type ‘char **’.
|
|
‘gl_offs’
|
The offset of the first real element of the vector, from its
|
nominal address in the ‘gl_pathv’ field. Unlike the other
|
fields, this is always an input to ‘glob’, rather than an
|
output from it.
|
|
If you use a nonzero offset, then that many elements at the
|
beginning of the vector are left empty. (The ‘glob’ function
|
fills them with null pointers.)
|
|
The ‘gl_offs’ field is meaningful only if you use the
|
‘GLOB_DOOFFS’ flag. Otherwise, the offset is always zero
|
regardless of what is in this field, and the first real
|
element comes at the beginning of the vector.
|
|
‘gl_closedir’
|
The address of an alternative implementation of the ‘closedir’
|
function. It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in
|
the flag parameter. The type of this field is
|
‘void (*) (void *)’.
|
|
This is a GNU extension.
|
|
‘gl_readdir’
|
The address of an alternative implementation of the ‘readdir’
|
function used to read the contents of a directory. It is used
|
if the ‘GLOB_ALTDIRFUNC’ bit is set in the flag parameter.
|
The type of this field is ‘struct dirent *(*) (void *)’.
|
|
An implementation of ‘gl_readdir’ needs to initialize the
|
following members of the ‘struct dirent’ object:
|
|
‘d_type’
|
This member should be set to the file type of the entry
|
if it is known. Otherwise, the value ‘DT_UNKNOWN’ can be
|
used. The ‘glob’ function may use the specified file
|
type to avoid callbacks in cases where the file type
|
indicates that the data is not required.
|
|
‘d_ino’
|
This member needs to be non-zero, otherwise ‘glob’ may
|
skip the current entry and call the ‘gl_readdir’ callback
|
function again to retrieve another entry.
|
|
‘d_name’
|
This member must be set to the name of the entry. It
|
must be null-terminated.
|
|
The example below shows how to allocate a ‘struct dirent’
|
object containing a given name.
|
|
|
#include <dirent.h>
|
#include <errno.h>
|
#include <stddef.h>
|
#include <stdlib.h>
|
#include <string.h>
|
|
struct dirent *
|
mkdirent (const char *name)
|
{
|
size_t dirent_size = offsetof (struct dirent, d_name) + 1;
|
size_t name_length = strlen (name);
|
size_t total_size = dirent_size + name_length;
|
if (total_size < dirent_size)
|
{
|
errno = ENOMEM;
|
return NULL;
|
}
|
struct dirent *result = malloc (total_size);
|
if (result == NULL)
|
return NULL;
|
result->d_type = DT_UNKNOWN;
|
result->d_ino = 1; /* Do not skip this entry. */
|
memcpy (result->d_name, name, name_length + 1);
|
return result;
|
}
|
|
The ‘glob’ function reads the ‘struct dirent’ members listed
|
above and makes a copy of the file name in the ‘d_name’ member
|
immediately after the ‘gl_readdir’ callback function returns.
|
Future invocations of any of the callback functions may
|
dealloacte or reuse the buffer. It is the responsibility of
|
the caller of the ‘glob’ function to allocate and deallocate
|
the buffer, around the call to ‘glob’ or using the callback
|
functions. For example, an application could allocate the
|
buffer in the ‘gl_readdir’ callback function, and deallocate
|
it in the ‘gl_closedir’ callback function.
|
|
The ‘gl_readdir’ member is a GNU extension.
|
|
‘gl_opendir’
|
The address of an alternative implementation of the ‘opendir’
|
function. It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in
|
the flag parameter. The type of this field is
|
‘void *(*) (const char *)’.
|
|
This is a GNU extension.
|
|
‘gl_stat’
|
The address of an alternative implementation of the ‘stat’
|
function to get information about an object in the filesystem.
|
It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in the flag
|
parameter. The type of this field is
|
‘int (*) (const char *, struct stat *)’.
|
|
This is a GNU extension.
|
|
‘gl_lstat’
|
The address of an alternative implementation of the ‘lstat’
|
function to get information about an object in the
|
filesystems, not following symbolic links. It is used if the
|
‘GLOB_ALTDIRFUNC’ bit is set in the flag parameter. The type
|
of this field is ‘int (*) (const char *, struct stat *)’.
|
|
This is a GNU extension.
|
|
‘gl_flags’
|
The flags used when ‘glob’ was called. In addition,
|
‘GLOB_MAGCHAR’ might be set. See *note Flags for Globbing::
|
for more details.
|
|
This is a GNU extension.
|
|
For use in the ‘glob64’ function ‘glob.h’ contains another definition
|
for a very similar type. ‘glob64_t’ differs from ‘glob_t’ only in the
|
types of the members ‘gl_readdir’, ‘gl_stat’, and ‘gl_lstat’.
|
|
-- Data Type: glob64_t
|
This data type holds a pointer to a word vector. More precisely,
|
it records both the address of the word vector and its size. The
|
GNU implementation contains some more fields which are non-standard
|
extensions.
|
|
‘gl_pathc’
|
The number of elements in the vector, excluding the initial
|
null entries if the GLOB_DOOFFS flag is used (see gl_offs
|
below).
|
|
‘gl_pathv’
|
The address of the vector. This field has type ‘char **’.
|
|
‘gl_offs’
|
The offset of the first real element of the vector, from its
|
nominal address in the ‘gl_pathv’ field. Unlike the other
|
fields, this is always an input to ‘glob’, rather than an
|
output from it.
|
|
If you use a nonzero offset, then that many elements at the
|
beginning of the vector are left empty. (The ‘glob’ function
|
fills them with null pointers.)
|
|
The ‘gl_offs’ field is meaningful only if you use the
|
‘GLOB_DOOFFS’ flag. Otherwise, the offset is always zero
|
regardless of what is in this field, and the first real
|
element comes at the beginning of the vector.
|
|
‘gl_closedir’
|
The address of an alternative implementation of the ‘closedir’
|
function. It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in
|
the flag parameter. The type of this field is
|
‘void (*) (void *)’.
|
|
This is a GNU extension.
|
|
‘gl_readdir’
|
The address of an alternative implementation of the
|
‘readdir64’ function used to read the contents of a directory.
|
It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in the flag
|
parameter. The type of this field is
|
‘struct dirent64 *(*) (void *)’.
|
|
This is a GNU extension.
|
|
‘gl_opendir’
|
The address of an alternative implementation of the ‘opendir’
|
function. It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in
|
the flag parameter. The type of this field is
|
‘void *(*) (const char *)’.
|
|
This is a GNU extension.
|
|
‘gl_stat’
|
The address of an alternative implementation of the ‘stat64’
|
function to get information about an object in the filesystem.
|
It is used if the ‘GLOB_ALTDIRFUNC’ bit is set in the flag
|
parameter. The type of this field is
|
‘int (*) (const char *, struct stat64 *)’.
|
|
This is a GNU extension.
|
|
‘gl_lstat’
|
The address of an alternative implementation of the ‘lstat64’
|
function to get information about an object in the
|
filesystems, not following symbolic links. It is used if the
|
‘GLOB_ALTDIRFUNC’ bit is set in the flag parameter. The type
|
of this field is ‘int (*) (const char *, struct stat64 *)’.
|
|
This is a GNU extension.
|
|
‘gl_flags’
|
The flags used when ‘glob’ was called. In addition,
|
‘GLOB_MAGCHAR’ might be set. See *note Flags for Globbing::
|
for more details.
|
|
This is a GNU extension.
|
|
-- Function: int glob (const char *PATTERN, int FLAGS, int (*ERRFUNC)
|
(const char *FILENAME, int ERROR-CODE), glob_t *VECTOR-PTR)
|
Preliminary: | MT-Unsafe race:utent env sig:ALRM timer locale |
|
AS-Unsafe dlopen plugin corrupt heap lock | AC-Unsafe corrupt lock
|
fd mem | *Note POSIX Safety Concepts::.
|
|
The function ‘glob’ does globbing using the pattern PATTERN in the
|
current directory. It puts the result in a newly allocated vector,
|
and stores the size and address of this vector into ‘*VECTOR-PTR’.
|
The argument FLAGS is a combination of bit flags; see *note Flags
|
for Globbing::, for details of the flags.
|
|
The result of globbing is a sequence of file names. The function
|
‘glob’ allocates a string for each resulting word, then allocates a
|
vector of type ‘char **’ to store the addresses of these strings.
|
The last element of the vector is a null pointer. This vector is
|
called the "word vector".
|
|
To return this vector, ‘glob’ stores both its address and its
|
length (number of elements, not counting the terminating null
|
pointer) into ‘*VECTOR-PTR’.
|
|
Normally, ‘glob’ sorts the file names alphabetically before
|
returning them. You can turn this off with the flag ‘GLOB_NOSORT’
|
if you want to get the information as fast as possible. Usually
|
it’s a good idea to let ‘glob’ sort them—if you process the files
|
in alphabetical order, the users will have a feel for the rate of
|
progress that your application is making.
|
|
If ‘glob’ succeeds, it returns 0. Otherwise, it returns one of
|
these error codes:
|
|
‘GLOB_ABORTED’
|
There was an error opening a directory, and you used the flag
|
‘GLOB_ERR’ or your specified ERRFUNC returned a nonzero value.
|
*Note Flags for Globbing::, for an explanation of the
|
‘GLOB_ERR’ flag and ERRFUNC.
|
|
‘GLOB_NOMATCH’
|
The pattern didn’t match any existing files. If you use the
|
‘GLOB_NOCHECK’ flag, then you never get this error code,
|
because that flag tells ‘glob’ to _pretend_ that the pattern
|
matched at least one file.
|
|
‘GLOB_NOSPACE’
|
It was impossible to allocate memory to hold the result.
|
|
In the event of an error, ‘glob’ stores information in
|
‘*VECTOR-PTR’ about all the matches it has found so far.
|
|
It is important to notice that the ‘glob’ function will not fail if
|
it encounters directories or files which cannot be handled without
|
the LFS interfaces. The implementation of ‘glob’ is supposed to
|
use these functions internally. This at least is the assumption
|
made by the Unix standard. The GNU extension of allowing the user
|
to provide their own directory handling and ‘stat’ functions
|
complicates things a bit. If these callback functions are used and
|
a large file or directory is encountered ‘glob’ _can_ fail.
|
|
-- Function: int glob64 (const char *PATTERN, int FLAGS, int (*ERRFUNC)
|
(const char *FILENAME, int ERROR-CODE), glob64_t *VECTOR-PTR)
|
Preliminary: | MT-Unsafe race:utent env sig:ALRM timer locale |
|
AS-Unsafe dlopen corrupt heap lock | AC-Unsafe corrupt lock fd mem
|
| *Note POSIX Safety Concepts::.
|
|
The ‘glob64’ function was added as part of the Large File Summit
|
extensions but is not part of the original LFS proposal. The
|
reason for this is simple: it is not necessary. The necessity for
|
a ‘glob64’ function is added by the extensions of the GNU ‘glob’
|
implementation which allows the user to provide their own directory
|
handling and ‘stat’ functions. The ‘readdir’ and ‘stat’ functions
|
do depend on the choice of ‘_FILE_OFFSET_BITS’ since the definition
|
of the types ‘struct dirent’ and ‘struct stat’ will change
|
depending on the choice.
|
|
Besides this difference, ‘glob64’ works just like ‘glob’ in all
|
aspects.
|
|
This function is a GNU extension.
|
|
|
File: libc.info, Node: Flags for Globbing, Next: More Flags for Globbing, Prev: Calling Glob, Up: Globbing
|
|
10.2.2 Flags for Globbing
|
-------------------------
|
|
This section describes the standard flags that you can specify in the
|
FLAGS argument to ‘glob’. Choose the flags you want, and combine them
|
with the C bitwise OR operator ‘|’.
|
|
Note that there are *note More Flags for Globbing:: available as GNU
|
extensions.
|
|
‘GLOB_APPEND’
|
Append the words from this expansion to the vector of words
|
produced by previous calls to ‘glob’. This way you can effectively
|
expand several words as if they were concatenated with spaces
|
between them.
|
|
In order for appending to work, you must not modify the contents of
|
the word vector structure between calls to ‘glob’. And, if you set
|
‘GLOB_DOOFFS’ in the first call to ‘glob’, you must also set it
|
when you append to the results.
|
|
Note that the pointer stored in ‘gl_pathv’ may no longer be valid
|
after you call ‘glob’ the second time, because ‘glob’ might have
|
relocated the vector. So always fetch ‘gl_pathv’ from the ‘glob_t’
|
structure after each ‘glob’ call; *never* save the pointer across
|
calls.
|
|
‘GLOB_DOOFFS’
|
Leave blank slots at the beginning of the vector of words. The
|
‘gl_offs’ field says how many slots to leave. The blank slots
|
contain null pointers.
|
|
‘GLOB_ERR’
|
Give up right away and report an error if there is any difficulty
|
reading the directories that must be read in order to expand
|
PATTERN fully. Such difficulties might include a directory in
|
which you don’t have the requisite access. Normally, ‘glob’ tries
|
its best to keep on going despite any errors, reading whatever
|
directories it can.
|
|
You can exercise even more control than this by specifying an
|
error-handler function ERRFUNC when you call ‘glob’. If ERRFUNC is
|
not a null pointer, then ‘glob’ doesn’t give up right away when it
|
can’t read a directory; instead, it calls ERRFUNC with two
|
arguments, like this:
|
|
(*ERRFUNC) (FILENAME, ERROR-CODE)
|
|
The argument FILENAME is the name of the directory that ‘glob’
|
couldn’t open or couldn’t read, and ERROR-CODE is the ‘errno’ value
|
that was reported to ‘glob’.
|
|
If the error handler function returns nonzero, then ‘glob’ gives up
|
right away. Otherwise, it continues.
|
|
‘GLOB_MARK’
|
If the pattern matches the name of a directory, append ‘/’ to the
|
directory’s name when returning it.
|
|
‘GLOB_NOCHECK’
|
If the pattern doesn’t match any file names, return the pattern
|
itself as if it were a file name that had been matched. (Normally,
|
when the pattern doesn’t match anything, ‘glob’ returns that there
|
were no matches.)
|
|
‘GLOB_NOESCAPE’
|
Don’t treat the ‘\’ character specially in patterns. Normally, ‘\’
|
quotes the following character, turning off its special meaning (if
|
any) so that it matches only itself. When quoting is enabled, the
|
pattern ‘\?’ matches only the string ‘?’, because the question mark
|
in the pattern acts like an ordinary character.
|
|
If you use ‘GLOB_NOESCAPE’, then ‘\’ is an ordinary character.
|
|
‘glob’ does its work by calling the function ‘fnmatch’ repeatedly.
|
It handles the flag ‘GLOB_NOESCAPE’ by turning on the
|
‘FNM_NOESCAPE’ flag in calls to ‘fnmatch’.
|
|
‘GLOB_NOSORT’
|
Don’t sort the file names; return them in no particular order. (In
|
practice, the order will depend on the order of the entries in the
|
directory.) The only reason _not_ to sort is to save time.
|
|
|
File: libc.info, Node: More Flags for Globbing, Prev: Flags for Globbing, Up: Globbing
|
|
10.2.3 More Flags for Globbing
|
------------------------------
|
|
Beside the flags described in the last section, the GNU implementation
|
of ‘glob’ allows a few more flags which are also defined in the ‘glob.h’
|
file. Some of the extensions implement functionality which is available
|
in modern shell implementations.
|
|
‘GLOB_PERIOD’
|
The ‘.’ character (period) is treated special. It cannot be
|
matched by wildcards. *Note Wildcard Matching::, ‘FNM_PERIOD’.
|
|
‘GLOB_MAGCHAR’
|
The ‘GLOB_MAGCHAR’ value is not to be given to ‘glob’ in the FLAGS
|
parameter. Instead, ‘glob’ sets this bit in the GL_FLAGS element
|
of the GLOB_T structure provided as the result if the pattern used
|
for matching contains any wildcard character.
|
|
‘GLOB_ALTDIRFUNC’
|
Instead of using the normal functions for accessing the filesystem
|
the ‘glob’ implementation uses the user-supplied functions
|
specified in the structure pointed to by PGLOB parameter. For more
|
information about the functions refer to the sections about
|
directory handling see *note Accessing Directories::, and *note
|
Reading Attributes::.
|
|
‘GLOB_BRACE’
|
If this flag is given, the handling of braces in the pattern is
|
changed. It is now required that braces appear correctly grouped.
|
I.e., for each opening brace there must be a closing one. Braces
|
can be used recursively. So it is possible to define one brace
|
expression in another one. It is important to note that the range
|
of each brace expression is completely contained in the outer brace
|
expression (if there is one).
|
|
The string between the matching braces is separated into single
|
expressions by splitting at ‘,’ (comma) characters. The commas
|
themselves are discarded. Please note what we said above about
|
recursive brace expressions. The commas used to separate the
|
subexpressions must be at the same level. Commas in brace
|
subexpressions are not matched. They are used during expansion of
|
the brace expression of the deeper level. The example below shows
|
this
|
|
glob ("{foo/{,bar,biz},baz}", GLOB_BRACE, NULL, &result)
|
|
is equivalent to the sequence
|
|
glob ("foo/", GLOB_BRACE, NULL, &result)
|
glob ("foo/bar", GLOB_BRACE|GLOB_APPEND, NULL, &result)
|
glob ("foo/biz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
|
glob ("baz", GLOB_BRACE|GLOB_APPEND, NULL, &result)
|
|
if we leave aside error handling.
|
|
‘GLOB_NOMAGIC’
|
If the pattern contains no wildcard constructs (it is a literal
|
file name), return it as the sole “matching” word, even if no file
|
exists by that name.
|
|
‘GLOB_TILDE’
|
If this flag is used the character ‘~’ (tilde) is handled specially
|
if it appears at the beginning of the pattern. Instead of being
|
taken verbatim it is used to represent the home directory of a
|
known user.
|
|
If ‘~’ is the only character in pattern or it is followed by a ‘/’
|
(slash), the home directory of the process owner is substituted.
|
Using ‘getlogin’ and ‘getpwnam’ the information is read from the
|
system databases. As an example take user ‘bart’ with his home
|
directory at ‘/home/bart’. For him a call like
|
|
glob ("~/bin/*", GLOB_TILDE, NULL, &result)
|
|
would return the contents of the directory ‘/home/bart/bin’.
|
Instead of referring to the own home directory it is also possible
|
to name the home directory of other users. To do so one has to
|
append the user name after the tilde character. So the contents of
|
user ‘homer’’s ‘bin’ directory can be retrieved by
|
|
glob ("~homer/bin/*", GLOB_TILDE, NULL, &result)
|
|
If the user name is not valid or the home directory cannot be
|
determined for some reason the pattern is left untouched and itself
|
used as the result. I.e., if in the last example ‘home’ is not
|
available the tilde expansion yields to ‘"~homer/bin/*"’ and ‘glob’
|
is not looking for a directory named ‘~homer’.
|
|
This functionality is equivalent to what is available in C-shells
|
if the ‘nonomatch’ flag is set.
|
|
‘GLOB_TILDE_CHECK’
|
If this flag is used ‘glob’ behaves as if ‘GLOB_TILDE’ is given.
|
The only difference is that if the user name is not available or
|
the home directory cannot be determined for other reasons this
|
leads to an error. ‘glob’ will return ‘GLOB_NOMATCH’ instead of
|
using the pattern itself as the name.
|
|
This functionality is equivalent to what is available in C-shells
|
if the ‘nonomatch’ flag is not set.
|
|
‘GLOB_ONLYDIR’
|
If this flag is used the globbing function takes this as a *hint*
|
that the caller is only interested in directories matching the
|
pattern. If the information about the type of the file is easily
|
available non-directories will be rejected but no extra work will
|
be done to determine the information for each file. I.e., the
|
caller must still be able to filter directories out.
|
|
This functionality is only available with the GNU ‘glob’
|
implementation. It is mainly used internally to increase the
|
performance but might be useful for a user as well and therefore is
|
documented here.
|
|
Calling ‘glob’ will in most cases allocate resources which are used
|
to represent the result of the function call. If the same object of
|
type ‘glob_t’ is used in multiple call to ‘glob’ the resources are freed
|
or reused so that no leaks appear. But this does not include the time
|
when all ‘glob’ calls are done.
|
|
-- Function: void globfree (glob_t *PGLOB)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt heap | AC-Unsafe corrupt
|
mem | *Note POSIX Safety Concepts::.
|
|
The ‘globfree’ function frees all resources allocated by previous
|
calls to ‘glob’ associated with the object pointed to by PGLOB.
|
This function should be called whenever the currently used ‘glob_t’
|
typed object isn’t used anymore.
|
|
-- Function: void globfree64 (glob64_t *PGLOB)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt lock | AC-Unsafe corrupt
|
lock fd mem | *Note POSIX Safety Concepts::.
|
|
This function is equivalent to ‘globfree’ but it frees records of
|
type ‘glob64_t’ which were allocated by ‘glob64’.
|
|
|
File: libc.info, Node: Regular Expressions, Next: Word Expansion, Prev: Globbing, Up: Pattern Matching
|
|
10.3 Regular Expression Matching
|
================================
|
|
The GNU C Library supports two interfaces for matching regular
|
expressions. One is the standard POSIX.2 interface, and the other is
|
what the GNU C Library has had for many years.
|
|
Both interfaces are declared in the header file ‘regex.h’. If you
|
define ‘_POSIX_C_SOURCE’, then only the POSIX.2 functions, structures,
|
and constants are declared.
|
|
* Menu:
|
|
* POSIX Regexp Compilation:: Using ‘regcomp’ to prepare to match.
|
* Flags for POSIX Regexps:: Syntax variations for ‘regcomp’.
|
* Matching POSIX Regexps:: Using ‘regexec’ to match the compiled
|
pattern that you get from ‘regcomp’.
|
* Regexp Subexpressions:: Finding which parts of the string were matched.
|
* Subexpression Complications:: Find points of which parts were matched.
|
* Regexp Cleanup:: Freeing storage; reporting errors.
|
|
|
File: libc.info, Node: POSIX Regexp Compilation, Next: Flags for POSIX Regexps, Up: Regular Expressions
|
|
10.3.1 POSIX Regular Expression Compilation
|
-------------------------------------------
|
|
Before you can actually match a regular expression, you must "compile"
|
it. This is not true compilation—it produces a special data structure,
|
not machine instructions. But it is like ordinary compilation in that
|
its purpose is to enable you to “execute” the pattern fast. (*Note
|
Matching POSIX Regexps::, for how to use the compiled regular expression
|
for matching.)
|
|
There is a special data type for compiled regular expressions:
|
|
-- Data Type: regex_t
|
This type of object holds a compiled regular expression. It is
|
actually a structure. It has just one field that your programs
|
should look at:
|
|
‘re_nsub’
|
This field holds the number of parenthetical subexpressions in
|
the regular expression that was compiled.
|
|
There are several other fields, but we don’t describe them here,
|
because only the functions in the library should use them.
|
|
After you create a ‘regex_t’ object, you can compile a regular
|
expression into it by calling ‘regcomp’.
|
|
-- Function: int regcomp (regex_t *restrict COMPILED, const char
|
*restrict PATTERN, int CFLAGS)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap lock dlopen
|
| AC-Unsafe corrupt lock mem fd | *Note POSIX Safety Concepts::.
|
|
The function ‘regcomp’ “compiles” a regular expression into a data
|
structure that you can use with ‘regexec’ to match against a
|
string. The compiled regular expression format is designed for
|
efficient matching. ‘regcomp’ stores it into ‘*COMPILED’.
|
|
It’s up to you to allocate an object of type ‘regex_t’ and pass its
|
address to ‘regcomp’.
|
|
The argument CFLAGS lets you specify various options that control
|
the syntax and semantics of regular expressions. *Note Flags for
|
POSIX Regexps::.
|
|
If you use the flag ‘REG_NOSUB’, then ‘regcomp’ omits from the
|
compiled regular expression the information necessary to record how
|
subexpressions actually match. In this case, you might as well
|
pass ‘0’ for the MATCHPTR and NMATCH arguments when you call
|
‘regexec’.
|
|
If you don’t use ‘REG_NOSUB’, then the compiled regular expression
|
does have the capacity to record how subexpressions match. Also,
|
‘regcomp’ tells you how many subexpressions PATTERN has, by storing
|
the number in ‘COMPILED->re_nsub’. You can use that value to
|
decide how long an array to allocate to hold information about
|
subexpression matches.
|
|
‘regcomp’ returns ‘0’ if it succeeds in compiling the regular
|
expression; otherwise, it returns a nonzero error code (see the
|
table below). You can use ‘regerror’ to produce an error message
|
string describing the reason for a nonzero value; see *note Regexp
|
Cleanup::.
|
|
Here are the possible nonzero values that ‘regcomp’ can return:
|
|
‘REG_BADBR’
|
There was an invalid ‘\{…\}’ construct in the regular expression.
|
A valid ‘\{…\}’ construct must contain either a single number, or
|
two numbers in increasing order separated by a comma.
|
|
‘REG_BADPAT’
|
There was a syntax error in the regular expression.
|
|
‘REG_BADRPT’
|
A repetition operator such as ‘?’ or ‘*’ appeared in a bad position
|
(with no preceding subexpression to act on).
|
|
‘REG_ECOLLATE’
|
The regular expression referred to an invalid collating element
|
(one not defined in the current locale for string collation).
|
*Note Locale Categories::.
|
|
‘REG_ECTYPE’
|
The regular expression referred to an invalid character class name.
|
|
‘REG_EESCAPE’
|
The regular expression ended with ‘\’.
|
|
‘REG_ESUBREG’
|
There was an invalid number in the ‘\DIGIT’ construct.
|
|
‘REG_EBRACK’
|
There were unbalanced square brackets in the regular expression.
|
|
‘REG_EPAREN’
|
An extended regular expression had unbalanced parentheses, or a
|
basic regular expression had unbalanced ‘\(’ and ‘\)’.
|
|
‘REG_EBRACE’
|
The regular expression had unbalanced ‘\{’ and ‘\}’.
|
|
‘REG_ERANGE’
|
One of the endpoints in a range expression was invalid.
|
|
‘REG_ESPACE’
|
‘regcomp’ ran out of memory.
|
|
|
File: libc.info, Node: Flags for POSIX Regexps, Next: Matching POSIX Regexps, Prev: POSIX Regexp Compilation, Up: Regular Expressions
|
|
10.3.2 Flags for POSIX Regular Expressions
|
------------------------------------------
|
|
These are the bit flags that you can use in the CFLAGS operand when
|
compiling a regular expression with ‘regcomp’.
|
|
‘REG_EXTENDED’
|
Treat the pattern as an extended regular expression, rather than as
|
a basic regular expression.
|
|
‘REG_ICASE’
|
Ignore case when matching letters.
|
|
‘REG_NOSUB’
|
Don’t bother storing the contents of the MATCHPTR array.
|
|
‘REG_NEWLINE’
|
Treat a newline in STRING as dividing STRING into multiple lines,
|
so that ‘$’ can match before the newline and ‘^’ can match after.
|
Also, don’t permit ‘.’ to match a newline, and don’t permit ‘[^…]’
|
to match a newline.
|
|
Otherwise, newline acts like any other ordinary character.
|
|
|
File: libc.info, Node: Matching POSIX Regexps, Next: Regexp Subexpressions, Prev: Flags for POSIX Regexps, Up: Regular Expressions
|
|
10.3.3 Matching a Compiled POSIX Regular Expression
|
---------------------------------------------------
|
|
Once you have compiled a regular expression, as described in *note POSIX
|
Regexp Compilation::, you can match it against strings using ‘regexec’.
|
A match anywhere inside the string counts as success, unless the regular
|
expression contains anchor characters (‘^’ or ‘$’).
|
|
-- Function: int regexec (const regex_t *restrict COMPILED, const char
|
*restrict STRING, size_t NMATCH, regmatch_t
|
MATCHPTR[restrict], int EFLAGS)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap lock dlopen
|
| AC-Unsafe corrupt lock mem fd | *Note POSIX Safety Concepts::.
|
|
This function tries to match the compiled regular expression
|
‘*COMPILED’ against STRING.
|
|
‘regexec’ returns ‘0’ if the regular expression matches; otherwise,
|
it returns a nonzero value. See the table below for what nonzero
|
values mean. You can use ‘regerror’ to produce an error message
|
string describing the reason for a nonzero value; see *note Regexp
|
Cleanup::.
|
|
The argument EFLAGS is a word of bit flags that enable various
|
options.
|
|
If you want to get information about what part of STRING actually
|
matched the regular expression or its subexpressions, use the
|
arguments MATCHPTR and NMATCH. Otherwise, pass ‘0’ for NMATCH, and
|
‘NULL’ for MATCHPTR. *Note Regexp Subexpressions::.
|
|
You must match the regular expression with the same set of current
|
locales that were in effect when you compiled the regular expression.
|
|
The function ‘regexec’ accepts the following flags in the EFLAGS
|
argument:
|
|
‘REG_NOTBOL’
|
Do not regard the beginning of the specified string as the
|
beginning of a line; more generally, don’t make any assumptions
|
about what text might precede it.
|
|
‘REG_NOTEOL’
|
Do not regard the end of the specified string as the end of a line;
|
more generally, don’t make any assumptions about what text might
|
follow it.
|
|
Here are the possible nonzero values that ‘regexec’ can return:
|
|
‘REG_NOMATCH’
|
The pattern didn’t match the string. This isn’t really an error.
|
|
‘REG_ESPACE’
|
‘regexec’ ran out of memory.
|
|
|
File: libc.info, Node: Regexp Subexpressions, Next: Subexpression Complications, Prev: Matching POSIX Regexps, Up: Regular Expressions
|
|
10.3.4 Match Results with Subexpressions
|
----------------------------------------
|
|
When ‘regexec’ matches parenthetical subexpressions of PATTERN, it
|
records which parts of STRING they match. It returns that information
|
by storing the offsets into an array whose elements are structures of
|
type ‘regmatch_t’. The first element of the array (index ‘0’) records
|
the part of the string that matched the entire regular expression. Each
|
other element of the array records the beginning and end of the part
|
that matched a single parenthetical subexpression.
|
|
-- Data Type: regmatch_t
|
This is the data type of the MATCHPTR array that you pass to
|
‘regexec’. It contains two structure fields, as follows:
|
|
‘rm_so’
|
The offset in STRING of the beginning of a substring. Add
|
this value to STRING to get the address of that part.
|
|
‘rm_eo’
|
The offset in STRING of the end of the substring.
|
|
-- Data Type: regoff_t
|
‘regoff_t’ is an alias for another signed integer type. The fields
|
of ‘regmatch_t’ have type ‘regoff_t’.
|
|
The ‘regmatch_t’ elements correspond to subexpressions positionally;
|
the first element (index ‘1’) records where the first subexpression
|
matched, the second element records the second subexpression, and so on.
|
The order of the subexpressions is the order in which they begin.
|
|
When you call ‘regexec’, you specify how long the MATCHPTR array is,
|
with the NMATCH argument. This tells ‘regexec’ how many elements to
|
store. If the actual regular expression has more than NMATCH
|
subexpressions, then you won’t get offset information about the rest of
|
them. But this doesn’t alter whether the pattern matches a particular
|
string or not.
|
|
If you don’t want ‘regexec’ to return any information about where the
|
subexpressions matched, you can either supply ‘0’ for NMATCH, or use the
|
flag ‘REG_NOSUB’ when you compile the pattern with ‘regcomp’.
|
|
|
File: libc.info, Node: Subexpression Complications, Next: Regexp Cleanup, Prev: Regexp Subexpressions, Up: Regular Expressions
|
|
10.3.5 Complications in Subexpression Matching
|
----------------------------------------------
|
|
Sometimes a subexpression matches a substring of no characters. This
|
happens when ‘f\(o*\)’ matches the string ‘fum’. (It really matches
|
just the ‘f’.) In this case, both of the offsets identify the point in
|
the string where the null substring was found. In this example, the
|
offsets are both ‘1’.
|
|
Sometimes the entire regular expression can match without using some
|
of its subexpressions at all—for example, when ‘ba\(na\)*’ matches the
|
string ‘ba’, the parenthetical subexpression is not used. When this
|
happens, ‘regexec’ stores ‘-1’ in both fields of the element for that
|
subexpression.
|
|
Sometimes matching the entire regular expression can match a
|
particular subexpression more than once—for example, when ‘ba\(na\)*’
|
matches the string ‘bananana’, the parenthetical subexpression matches
|
three times. When this happens, ‘regexec’ usually stores the offsets of
|
the last part of the string that matched the subexpression. In the case
|
of ‘bananana’, these offsets are ‘6’ and ‘8’.
|
|
But the last match is not always the one that is chosen. It’s more
|
accurate to say that the last _opportunity_ to match is the one that
|
takes precedence. What this means is that when one subexpression
|
appears within another, then the results reported for the inner
|
subexpression reflect whatever happened on the last match of the outer
|
subexpression. For an example, consider ‘\(ba\(na\)*s \)*’ matching the
|
string ‘bananas bas ’. The last time the inner expression actually
|
matches is near the end of the first word. But it is _considered_ again
|
in the second word, and fails to match there. ‘regexec’ reports nonuse
|
of the “na” subexpression.
|
|
Another place where this rule applies is when the regular expression
|
\(ba\(na\)*s \|nefer\(ti\)* \)*
|
matches ‘bananas nefertiti’. The “na” subexpression does match in the
|
first word, but it doesn’t match in the second word because the other
|
alternative is used there. Once again, the second repetition of the
|
outer subexpression overrides the first, and within that second
|
repetition, the “na” subexpression is not used. So ‘regexec’ reports
|
nonuse of the “na” subexpression.
|
|
|
File: libc.info, Node: Regexp Cleanup, Prev: Subexpression Complications, Up: Regular Expressions
|
|
10.3.6 POSIX Regexp Matching Cleanup
|
------------------------------------
|
|
When you are finished using a compiled regular expression, you can free
|
the storage it uses by calling ‘regfree’.
|
|
-- Function: void regfree (regex_t *COMPILED)
|
Preliminary: | MT-Safe | AS-Unsafe heap | AC-Unsafe mem | *Note
|
POSIX Safety Concepts::.
|
|
Calling ‘regfree’ frees all the storage that ‘*COMPILED’ points to.
|
This includes various internal fields of the ‘regex_t’ structure
|
that aren’t documented in this manual.
|
|
‘regfree’ does not free the object ‘*COMPILED’ itself.
|
|
You should always free the space in a ‘regex_t’ structure with
|
‘regfree’ before using the structure to compile another regular
|
expression.
|
|
When ‘regcomp’ or ‘regexec’ reports an error, you can use the
|
function ‘regerror’ to turn it into an error message string.
|
|
-- Function: size_t regerror (int ERRCODE, const regex_t *restrict
|
COMPILED, char *restrict BUFFER, size_t LENGTH)
|
Preliminary: | MT-Safe env | AS-Unsafe corrupt heap lock dlopen |
|
AC-Unsafe corrupt lock fd mem | *Note POSIX Safety Concepts::.
|
|
This function produces an error message string for the error code
|
ERRCODE, and stores the string in LENGTH bytes of memory starting
|
at BUFFER. For the COMPILED argument, supply the same compiled
|
regular expression structure that ‘regcomp’ or ‘regexec’ was
|
working with when it got the error. Alternatively, you can supply
|
‘NULL’ for COMPILED; you will still get a meaningful error message,
|
but it might not be as detailed.
|
|
If the error message can’t fit in LENGTH bytes (including a
|
terminating null character), then ‘regerror’ truncates it. The
|
string that ‘regerror’ stores is always null-terminated even if it
|
has been truncated.
|
|
The return value of ‘regerror’ is the minimum length needed to
|
store the entire error message. If this is less than LENGTH, then
|
the error message was not truncated, and you can use it.
|
Otherwise, you should call ‘regerror’ again with a larger buffer.
|
|
Here is a function which uses ‘regerror’, but always dynamically
|
allocates a buffer for the error message:
|
|
char *get_regerror (int errcode, regex_t *compiled)
|
{
|
size_t length = regerror (errcode, compiled, NULL, 0);
|
char *buffer = xmalloc (length);
|
(void) regerror (errcode, compiled, buffer, length);
|
return buffer;
|
}
|
|
|
File: libc.info, Node: Word Expansion, Prev: Regular Expressions, Up: Pattern Matching
|
|
10.4 Shell-Style Word Expansion
|
===============================
|
|
"Word expansion" means the process of splitting a string into "words"
|
and substituting for variables, commands, and wildcards just as the
|
shell does.
|
|
For example, when you write ‘ls -l foo.c’, this string is split into
|
three separate words—‘ls’, ‘-l’ and ‘foo.c’. This is the most basic
|
function of word expansion.
|
|
When you write ‘ls *.c’, this can become many words, because the word
|
‘*.c’ can be replaced with any number of file names. This is called
|
"wildcard expansion", and it is also a part of word expansion.
|
|
When you use ‘echo $PATH’ to print your path, you are taking
|
advantage of "variable substitution", which is also part of word
|
expansion.
|
|
Ordinary programs can perform word expansion just like the shell by
|
calling the library function ‘wordexp’.
|
|
* Menu:
|
|
* Expansion Stages:: What word expansion does to a string.
|
* Calling Wordexp:: How to call ‘wordexp’.
|
* Flags for Wordexp:: Options you can enable in ‘wordexp’.
|
* Wordexp Example:: A sample program that does word expansion.
|
* Tilde Expansion:: Details of how tilde expansion works.
|
* Variable Substitution:: Different types of variable substitution.
|
|
|
File: libc.info, Node: Expansion Stages, Next: Calling Wordexp, Up: Word Expansion
|
|
10.4.1 The Stages of Word Expansion
|
-----------------------------------
|
|
When word expansion is applied to a sequence of words, it performs the
|
following transformations in the order shown here:
|
|
1. "Tilde expansion": Replacement of ‘~foo’ with the name of the home
|
directory of ‘foo’.
|
|
2. Next, three different transformations are applied in the same step,
|
from left to right:
|
|
• "Variable substitution": Environment variables are substituted
|
for references such as ‘$foo’.
|
|
• "Command substitution": Constructs such as ‘`cat foo`’ and the
|
equivalent ‘$(cat foo)’ are replaced with the output from the
|
inner command.
|
|
• "Arithmetic expansion": Constructs such as ‘$(($x-1))’ are
|
replaced with the result of the arithmetic computation.
|
|
3. "Field splitting": subdivision of the text into "words".
|
|
4. "Wildcard expansion": The replacement of a construct such as ‘*.c’
|
with a list of ‘.c’ file names. Wildcard expansion applies to an
|
entire word at a time, and replaces that word with 0 or more file
|
names that are themselves words.
|
|
5. "Quote removal": The deletion of string-quotes, now that they have
|
done their job by inhibiting the above transformations when
|
appropriate.
|
|
For the details of these transformations, and how to write the
|
constructs that use them, see ‘The BASH Manual’ (to appear).
|
|
|
File: libc.info, Node: Calling Wordexp, Next: Flags for Wordexp, Prev: Expansion Stages, Up: Word Expansion
|
|
10.4.2 Calling ‘wordexp’
|
------------------------
|
|
All the functions, constants and data types for word expansion are
|
declared in the header file ‘wordexp.h’.
|
|
Word expansion produces a vector of words (strings). To return this
|
vector, ‘wordexp’ uses a special data type, ‘wordexp_t’, which is a
|
structure. You pass ‘wordexp’ the address of the structure, and it
|
fills in the structure’s fields to tell you about the results.
|
|
-- Data Type: wordexp_t
|
This data type holds a pointer to a word vector. More precisely,
|
it records both the address of the word vector and its size.
|
|
‘we_wordc’
|
The number of elements in the vector.
|
|
‘we_wordv’
|
The address of the vector. This field has type ‘char **’.
|
|
‘we_offs’
|
The offset of the first real element of the vector, from its
|
nominal address in the ‘we_wordv’ field. Unlike the other
|
fields, this is always an input to ‘wordexp’, rather than an
|
output from it.
|
|
If you use a nonzero offset, then that many elements at the
|
beginning of the vector are left empty. (The ‘wordexp’
|
function fills them with null pointers.)
|
|
The ‘we_offs’ field is meaningful only if you use the
|
‘WRDE_DOOFFS’ flag. Otherwise, the offset is always zero
|
regardless of what is in this field, and the first real
|
element comes at the beginning of the vector.
|
|
-- Function: int wordexp (const char *WORDS, wordexp_t
|
*WORD-VECTOR-PTR, int FLAGS)
|
Preliminary: | MT-Unsafe race:utent const:env env sig:ALRM timer
|
locale | AS-Unsafe dlopen plugin i18n heap corrupt lock | AC-Unsafe
|
corrupt lock fd mem | *Note POSIX Safety Concepts::.
|
|
Perform word expansion on the string WORDS, putting the result in a
|
newly allocated vector, and store the size and address of this
|
vector into ‘*WORD-VECTOR-PTR’. The argument FLAGS is a
|
combination of bit flags; see *note Flags for Wordexp::, for
|
details of the flags.
|
|
You shouldn’t use any of the characters ‘|&;<>’ in the string WORDS
|
unless they are quoted; likewise for newline. If you use these
|
characters unquoted, you will get the ‘WRDE_BADCHAR’ error code.
|
Don’t use parentheses or braces unless they are quoted or part of a
|
word expansion construct. If you use quotation characters ‘'"`’,
|
they should come in pairs that balance.
|
|
The results of word expansion are a sequence of words. The
|
function ‘wordexp’ allocates a string for each resulting word, then
|
allocates a vector of type ‘char **’ to store the addresses of
|
these strings. The last element of the vector is a null pointer.
|
This vector is called the "word vector".
|
|
To return this vector, ‘wordexp’ stores both its address and its
|
length (number of elements, not counting the terminating null
|
pointer) into ‘*WORD-VECTOR-PTR’.
|
|
If ‘wordexp’ succeeds, it returns 0. Otherwise, it returns one of
|
these error codes:
|
|
‘WRDE_BADCHAR’
|
The input string WORDS contains an unquoted invalid character
|
such as ‘|’.
|
|
‘WRDE_BADVAL’
|
The input string refers to an undefined shell variable, and
|
you used the flag ‘WRDE_UNDEF’ to forbid such references.
|
|
‘WRDE_CMDSUB’
|
The input string uses command substitution, and you used the
|
flag ‘WRDE_NOCMD’ to forbid command substitution.
|
|
‘WRDE_NOSPACE’
|
It was impossible to allocate memory to hold the result. In
|
this case, ‘wordexp’ can store part of the results—as much as
|
it could allocate room for.
|
|
‘WRDE_SYNTAX’
|
There was a syntax error in the input string. For example, an
|
unmatched quoting character is a syntax error. This error
|
code is also used to signal division by zero and overflow in
|
arithmetic expansion.
|
|
-- Function: void wordfree (wordexp_t *WORD-VECTOR-PTR)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt heap | AC-Unsafe corrupt
|
mem | *Note POSIX Safety Concepts::.
|
|
Free the storage used for the word-strings and vector that
|
‘*WORD-VECTOR-PTR’ points to. This does not free the structure
|
‘*WORD-VECTOR-PTR’ itself—only the other data it points to.
|
|
|
File: libc.info, Node: Flags for Wordexp, Next: Wordexp Example, Prev: Calling Wordexp, Up: Word Expansion
|
|
10.4.3 Flags for Word Expansion
|
-------------------------------
|
|
This section describes the flags that you can specify in the FLAGS
|
argument to ‘wordexp’. Choose the flags you want, and combine them with
|
the C operator ‘|’.
|
|
‘WRDE_APPEND’
|
Append the words from this expansion to the vector of words
|
produced by previous calls to ‘wordexp’. This way you can
|
effectively expand several words as if they were concatenated with
|
spaces between them.
|
|
In order for appending to work, you must not modify the contents of
|
the word vector structure between calls to ‘wordexp’. And, if you
|
set ‘WRDE_DOOFFS’ in the first call to ‘wordexp’, you must also set
|
it when you append to the results.
|
|
‘WRDE_DOOFFS’
|
Leave blank slots at the beginning of the vector of words. The
|
‘we_offs’ field says how many slots to leave. The blank slots
|
contain null pointers.
|
|
‘WRDE_NOCMD’
|
Don’t do command substitution; if the input requests command
|
substitution, report an error.
|
|
‘WRDE_REUSE’
|
Reuse a word vector made by a previous call to ‘wordexp’. Instead
|
of allocating a new vector of words, this call to ‘wordexp’ will
|
use the vector that already exists (making it larger if necessary).
|
|
Note that the vector may move, so it is not safe to save an old
|
pointer and use it again after calling ‘wordexp’. You must fetch
|
‘we_pathv’ anew after each call.
|
|
‘WRDE_SHOWERR’
|
Do show any error messages printed by commands run by command
|
substitution. More precisely, allow these commands to inherit the
|
standard error output stream of the current process. By default,
|
‘wordexp’ gives these commands a standard error stream that
|
discards all output.
|
|
‘WRDE_UNDEF’
|
If the input refers to a shell variable that is not defined, report
|
an error.
|
|
|
File: libc.info, Node: Wordexp Example, Next: Tilde Expansion, Prev: Flags for Wordexp, Up: Word Expansion
|
|
10.4.4 ‘wordexp’ Example
|
------------------------
|
|
Here is an example of using ‘wordexp’ to expand several strings and use
|
the results to run a shell command. It also shows the use of
|
‘WRDE_APPEND’ to concatenate the expansions and of ‘wordfree’ to free
|
the space allocated by ‘wordexp’.
|
|
int
|
expand_and_execute (const char *program, const char **options)
|
{
|
wordexp_t result;
|
pid_t pid
|
int status, i;
|
|
/* Expand the string for the program to run. */
|
switch (wordexp (program, &result, 0))
|
{
|
case 0: /* Successful. */
|
break;
|
case WRDE_NOSPACE:
|
/* If the error was ‘WRDE_NOSPACE’,
|
then perhaps part of the result was allocated. */
|
wordfree (&result);
|
default: /* Some other error. */
|
return -1;
|
}
|
|
/* Expand the strings specified for the arguments. */
|
for (i = 0; options[i] != NULL; i++)
|
{
|
if (wordexp (options[i], &result, WRDE_APPEND))
|
{
|
wordfree (&result);
|
return -1;
|
}
|
}
|
|
pid = fork ();
|
if (pid == 0)
|
{
|
/* This is the child process. Execute the command. */
|
execv (result.we_wordv[0], result.we_wordv);
|
exit (EXIT_FAILURE);
|
}
|
else if (pid < 0)
|
/* The fork failed. Report failure. */
|
status = -1;
|
else
|
/* This is the parent process. Wait for the child to complete. */
|
if (waitpid (pid, &status, 0) != pid)
|
status = -1;
|
|
wordfree (&result);
|
return status;
|
}
|
|
|
File: libc.info, Node: Tilde Expansion, Next: Variable Substitution, Prev: Wordexp Example, Up: Word Expansion
|
|
10.4.5 Details of Tilde Expansion
|
---------------------------------
|
|
It’s a standard part of shell syntax that you can use ‘~’ at the
|
beginning of a file name to stand for your own home directory. You can
|
use ‘~USER’ to stand for USER’s home directory.
|
|
"Tilde expansion" is the process of converting these abbreviations to
|
the directory names that they stand for.
|
|
Tilde expansion applies to the ‘~’ plus all following characters up
|
to whitespace or a slash. It takes place only at the beginning of a
|
word, and only if none of the characters to be transformed is quoted in
|
any way.
|
|
Plain ‘~’ uses the value of the environment variable ‘HOME’ as the
|
proper home directory name. ‘~’ followed by a user name uses
|
‘getpwname’ to look up that user in the user database, and uses whatever
|
directory is recorded there. Thus, ‘~’ followed by your own name can
|
give different results from plain ‘~’, if the value of ‘HOME’ is not
|
really your home directory.
|
|
|
File: libc.info, Node: Variable Substitution, Prev: Tilde Expansion, Up: Word Expansion
|
|
10.4.6 Details of Variable Substitution
|
---------------------------------------
|
|
Part of ordinary shell syntax is the use of ‘$VARIABLE’ to substitute
|
the value of a shell variable into a command. This is called "variable
|
substitution", and it is one part of doing word expansion.
|
|
There are two basic ways you can write a variable reference for
|
substitution:
|
|
‘${VARIABLE}’
|
If you write braces around the variable name, then it is completely
|
unambiguous where the variable name ends. You can concatenate
|
additional letters onto the end of the variable value by writing
|
them immediately after the close brace. For example, ‘${foo}s’
|
expands into ‘tractors’.
|
|
‘$VARIABLE’
|
If you do not put braces around the variable name, then the
|
variable name consists of all the alphanumeric characters and
|
underscores that follow the ‘$’. The next punctuation character
|
ends the variable name. Thus, ‘$foo-bar’ refers to the variable
|
‘foo’ and expands into ‘tractor-bar’.
|
|
When you use braces, you can also use various constructs to modify
|
the value that is substituted, or test it in various ways.
|
|
‘${VARIABLE:-DEFAULT}’
|
Substitute the value of VARIABLE, but if that is empty or
|
undefined, use DEFAULT instead.
|
|
‘${VARIABLE:=DEFAULT}’
|
Substitute the value of VARIABLE, but if that is empty or
|
undefined, use DEFAULT instead and set the variable to DEFAULT.
|
|
‘${VARIABLE:?MESSAGE}’
|
If VARIABLE is defined and not empty, substitute its value.
|
|
Otherwise, print MESSAGE as an error message on the standard error
|
stream, and consider word expansion a failure.
|
|
‘${VARIABLE:+REPLACEMENT}’
|
Substitute REPLACEMENT, but only if VARIABLE is defined and
|
nonempty. Otherwise, substitute nothing for this construct.
|
|
‘${#VARIABLE}’
|
Substitute a numeral which expresses in base ten the number of
|
characters in the value of VARIABLE. ‘${#foo}’ stands for ‘7’,
|
because ‘tractor’ is seven characters.
|
|
These variants of variable substitution let you remove part of the
|
variable’s value before substituting it. The PREFIX and SUFFIX are not
|
mere strings; they are wildcard patterns, just like the patterns that
|
you use to match multiple file names. But in this context, they match
|
against parts of the variable value rather than against file names.
|
|
‘${VARIABLE%%SUFFIX}’
|
Substitute the value of VARIABLE, but first discard from that
|
variable any portion at the end that matches the pattern SUFFIX.
|
|
If there is more than one alternative for how to match against
|
SUFFIX, this construct uses the longest possible match.
|
|
Thus, ‘${foo%%r*}’ substitutes ‘t’, because the largest match for
|
‘r*’ at the end of ‘tractor’ is ‘ractor’.
|
|
‘${VARIABLE%SUFFIX}’
|
Substitute the value of VARIABLE, but first discard from that
|
variable any portion at the end that matches the pattern SUFFIX.
|
|
If there is more than one alternative for how to match against
|
SUFFIX, this construct uses the shortest possible alternative.
|
|
Thus, ‘${foo%r*}’ substitutes ‘tracto’, because the shortest match
|
for ‘r*’ at the end of ‘tractor’ is just ‘r’.
|
|
‘${VARIABLE##PREFIX}’
|
Substitute the value of VARIABLE, but first discard from that
|
variable any portion at the beginning that matches the pattern
|
PREFIX.
|
|
If there is more than one alternative for how to match against
|
PREFIX, this construct uses the longest possible match.
|
|
Thus, ‘${foo##*t}’ substitutes ‘or’, because the largest match for
|
‘*t’ at the beginning of ‘tractor’ is ‘tract’.
|
|
‘${VARIABLE#PREFIX}’
|
Substitute the value of VARIABLE, but first discard from that
|
variable any portion at the beginning that matches the pattern
|
PREFIX.
|
|
If there is more than one alternative for how to match against
|
PREFIX, this construct uses the shortest possible alternative.
|
|
Thus, ‘${foo#*t}’ substitutes ‘ractor’, because the shortest match
|
for ‘*t’ at the beginning of ‘tractor’ is just ‘t’.
|
|
|
File: libc.info, Node: I/O Overview, Next: I/O on Streams, Prev: Pattern Matching, Up: Top
|
|
11 Input/Output Overview
|
************************
|
|
Most programs need to do either input (reading data) or output (writing
|
data), or most frequently both, in order to do anything useful. The GNU
|
C Library provides such a large selection of input and output functions
|
that the hardest part is often deciding which function is most
|
appropriate!
|
|
This chapter introduces concepts and terminology relating to input
|
and output. Other chapters relating to the GNU I/O facilities are:
|
|
• *note I/O on Streams::, which covers the high-level functions that
|
operate on streams, including formatted input and output.
|
|
• *note Low-Level I/O::, which covers the basic I/O and control
|
functions on file descriptors.
|
|
• *note File System Interface::, which covers functions for operating
|
on directories and for manipulating file attributes such as access
|
modes and ownership.
|
|
• *note Pipes and FIFOs::, which includes information on the basic
|
interprocess communication facilities.
|
|
• *note Sockets::, which covers a more complicated interprocess
|
communication facility with support for networking.
|
|
• *note Low-Level Terminal Interface::, which covers functions for
|
changing how input and output to terminals or other serial devices
|
are processed.
|
|
* Menu:
|
|
* I/O Concepts:: Some basic information and terminology.
|
* File Names:: How to refer to a file.
|
|
|
File: libc.info, Node: I/O Concepts, Next: File Names, Up: I/O Overview
|
|
11.1 Input/Output Concepts
|
==========================
|
|
Before you can read or write the contents of a file, you must establish
|
a connection or communications channel to the file. This process is
|
called "opening" the file. You can open a file for reading, writing, or
|
both.
|
|
The connection to an open file is represented either as a stream or
|
as a file descriptor. You pass this as an argument to the functions
|
that do the actual read or write operations, to tell them which file to
|
operate on. Certain functions expect streams, and others are designed
|
to operate on file descriptors.
|
|
When you have finished reading to or writing from the file, you can
|
terminate the connection by "closing" the file. Once you have closed a
|
stream or file descriptor, you cannot do any more input or output
|
operations on it.
|
|
* Menu:
|
|
* Streams and File Descriptors:: The GNU C Library provides two ways
|
to access the contents of files.
|
* File Position:: The number of bytes from the
|
beginning of the file.
|
|
|
File: libc.info, Node: Streams and File Descriptors, Next: File Position, Up: I/O Concepts
|
|
11.1.1 Streams and File Descriptors
|
-----------------------------------
|
|
When you want to do input or output to a file, you have a choice of two
|
basic mechanisms for representing the connection between your program
|
and the file: file descriptors and streams. File descriptors are
|
represented as objects of type ‘int’, while streams are represented as
|
‘FILE *’ objects.
|
|
File descriptors provide a primitive, low-level interface to input
|
and output operations. Both file descriptors and streams can represent
|
a connection to a device (such as a terminal), or a pipe or socket for
|
communicating with another process, as well as a normal file. But, if
|
you want to do control operations that are specific to a particular kind
|
of device, you must use a file descriptor; there are no facilities to
|
use streams in this way. You must also use file descriptors if your
|
program needs to do input or output in special modes, such as
|
nonblocking (or polled) input (*note File Status Flags::).
|
|
Streams provide a higher-level interface, layered on top of the
|
primitive file descriptor facilities. The stream interface treats all
|
kinds of files pretty much alike—the sole exception being the three
|
styles of buffering that you can choose (*note Stream Buffering::).
|
|
The main advantage of using the stream interface is that the set of
|
functions for performing actual input and output operations (as opposed
|
to control operations) on streams is much richer and more powerful than
|
the corresponding facilities for file descriptors. The file descriptor
|
interface provides only simple functions for transferring blocks of
|
characters, but the stream interface also provides powerful formatted
|
input and output functions (‘printf’ and ‘scanf’) as well as functions
|
for character- and line-oriented input and output.
|
|
Since streams are implemented in terms of file descriptors, you can
|
extract the file descriptor from a stream and perform low-level
|
operations directly on the file descriptor. You can also initially open
|
a connection as a file descriptor and then make a stream associated with
|
that file descriptor.
|
|
In general, you should stick with using streams rather than file
|
descriptors, unless there is some specific operation you want to do that
|
can only be done on a file descriptor. If you are a beginning
|
programmer and aren’t sure what functions to use, we suggest that you
|
concentrate on the formatted input functions (*note Formatted Input::)
|
and formatted output functions (*note Formatted Output::).
|
|
If you are concerned about portability of your programs to systems
|
other than GNU, you should also be aware that file descriptors are not
|
as portable as streams. You can expect any system running ISO C to
|
support streams, but non-GNU systems may not support file descriptors at
|
all, or may only implement a subset of the GNU functions that operate on
|
file descriptors. Most of the file descriptor functions in the GNU C
|
Library are included in the POSIX.1 standard, however.
|
|
|
File: libc.info, Node: File Position, Prev: Streams and File Descriptors, Up: I/O Concepts
|
|
11.1.2 File Position
|
--------------------
|
|
One of the attributes of an open file is its "file position" that keeps
|
track of where in the file the next character is to be read or written.
|
On GNU systems, and all POSIX.1 systems, the file position is simply an
|
integer representing the number of bytes from the beginning of the file.
|
|
The file position is normally set to the beginning of the file when
|
it is opened, and each time a character is read or written, the file
|
position is incremented. In other words, access to the file is normally
|
"sequential".
|
|
Ordinary files permit read or write operations at any position within
|
the file. Some other kinds of files may also permit this. Files which
|
do permit this are sometimes referred to as "random-access" files. You
|
can change the file position using the ‘fseek’ function on a stream
|
(*note File Positioning::) or the ‘lseek’ function on a file descriptor
|
(*note I/O Primitives::). If you try to change the file position on a
|
file that doesn’t support random access, you get the ‘ESPIPE’ error.
|
|
Streams and descriptors that are opened for "append access" are
|
treated specially for output: output to such files is _always_ appended
|
sequentially to the _end_ of the file, regardless of the file position.
|
However, the file position is still used to control where in the file
|
reading is done.
|
|
If you think about it, you’ll realize that several programs can read
|
a given file at the same time. In order for each program to be able to
|
read the file at its own pace, each program must have its own file
|
pointer, which is not affected by anything the other programs do.
|
|
In fact, each opening of a file creates a separate file position.
|
Thus, if you open a file twice even in the same program, you get two
|
streams or descriptors with independent file positions.
|
|
By contrast, if you open a descriptor and then duplicate it to get
|
another descriptor, these two descriptors share the same file position:
|
changing the file position of one descriptor will affect the other.
|
|
|
File: libc.info, Node: File Names, Prev: I/O Concepts, Up: I/O Overview
|
|
11.2 File Names
|
===============
|
|
In order to open a connection to a file, or to perform other operations
|
such as deleting a file, you need some way to refer to the file. Nearly
|
all files have names that are strings—even files which are actually
|
devices such as tape drives or terminals. These strings are called
|
"file names". You specify the file name to say which file you want to
|
open or operate on.
|
|
This section describes the conventions for file names and how the
|
operating system works with them.
|
|
* Menu:
|
|
* Directories:: Directories contain entries for files.
|
* File Name Resolution:: A file name specifies how to look up a file.
|
* File Name Errors:: Error conditions relating to file names.
|
* File Name Portability:: File name portability and syntax issues.
|
|
|
File: libc.info, Node: Directories, Next: File Name Resolution, Up: File Names
|
|
11.2.1 Directories
|
------------------
|
|
In order to understand the syntax of file names, you need to understand
|
how the file system is organized into a hierarchy of directories.
|
|
A "directory" is a file that contains information to associate other
|
files with names; these associations are called "links" or "directory
|
entries". Sometimes, people speak of “files in a directory”, but in
|
reality, a directory only contains pointers to files, not the files
|
themselves.
|
|
The name of a file contained in a directory entry is called a "file
|
name component". In general, a file name consists of a sequence of one
|
or more such components, separated by the slash character (‘/’). A file
|
name which is just one component names a file with respect to its
|
directory. A file name with multiple components names a directory, and
|
then a file in that directory, and so on.
|
|
Some other documents, such as the POSIX standard, use the term
|
"pathname" for what we call a file name, and either "filename" or
|
"pathname component" for what this manual calls a file name component.
|
We don’t use this terminology because a “path” is something completely
|
different (a list of directories to search), and we think that
|
“pathname” used for something else will confuse users. We always use
|
“file name” and “file name component” (or sometimes just “component”,
|
where the context is obvious) in GNU documentation. Some macros use the
|
POSIX terminology in their names, such as ‘PATH_MAX’. These macros are
|
defined by the POSIX standard, so we cannot change their names.
|
|
You can find more detailed information about operations on
|
directories in *note File System Interface::.
|
|
|
File: libc.info, Node: File Name Resolution, Next: File Name Errors, Prev: Directories, Up: File Names
|
|
11.2.2 File Name Resolution
|
---------------------------
|
|
A file name consists of file name components separated by slash (‘/’)
|
characters. On the systems that the GNU C Library supports, multiple
|
successive ‘/’ characters are equivalent to a single ‘/’ character.
|
|
The process of determining what file a file name refers to is called
|
"file name resolution". This is performed by examining the components
|
that make up a file name in left-to-right order, and locating each
|
successive component in the directory named by the previous component.
|
Of course, each of the files that are referenced as directories must
|
actually exist, be directories instead of regular files, and have the
|
appropriate permissions to be accessible by the process; otherwise the
|
file name resolution fails.
|
|
If a file name begins with a ‘/’, the first component in the file
|
name is located in the "root directory" of the process (usually all
|
processes on the system have the same root directory). Such a file name
|
is called an "absolute file name".
|
|
Otherwise, the first component in the file name is located in the
|
current working directory (*note Working Directory::). This kind of
|
file name is called a "relative file name".
|
|
The file name components ‘.’ (“dot”) and ‘..’ (“dot-dot”) have
|
special meanings. Every directory has entries for these file name
|
components. The file name component ‘.’ refers to the directory itself,
|
while the file name component ‘..’ refers to its "parent directory" (the
|
directory that contains the link for the directory in question). As a
|
special case, ‘..’ in the root directory refers to the root directory
|
itself, since it has no parent; thus ‘/..’ is the same as ‘/’.
|
|
Here are some examples of file names:
|
|
‘/a’
|
The file named ‘a’, in the root directory.
|
|
‘/a/b’
|
The file named ‘b’, in the directory named ‘a’ in the root
|
directory.
|
|
‘a’
|
The file named ‘a’, in the current working directory.
|
|
‘/a/./b’
|
This is the same as ‘/a/b’.
|
|
‘./a’
|
The file named ‘a’, in the current working directory.
|
|
‘../a’
|
The file named ‘a’, in the parent directory of the current working
|
directory.
|
|
A file name that names a directory may optionally end in a ‘/’. You
|
can specify a file name of ‘/’ to refer to the root directory, but the
|
empty string is not a meaningful file name. If you want to refer to the
|
current working directory, use a file name of ‘.’ or ‘./’.
|
|
Unlike some other operating systems, GNU systems don’t have any
|
built-in support for file types (or extensions) or file versions as part
|
of its file name syntax. Many programs and utilities use conventions
|
for file names—for example, files containing C source code usually have
|
names suffixed with ‘.c’—but there is nothing in the file system itself
|
that enforces this kind of convention.
|
|
|
File: libc.info, Node: File Name Errors, Next: File Name Portability, Prev: File Name Resolution, Up: File Names
|
|
11.2.3 File Name Errors
|
-----------------------
|
|
Functions that accept file name arguments usually detect these ‘errno’
|
error conditions relating to the file name syntax or trouble finding the
|
named file. These errors are referred to throughout this manual as the
|
"usual file name errors".
|
|
‘EACCES’
|
The process does not have search permission for a directory
|
component of the file name.
|
|
‘ENAMETOOLONG’
|
This error is used when either the total length of a file name is
|
greater than ‘PATH_MAX’, or when an individual file name component
|
has a length greater than ‘NAME_MAX’. *Note Limits for Files::.
|
|
On GNU/Hurd systems, there is no imposed limit on overall file name
|
length, but some file systems may place limits on the length of a
|
component.
|
|
‘ENOENT’
|
This error is reported when a file referenced as a directory
|
component in the file name doesn’t exist, or when a component is a
|
symbolic link whose target file does not exist. *Note Symbolic
|
Links::.
|
|
‘ENOTDIR’
|
A file that is referenced as a directory component in the file name
|
exists, but it isn’t a directory.
|
|
‘ELOOP’
|
Too many symbolic links were resolved while trying to look up the
|
file name. The system has an arbitrary limit on the number of
|
symbolic links that may be resolved in looking up a single file
|
name, as a primitive way to detect loops. *Note Symbolic Links::.
|
|
|
File: libc.info, Node: File Name Portability, Prev: File Name Errors, Up: File Names
|
|
11.2.4 Portability of File Names
|
--------------------------------
|
|
The rules for the syntax of file names discussed in *note File Names::,
|
are the rules normally used by GNU systems and by other POSIX systems.
|
However, other operating systems may use other conventions.
|
|
There are two reasons why it can be important for you to be aware of
|
file name portability issues:
|
|
• If your program makes assumptions about file name syntax, or
|
contains embedded literal file name strings, it is more difficult
|
to get it to run under other operating systems that use different
|
syntax conventions.
|
|
• Even if you are not concerned about running your program on
|
machines that run other operating systems, it may still be possible
|
to access files that use different naming conventions. For
|
example, you may be able to access file systems on another computer
|
running a different operating system over a network, or read and
|
write disks in formats used by other operating systems.
|
|
The ISO C standard says very little about file name syntax, only that
|
file names are strings. In addition to varying restrictions on the
|
length of file names and what characters can validly appear in a file
|
name, different operating systems use different conventions and syntax
|
for concepts such as structured directories and file types or
|
extensions. Some concepts such as file versions might be supported in
|
some operating systems and not by others.
|
|
The POSIX.1 standard allows implementations to put additional
|
restrictions on file name syntax, concerning what characters are
|
permitted in file names and on the length of file name and file name
|
component strings. However, on GNU systems, any character except the
|
null character is permitted in a file name string, and on GNU/Hurd
|
systems there are no limits on the length of file name strings.
|
|
|
File: libc.info, Node: I/O on Streams, Next: Low-Level I/O, Prev: I/O Overview, Up: Top
|
|
12 Input/Output on Streams
|
**************************
|
|
This chapter describes the functions for creating streams and performing
|
input and output operations on them. As discussed in *note I/O
|
Overview::, a stream is a fairly abstract, high-level concept
|
representing a communications channel to a file, device, or process.
|
|
* Menu:
|
|
* Streams:: About the data type representing a stream.
|
* Standard Streams:: Streams to the standard input and output
|
devices are created for you.
|
* Opening Streams:: How to create a stream to talk to a file.
|
* Closing Streams:: Close a stream when you are finished with it.
|
* Streams and Threads:: Issues with streams in threaded programs.
|
* Streams and I18N:: Streams in internationalized applications.
|
* Simple Output:: Unformatted output by characters and lines.
|
* Character Input:: Unformatted input by characters and words.
|
* Line Input:: Reading a line or a record from a stream.
|
* Unreading:: Peeking ahead/pushing back input just read.
|
* Block Input/Output:: Input and output operations on blocks of data.
|
* Formatted Output:: ‘printf’ and related functions.
|
* Customizing Printf:: You can define new conversion specifiers for
|
‘printf’ and friends.
|
* Formatted Input:: ‘scanf’ and related functions.
|
* EOF and Errors:: How you can tell if an I/O error happens.
|
* Error Recovery:: What you can do about errors.
|
* Binary Streams:: Some systems distinguish between text files
|
and binary files.
|
* File Positioning:: About random-access streams.
|
* Portable Positioning:: Random access on peculiar ISO C systems.
|
* Stream Buffering:: How to control buffering of streams.
|
* Other Kinds of Streams:: Streams that do not necessarily correspond
|
to an open file.
|
* Formatted Messages:: Print strictly formatted messages.
|
|
|
File: libc.info, Node: Streams, Next: Standard Streams, Up: I/O on Streams
|
|
12.1 Streams
|
============
|
|
For historical reasons, the type of the C data structure that represents
|
a stream is called ‘FILE’ rather than “stream”. Since most of the
|
library functions deal with objects of type ‘FILE *’, sometimes the term
|
"file pointer" is also used to mean “stream”. This leads to unfortunate
|
confusion over terminology in many books on C. This manual, however, is
|
careful to use the terms “file” and “stream” only in the technical
|
sense.
|
|
The ‘FILE’ type is declared in the header file ‘stdio.h’.
|
|
-- Data Type: FILE
|
This is the data type used to represent stream objects. A ‘FILE’
|
object holds all of the internal state information about the
|
connection to the associated file, including such things as the
|
file position indicator and buffering information. Each stream
|
also has error and end-of-file status indicators that can be tested
|
with the ‘ferror’ and ‘feof’ functions; see *note EOF and Errors::.
|
|
‘FILE’ objects are allocated and managed internally by the
|
input/output library functions. Don’t try to create your own objects of
|
type ‘FILE’; let the library do it. Your programs should deal only with
|
pointers to these objects (that is, ‘FILE *’ values) rather than the
|
objects themselves.
|
|
|
File: libc.info, Node: Standard Streams, Next: Opening Streams, Prev: Streams, Up: I/O on Streams
|
|
12.2 Standard Streams
|
=====================
|
|
When the ‘main’ function of your program is invoked, it already has
|
three predefined streams open and available for use. These represent
|
the “standard” input and output channels that have been established for
|
the process.
|
|
These streams are declared in the header file ‘stdio.h’.
|
|
-- Variable: FILE * stdin
|
The "standard input" stream, which is the normal source of input
|
for the program.
|
|
-- Variable: FILE * stdout
|
The "standard output" stream, which is used for normal output from
|
the program.
|
|
-- Variable: FILE * stderr
|
The "standard error" stream, which is used for error messages and
|
diagnostics issued by the program.
|
|
On GNU systems, you can specify what files or processes correspond to
|
these streams using the pipe and redirection facilities provided by the
|
shell. (The primitives shells use to implement these facilities are
|
described in *note File System Interface::.) Most other operating
|
systems provide similar mechanisms, but the details of how to use them
|
can vary.
|
|
In the GNU C Library, ‘stdin’, ‘stdout’, and ‘stderr’ are normal
|
variables which you can set just like any others. For example, to
|
redirect the standard output to a file, you could do:
|
|
fclose (stdout);
|
stdout = fopen ("standard-output-file", "w");
|
|
Note however, that in other systems ‘stdin’, ‘stdout’, and ‘stderr’
|
are macros that you cannot assign to in the normal way. But you can use
|
‘freopen’ to get the effect of closing one and reopening it. *Note
|
Opening Streams::.
|
|
The three streams ‘stdin’, ‘stdout’, and ‘stderr’ are not unoriented
|
at program start (*note Streams and I18N::).
|
|
|
File: libc.info, Node: Opening Streams, Next: Closing Streams, Prev: Standard Streams, Up: I/O on Streams
|
|
12.3 Opening Streams
|
====================
|
|
Opening a file with the ‘fopen’ function creates a new stream and
|
establishes a connection between the stream and a file. This may
|
involve creating a new file.
|
|
Everything described in this section is declared in the header file
|
‘stdio.h’.
|
|
-- Function: FILE * fopen (const char *FILENAME, const char *OPENTYPE)
|
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd
|
lock | *Note POSIX Safety Concepts::.
|
|
The ‘fopen’ function opens a stream for I/O to the file FILENAME,
|
and returns a pointer to the stream.
|
|
The OPENTYPE argument is a string that controls how the file is
|
opened and specifies attributes of the resulting stream. It must
|
begin with one of the following sequences of characters:
|
|
‘r’
|
Open an existing file for reading only.
|
|
‘w’
|
Open the file for writing only. If the file already exists,
|
it is truncated to zero length. Otherwise a new file is
|
created.
|
|
‘a’
|
Open a file for append access; that is, writing at the end of
|
file only. If the file already exists, its initial contents
|
are unchanged and output to the stream is appended to the end
|
of the file. Otherwise, a new, empty file is created.
|
|
‘r+’
|
Open an existing file for both reading and writing. The
|
initial contents of the file are unchanged and the initial
|
file position is at the beginning of the file.
|
|
‘w+’
|
Open a file for both reading and writing. If the file already
|
exists, it is truncated to zero length. Otherwise, a new file
|
is created.
|
|
‘a+’
|
Open or create file for both reading and appending. If the
|
file exists, its initial contents are unchanged. Otherwise, a
|
new file is created. The initial file position for reading is
|
at the beginning of the file, but output is always appended to
|
the end of the file.
|
|
As you can see, ‘+’ requests a stream that can do both input and
|
output. When using such a stream, you must call ‘fflush’ (*note
|
Stream Buffering::) or a file positioning function such as ‘fseek’
|
(*note File Positioning::) when switching from reading to writing
|
or vice versa. Otherwise, internal buffers might not be emptied
|
properly.
|
|
Additional characters may appear after these to specify flags for
|
the call. Always put the mode (‘r’, ‘w+’, etc.) first; that is
|
the only part you are guaranteed will be understood by all systems.
|
|
The GNU C Library defines additional characters for use in
|
OPENTYPE:
|
|
‘c’
|
The file is opened with cancellation in the I/O functions
|
disabled.
|
|
‘e’
|
The underlying file descriptor will be closed if you use any
|
of the ‘exec…’ functions (*note Executing a File::). (This is
|
equivalent to having set ‘FD_CLOEXEC’ on that descriptor.
|
*Note Descriptor Flags::.)
|
|
‘m’
|
The file is opened and accessed using ‘mmap’. This is only
|
supported with files opened for reading.
|
|
‘x’
|
Insist on creating a new file—if a file FILENAME already
|
exists, ‘fopen’ fails rather than opening it. If you use ‘x’
|
you are guaranteed that you will not clobber an existing file.
|
This is equivalent to the ‘O_EXCL’ option to the ‘open’
|
function (*note Opening and Closing Files::).
|
|
The ‘x’ modifier is part of ISO C11.
|
|
The character ‘b’ in OPENTYPE has a standard meaning; it requests a
|
binary stream rather than a text stream. But this makes no
|
difference in POSIX systems (including GNU systems). If both ‘+’
|
and ‘b’ are specified, they can appear in either order. *Note
|
Binary Streams::.
|
|
If the OPENTYPE string contains the sequence ‘,ccs=STRING’ then
|
STRING is taken as the name of a coded character set and ‘fopen’
|
will mark the stream as wide-oriented with appropriate conversion
|
functions in place to convert from and to the character set STRING.
|
Any other stream is opened initially unoriented and the orientation
|
is decided with the first file operation. If the first operation
|
is a wide character operation, the stream is not only marked as
|
wide-oriented, also the conversion functions to convert to the
|
coded character set used for the current locale are loaded. This
|
will not change anymore from this point on even if the locale
|
selected for the ‘LC_CTYPE’ category is changed.
|
|
Any other characters in OPENTYPE are simply ignored. They may be
|
meaningful in other systems.
|
|
If the open fails, ‘fopen’ returns a null pointer.
|
|
When the sources are compiled with ‘_FILE_OFFSET_BITS == 64’ on a
|
32 bit machine this function is in fact ‘fopen64’ since the LFS
|
interface replaces transparently the old interface.
|
|
You can have multiple streams (or file descriptors) pointing to the
|
same file open at the same time. If you do only input, this works
|
straightforwardly, but you must be careful if any output streams are
|
included. *Note Stream/Descriptor Precautions::. This is equally true
|
whether the streams are in one program (not usual) or in several
|
programs (which can easily happen). It may be advantageous to use the
|
file locking facilities to avoid simultaneous access. *Note File
|
Locks::.
|
|
-- Function: FILE * fopen64 (const char *FILENAME, const char
|
*OPENTYPE)
|
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe mem fd
|
lock | *Note POSIX Safety Concepts::.
|
|
This function is similar to ‘fopen’ but the stream it returns a
|
pointer for is opened using ‘open64’. Therefore this stream can be
|
used even on files larger than 2^31 bytes on 32 bit machines.
|
|
Please note that the return type is still ‘FILE *’. There is no
|
special ‘FILE’ type for the LFS interface.
|
|
If the sources are compiled with ‘_FILE_OFFSET_BITS == 64’ on a 32
|
bits machine this function is available under the name ‘fopen’ and
|
so transparently replaces the old interface.
|
|
-- Macro: int FOPEN_MAX
|
The value of this macro is an integer constant expression that
|
represents the minimum number of streams that the implementation
|
guarantees can be open simultaneously. You might be able to open
|
more than this many streams, but that is not guaranteed. The value
|
of this constant is at least eight, which includes the three
|
standard streams ‘stdin’, ‘stdout’, and ‘stderr’. In POSIX.1
|
systems this value is determined by the ‘OPEN_MAX’ parameter; *note
|
General Limits::. In BSD and GNU, it is controlled by the
|
‘RLIMIT_NOFILE’ resource limit; *note Limits on Resources::.
|
|
-- Function: FILE * freopen (const char *FILENAME, const char
|
*OPENTYPE, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt fd |
|
*Note POSIX Safety Concepts::.
|
|
This function is like a combination of ‘fclose’ and ‘fopen’. It
|
first closes the stream referred to by STREAM, ignoring any errors
|
that are detected in the process. (Because errors are ignored, you
|
should not use ‘freopen’ on an output stream if you have actually
|
done any output using the stream.) Then the file named by FILENAME
|
is opened with mode OPENTYPE as for ‘fopen’, and associated with
|
the same stream object STREAM.
|
|
If the operation fails, a null pointer is returned; otherwise,
|
‘freopen’ returns STREAM.
|
|
‘freopen’ has traditionally been used to connect a standard stream
|
such as ‘stdin’ with a file of your own choice. This is useful in
|
programs in which use of a standard stream for certain purposes is
|
hard-coded. In the GNU C Library, you can simply close the
|
standard streams and open new ones with ‘fopen’. But other systems
|
lack this ability, so using ‘freopen’ is more portable.
|
|
When the sources are compiled with ‘_FILE_OFFSET_BITS == 64’ on a
|
32 bit machine this function is in fact ‘freopen64’ since the LFS
|
interface replaces transparently the old interface.
|
|
-- Function: FILE * freopen64 (const char *FILENAME, const char
|
*OPENTYPE, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt fd |
|
*Note POSIX Safety Concepts::.
|
|
This function is similar to ‘freopen’. The only difference is that
|
on 32 bit machine the stream returned is able to read beyond the
|
2^31 bytes limits imposed by the normal interface. It should be
|
noted that the stream pointed to by STREAM need not be opened using
|
‘fopen64’ or ‘freopen64’ since its mode is not important for this
|
function.
|
|
If the sources are compiled with ‘_FILE_OFFSET_BITS == 64’ on a 32
|
bits machine this function is available under the name ‘freopen’
|
and so transparently replaces the old interface.
|
|
In some situations it is useful to know whether a given stream is
|
available for reading or writing. This information is normally not
|
available and would have to be remembered separately. Solaris
|
introduced a few functions to get this information from the stream
|
descriptor and these functions are also available in the GNU C Library.
|
|
-- Function: int __freadable (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘__freadable’ function determines whether the stream STREAM was
|
opened to allow reading. In this case the return value is nonzero.
|
For write-only streams the function returns zero.
|
|
This function is declared in ‘stdio_ext.h’.
|
|
-- Function: int __fwritable (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘__fwritable’ function determines whether the stream STREAM was
|
opened to allow writing. In this case the return value is nonzero.
|
For read-only streams the function returns zero.
|
|
This function is declared in ‘stdio_ext.h’.
|
|
For slightly different kinds of problems there are two more
|
functions. They provide even finer-grained information.
|
|
-- Function: int __freading (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘__freading’ function determines whether the stream STREAM was
|
last read from or whether it is opened read-only. In this case the
|
return value is nonzero, otherwise it is zero. Determining whether
|
a stream opened for reading and writing was last used for writing
|
allows to draw conclusions about the content about the buffer,
|
among other things.
|
|
This function is declared in ‘stdio_ext.h’.
|
|
-- Function: int __fwriting (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Safe | *Note POSIX Safety
|
Concepts::.
|
|
The ‘__fwriting’ function determines whether the stream STREAM was
|
last written to or whether it is opened write-only. In this case
|
the return value is nonzero, otherwise it is zero.
|
|
This function is declared in ‘stdio_ext.h’.
|
|
|
File: libc.info, Node: Closing Streams, Next: Streams and Threads, Prev: Opening Streams, Up: I/O on Streams
|
|
12.4 Closing Streams
|
====================
|
|
When a stream is closed with ‘fclose’, the connection between the stream
|
and the file is canceled. After you have closed a stream, you cannot
|
perform any additional operations on it.
|
|
-- Function: int fclose (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe lock mem
|
fd | *Note POSIX Safety Concepts::.
|
|
This function causes STREAM to be closed and the connection to the
|
corresponding file to be broken. Any buffered output is written
|
and any buffered input is discarded. The ‘fclose’ function returns
|
a value of ‘0’ if the file was closed successfully, and ‘EOF’ if an
|
error was detected.
|
|
It is important to check for errors when you call ‘fclose’ to close
|
an output stream, because real, everyday errors can be detected at
|
this time. For example, when ‘fclose’ writes the remaining
|
buffered output, it might get an error because the disk is full.
|
Even if you know the buffer is empty, errors can still occur when
|
closing a file if you are using NFS.
|
|
The function ‘fclose’ is declared in ‘stdio.h’.
|
|
To close all streams currently available the GNU C Library provides
|
another function.
|
|
-- Function: int fcloseall (void)
|
Preliminary: | MT-Unsafe race:streams | AS-Unsafe | AC-Safe | *Note
|
POSIX Safety Concepts::.
|
|
This function causes all open streams of the process to be closed
|
and the connections to corresponding files to be broken. All
|
buffered data is written and any buffered input is discarded. The
|
‘fcloseall’ function returns a value of ‘0’ if all the files were
|
closed successfully, and ‘EOF’ if an error was detected.
|
|
This function should be used only in special situations, e.g., when
|
an error occurred and the program must be aborted. Normally each
|
single stream should be closed separately so that problems with
|
individual streams can be identified. It is also problematic since
|
the standard streams (*note Standard Streams::) will also be
|
closed.
|
|
The function ‘fcloseall’ is declared in ‘stdio.h’.
|
|
If the ‘main’ function to your program returns, or if you call the
|
‘exit’ function (*note Normal Termination::), all open streams are
|
automatically closed properly. If your program terminates in any other
|
manner, such as by calling the ‘abort’ function (*note Aborting a
|
Program::) or from a fatal signal (*note Signal Handling::), open
|
streams might not be closed properly. Buffered output might not be
|
flushed and files may be incomplete. For more information on buffering
|
of streams, see *note Stream Buffering::.
|
|
|
File: libc.info, Node: Streams and Threads, Next: Streams and I18N, Prev: Closing Streams, Up: I/O on Streams
|
|
12.5 Streams and Threads
|
========================
|
|
Streams can be used in multi-threaded applications in the same way they
|
are used in single-threaded applications. But the programmer must be
|
aware of the possible complications. It is important to know about
|
these also if the program one writes never use threads since the design
|
and implementation of many stream functions are heavily influenced by
|
the requirements added by multi-threaded programming.
|
|
The POSIX standard requires that by default the stream operations are
|
atomic. I.e., issuing two stream operations for the same stream in two
|
threads at the same time will cause the operations to be executed as if
|
they were issued sequentially. The buffer operations performed while
|
reading or writing are protected from other uses of the same stream. To
|
do this each stream has an internal lock object which has to be
|
(implicitly) acquired before any work can be done.
|
|
But there are situations where this is not enough and there are also
|
situations where this is not wanted. The implicit locking is not enough
|
if the program requires more than one stream function call to happen
|
atomically. One example would be if an output line a program wants to
|
generate is created by several function calls. The functions by
|
themselves would ensure only atomicity of their own operation, but not
|
atomicity over all the function calls. For this it is necessary to
|
perform the stream locking in the application code.
|
|
-- Function: void flockfile (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Unsafe lock | *Note POSIX
|
Safety Concepts::.
|
|
The ‘flockfile’ function acquires the internal locking object
|
associated with the stream STREAM. This ensures that no other
|
thread can explicitly through ‘flockfile’/‘ftrylockfile’ or
|
implicitly through the call of a stream function lock the stream.
|
The thread will block until the lock is acquired. An explicit call
|
to ‘funlockfile’ has to be used to release the lock.
|
|
-- Function: int ftrylockfile (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Unsafe lock | *Note POSIX
|
Safety Concepts::.
|
|
The ‘ftrylockfile’ function tries to acquire the internal locking
|
object associated with the stream STREAM just like ‘flockfile’.
|
But unlike ‘flockfile’ this function does not block if the lock is
|
not available. ‘ftrylockfile’ returns zero if the lock was
|
successfully acquired. Otherwise the stream is locked by another
|
thread.
|
|
-- Function: void funlockfile (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Safe | AC-Unsafe lock | *Note POSIX
|
Safety Concepts::.
|
|
The ‘funlockfile’ function releases the internal locking object of
|
the stream STREAM. The stream must have been locked before by a
|
call to ‘flockfile’ or a successful call of ‘ftrylockfile’. The
|
implicit locking performed by the stream operations do not count.
|
The ‘funlockfile’ function does not return an error status and the
|
behavior of a call for a stream which is not locked by the current
|
thread is undefined.
|
|
The following example shows how the functions above can be used to
|
generate an output line atomically even in multi-threaded applications
|
(yes, the same job could be done with one ‘fprintf’ call but it is
|
sometimes not possible):
|
|
FILE *fp;
|
{
|
…
|
flockfile (fp);
|
fputs ("This is test number ", fp);
|
fprintf (fp, "%d\n", test);
|
funlockfile (fp)
|
}
|
|
Without the explicit locking it would be possible for another thread
|
to use the stream FP after the ‘fputs’ call returns and before ‘fprintf’
|
was called with the result that the number does not follow the word
|
‘number’.
|
|
From this description it might already be clear that the locking
|
objects in streams are no simple mutexes. Since locking the same stream
|
twice in the same thread is allowed the locking objects must be
|
equivalent to recursive mutexes. These mutexes keep track of the owner
|
and the number of times the lock is acquired. The same number of
|
‘funlockfile’ calls by the same threads is necessary to unlock the
|
stream completely. For instance:
|
|
void
|
foo (FILE *fp)
|
{
|
ftrylockfile (fp);
|
fputs ("in foo\n", fp);
|
/* This is very wrong!!! */
|
funlockfile (fp);
|
}
|
|
It is important here that the ‘funlockfile’ function is only called
|
if the ‘ftrylockfile’ function succeeded in locking the stream. It is
|
therefore always wrong to ignore the result of ‘ftrylockfile’. And it
|
makes no sense since otherwise one would use ‘flockfile’. The result of
|
code like that above is that either ‘funlockfile’ tries to free a stream
|
that hasn’t been locked by the current thread or it frees the stream
|
prematurely. The code should look like this:
|
|
void
|
foo (FILE *fp)
|
{
|
if (ftrylockfile (fp) == 0)
|
{
|
fputs ("in foo\n", fp);
|
funlockfile (fp);
|
}
|
}
|
|
Now that we covered why it is necessary to have locking it is
|
necessary to talk about situations when locking is unwanted and what can
|
be done. The locking operations (explicit or implicit) don’t come for
|
free. Even if a lock is not taken the cost is not zero. The operations
|
which have to be performed require memory operations that are safe in
|
multi-processor environments. With the many local caches involved in
|
such systems this is quite costly. So it is best to avoid the locking
|
completely if it is not needed – because the code in question is never
|
used in a context where two or more threads may use a stream at a time.
|
This can be determined most of the time for application code; for
|
library code which can be used in many contexts one should default to be
|
conservative and use locking.
|
|
There are two basic mechanisms to avoid locking. The first is to use
|
the ‘_unlocked’ variants of the stream operations. The POSIX standard
|
defines quite a few of those and the GNU C Library adds a few more.
|
These variants of the functions behave just like the functions with the
|
name without the suffix except that they do not lock the stream. Using
|
these functions is very desirable since they are potentially much
|
faster. This is not only because the locking operation itself is
|
avoided. More importantly, functions like ‘putc’ and ‘getc’ are very
|
simple and traditionally (before the introduction of threads) were
|
implemented as macros which are very fast if the buffer is not empty.
|
With the addition of locking requirements these functions are no longer
|
implemented as macros since they would expand to too much code. But
|
these macros are still available with the same functionality under the
|
new names ‘putc_unlocked’ and ‘getc_unlocked’. This possibly huge
|
difference of speed also suggests the use of the ‘_unlocked’ functions
|
even if locking is required. The difference is that the locking then
|
has to be performed in the program:
|
|
void
|
foo (FILE *fp, char *buf)
|
{
|
flockfile (fp);
|
while (*buf != '/')
|
putc_unlocked (*buf++, fp);
|
funlockfile (fp);
|
}
|
|
If in this example the ‘putc’ function would be used and the explicit
|
locking would be missing the ‘putc’ function would have to acquire the
|
lock in every call, potentially many times depending on when the loop
|
terminates. Writing it the way illustrated above allows the
|
‘putc_unlocked’ macro to be used which means no locking and direct
|
manipulation of the buffer of the stream.
|
|
A second way to avoid locking is by using a non-standard function
|
which was introduced in Solaris and is available in the GNU C Library as
|
well.
|
|
-- Function: int __fsetlocking (FILE *STREAM, int TYPE)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe lock | AC-Safe |
|
*Note POSIX Safety Concepts::.
|
|
The ‘__fsetlocking’ function can be used to select whether the
|
stream operations will implicitly acquire the locking object of the
|
stream STREAM. By default this is done but it can be disabled and
|
reinstated using this function. There are three values defined for
|
the TYPE parameter.
|
|
‘FSETLOCKING_INTERNAL’
|
The stream ‘stream’ will from now on use the default internal
|
locking. Every stream operation with exception of the
|
‘_unlocked’ variants will implicitly lock the stream.
|
|
‘FSETLOCKING_BYCALLER’
|
After the ‘__fsetlocking’ function returns, the user is
|
responsible for locking the stream. None of the stream
|
operations will implicitly do this anymore until the state is
|
set back to ‘FSETLOCKING_INTERNAL’.
|
|
‘FSETLOCKING_QUERY’
|
‘__fsetlocking’ only queries the current locking state of the
|
stream. The return value will be ‘FSETLOCKING_INTERNAL’ or
|
‘FSETLOCKING_BYCALLER’ depending on the state.
|
|
The return value of ‘__fsetlocking’ is either
|
‘FSETLOCKING_INTERNAL’ or ‘FSETLOCKING_BYCALLER’ depending on the
|
state of the stream before the call.
|
|
This function and the values for the TYPE parameter are declared in
|
‘stdio_ext.h’.
|
|
This function is especially useful when program code has to be used
|
which is written without knowledge about the ‘_unlocked’ functions (or
|
if the programmer was too lazy to use them).
|
|
|
File: libc.info, Node: Streams and I18N, Next: Simple Output, Prev: Streams and Threads, Up: I/O on Streams
|
|
12.6 Streams in Internationalized Applications
|
==============================================
|
|
ISO C90 introduced the new type ‘wchar_t’ to allow handling larger
|
character sets. What was missing was a possibility to output strings of
|
‘wchar_t’ directly. One had to convert them into multibyte strings
|
using ‘mbstowcs’ (there was no ‘mbsrtowcs’ yet) and then use the normal
|
stream functions. While this is doable it is very cumbersome since
|
performing the conversions is not trivial and greatly increases program
|
complexity and size.
|
|
The Unix standard early on (I think in XPG4.2) introduced two
|
additional format specifiers for the ‘printf’ and ‘scanf’ families of
|
functions. Printing and reading of single wide characters was made
|
possible using the ‘%C’ specifier and wide character strings can be
|
handled with ‘%S’. These modifiers behave just like ‘%c’ and ‘%s’ only
|
that they expect the corresponding argument to have the wide character
|
type and that the wide character and string are transformed into/from
|
multibyte strings before being used.
|
|
This was a beginning but it is still not good enough. Not always is
|
it desirable to use ‘printf’ and ‘scanf’. The other, smaller and faster
|
functions cannot handle wide characters. Second, it is not possible to
|
have a format string for ‘printf’ and ‘scanf’ consisting of wide
|
characters. The result is that format strings would have to be
|
generated if they have to contain non-basic characters.
|
|
In the Amendment 1 to ISO C90 a whole new set of functions was added
|
to solve the problem. Most of the stream functions got a counterpart
|
which take a wide character or wide character string instead of a
|
character or string respectively. The new functions operate on the same
|
streams (like ‘stdout’). This is different from the model of the C++
|
runtime library where separate streams for wide and normal I/O are used.
|
|
Being able to use the same stream for wide and normal operations
|
comes with a restriction: a stream can be used either for wide
|
operations or for normal operations. Once it is decided there is no way
|
back. Only a call to ‘freopen’ or ‘freopen64’ can reset the
|
"orientation". The orientation can be decided in three ways:
|
|
• If any of the normal character functions are used (this includes
|
the ‘fread’ and ‘fwrite’ functions) the stream is marked as not
|
wide oriented.
|
|
• If any of the wide character functions are used the stream is
|
marked as wide oriented.
|
|
• The ‘fwide’ function can be used to set the orientation either way.
|
|
It is important to never mix the use of wide and not wide operations
|
on a stream. There are no diagnostics issued. The application behavior
|
will simply be strange or the application will simply crash. The
|
‘fwide’ function can help avoid this.
|
|
-- Function: int fwide (FILE *STREAM, int MODE)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock | *Note
|
POSIX Safety Concepts::.
|
|
The ‘fwide’ function can be used to set and query the state of the
|
orientation of the stream STREAM. If the MODE parameter has a
|
positive value the streams get wide oriented, for negative values
|
narrow oriented. It is not possible to overwrite previous
|
orientations with ‘fwide’. I.e., if the stream STREAM was already
|
oriented before the call nothing is done.
|
|
If MODE is zero the current orientation state is queried and
|
nothing is changed.
|
|
The ‘fwide’ function returns a negative value, zero, or a positive
|
value if the stream is narrow, not at all, or wide oriented
|
respectively.
|
|
This function was introduced in Amendment 1 to ISO C90 and is
|
declared in ‘wchar.h’.
|
|
It is generally a good idea to orient a stream as early as possible.
|
This can prevent surprise especially for the standard streams ‘stdin’,
|
‘stdout’, and ‘stderr’. If some library function in some situations
|
uses one of these streams and this use orients the stream in a different
|
way the rest of the application expects it one might end up with hard to
|
reproduce errors. Remember that no errors are signal if the streams are
|
used incorrectly. Leaving a stream unoriented after creation is
|
normally only necessary for library functions which create streams which
|
can be used in different contexts.
|
|
When writing code which uses streams and which can be used in
|
different contexts it is important to query the orientation of the
|
stream before using it (unless the rules of the library interface demand
|
a specific orientation). The following little, silly function
|
illustrates this.
|
|
void
|
print_f (FILE *fp)
|
{
|
if (fwide (fp, 0) > 0)
|
/* Positive return value means wide orientation. */
|
fputwc (L'f', fp);
|
else
|
fputc ('f', fp);
|
}
|
|
Note that in this case the function ‘print_f’ decides about the
|
orientation of the stream if it was unoriented before (will not happen
|
if the advice above is followed).
|
|
The encoding used for the ‘wchar_t’ values is unspecified and the
|
user must not make any assumptions about it. For I/O of ‘wchar_t’
|
values this means that it is impossible to write these values directly
|
to the stream. This is not what follows from the ISO C locale model
|
either. What happens instead is that the bytes read from or written to
|
the underlying media are first converted into the internal encoding
|
chosen by the implementation for ‘wchar_t’. The external encoding is
|
determined by the ‘LC_CTYPE’ category of the current locale or by the
|
‘ccs’ part of the mode specification given to ‘fopen’, ‘fopen64’,
|
‘freopen’, or ‘freopen64’. How and when the conversion happens is
|
unspecified and it happens invisibly to the user.
|
|
Since a stream is created in the unoriented state it has at that
|
point no conversion associated with it. The conversion which will be
|
used is determined by the ‘LC_CTYPE’ category selected at the time the
|
stream is oriented. If the locales are changed at the runtime this
|
might produce surprising results unless one pays attention. This is
|
just another good reason to orient the stream explicitly as soon as
|
possible, perhaps with a call to ‘fwide’.
|
|
|
File: libc.info, Node: Simple Output, Next: Character Input, Prev: Streams and I18N, Up: I/O on Streams
|
|
12.7 Simple Output by Characters or Lines
|
=========================================
|
|
This section describes functions for performing character- and
|
line-oriented output.
|
|
These narrow stream functions are declared in the header file
|
‘stdio.h’ and the wide stream functions in ‘wchar.h’.
|
|
-- Function: int fputc (int C, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The ‘fputc’ function converts the character C to type ‘unsigned
|
char’, and writes it to the stream STREAM. ‘EOF’ is returned if a
|
write error occurs; otherwise the character C is returned.
|
|
-- Function: wint_t fputwc (wchar_t WC, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The ‘fputwc’ function writes the wide character WC to the stream
|
STREAM. ‘WEOF’ is returned if a write error occurs; otherwise the
|
character WC is returned.
|
|
-- Function: int fputc_unlocked (int C, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fputc_unlocked’ function is equivalent to the ‘fputc’ function
|
except that it does not implicitly lock the stream.
|
|
-- Function: wint_t fputwc_unlocked (wchar_t WC, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fputwc_unlocked’ function is equivalent to the ‘fputwc’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int putc (int C, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
This is just like ‘fputc’, except that most systems implement it as
|
a macro, making it faster. One consequence is that it may evaluate
|
the STREAM argument more than once, which is an exception to the
|
general rule for macros. ‘putc’ is usually the best function to
|
use for writing a single character.
|
|
-- Function: wint_t putwc (wchar_t WC, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
This is just like ‘fputwc’, except that it can be implement as a
|
macro, making it faster. One consequence is that it may evaluate
|
the STREAM argument more than once, which is an exception to the
|
general rule for macros. ‘putwc’ is usually the best function to
|
use for writing a single wide character.
|
|
-- Function: int putc_unlocked (int C, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘putc_unlocked’ function is equivalent to the ‘putc’ function
|
except that it does not implicitly lock the stream.
|
|
-- Function: wint_t putwc_unlocked (wchar_t WC, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘putwc_unlocked’ function is equivalent to the ‘putwc’ function
|
except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int putchar (int C)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The ‘putchar’ function is equivalent to ‘putc’ with ‘stdout’ as the
|
value of the STREAM argument.
|
|
-- Function: wint_t putwchar (wchar_t WC)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The ‘putwchar’ function is equivalent to ‘putwc’ with ‘stdout’ as
|
the value of the STREAM argument.
|
|
-- Function: int putchar_unlocked (int C)
|
Preliminary: | MT-Unsafe race:stdout | AS-Unsafe corrupt |
|
AC-Unsafe corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘putchar_unlocked’ function is equivalent to the ‘putchar’
|
function except that it does not implicitly lock the stream.
|
|
-- Function: wint_t putwchar_unlocked (wchar_t WC)
|
Preliminary: | MT-Unsafe race:stdout | AS-Unsafe corrupt |
|
AC-Unsafe corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘putwchar_unlocked’ function is equivalent to the ‘putwchar’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int fputs (const char *S, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The function ‘fputs’ writes the string S to the stream STREAM. The
|
terminating null character is not written. This function does
|
_not_ add a newline character, either. It outputs only the
|
characters in the string.
|
|
This function returns ‘EOF’ if a write error occurs, and otherwise
|
a non-negative value.
|
|
For example:
|
|
fputs ("Are ", stdout);
|
fputs ("you ", stdout);
|
fputs ("hungry?\n", stdout);
|
|
outputs the text ‘Are you hungry?’ followed by a newline.
|
|
-- Function: int fputws (const wchar_t *WS, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe corrupt lock
|
| *Note POSIX Safety Concepts::.
|
|
The function ‘fputws’ writes the wide character string WS to the
|
stream STREAM. The terminating null character is not written.
|
This function does _not_ add a newline character, either. It
|
outputs only the characters in the string.
|
|
This function returns ‘WEOF’ if a write error occurs, and otherwise
|
a non-negative value.
|
|
-- Function: int fputs_unlocked (const char *S, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fputs_unlocked’ function is equivalent to the ‘fputs’ function
|
except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int fputws_unlocked (const wchar_t *WS, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fputws_unlocked’ function is equivalent to the ‘fputws’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int puts (const char *S)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘puts’ function writes the string S to the stream ‘stdout’
|
followed by a newline. The terminating null character of the
|
string is not written. (Note that ‘fputs’ does _not_ write a
|
newline as this function does.)
|
|
‘puts’ is the most convenient function for printing simple
|
messages. For example:
|
|
puts ("This is a message.");
|
|
outputs the text ‘This is a message.’ followed by a newline.
|
|
-- Function: int putw (int W, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function writes the word W (that is, an ‘int’) to STREAM. It
|
is provided for compatibility with SVID, but we recommend you use
|
‘fwrite’ instead (*note Block Input/Output::).
|
|
|
File: libc.info, Node: Character Input, Next: Line Input, Prev: Simple Output, Up: I/O on Streams
|
|
12.8 Character Input
|
====================
|
|
This section describes functions for performing character-oriented
|
input. These narrow stream functions are declared in the header file
|
‘stdio.h’ and the wide character functions are declared in ‘wchar.h’.
|
|
These functions return an ‘int’ or ‘wint_t’ value (for narrow and
|
wide stream functions respectively) that is either a character of input,
|
or the special value ‘EOF’/‘WEOF’ (usually -1). For the narrow stream
|
functions it is important to store the result of these functions in a
|
variable of type ‘int’ instead of ‘char’, even when you plan to use it
|
only as a character. Storing ‘EOF’ in a ‘char’ variable truncates its
|
value to the size of a character, so that it is no longer
|
distinguishable from the valid character ‘(char) -1’. So always use an
|
‘int’ for the result of ‘getc’ and friends, and check for ‘EOF’ after
|
the call; once you’ve verified that the result is not ‘EOF’, you can be
|
sure that it will fit in a ‘char’ variable without loss of information.
|
|
-- Function: int fgetc (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function reads the next character as an ‘unsigned char’ from
|
the stream STREAM and returns its value, converted to an ‘int’. If
|
an end-of-file condition or read error occurs, ‘EOF’ is returned
|
instead.
|
|
-- Function: wint_t fgetwc (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function reads the next wide character from the stream STREAM
|
and returns its value. If an end-of-file condition or read error
|
occurs, ‘WEOF’ is returned instead.
|
|
-- Function: int fgetc_unlocked (FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fgetc_unlocked’ function is equivalent to the ‘fgetc’ function
|
except that it does not implicitly lock the stream.
|
|
-- Function: wint_t fgetwc_unlocked (FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fgetwc_unlocked’ function is equivalent to the ‘fgetwc’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int getc (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This is just like ‘fgetc’, except that it is permissible (and
|
typical) for it to be implemented as a macro that evaluates the
|
STREAM argument more than once. ‘getc’ is often highly optimized,
|
so it is usually the best function to use to read a single
|
character.
|
|
-- Function: wint_t getwc (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This is just like ‘fgetwc’, except that it is permissible for it to
|
be implemented as a macro that evaluates the STREAM argument more
|
than once. ‘getwc’ can be highly optimized, so it is usually the
|
best function to use to read a single wide character.
|
|
-- Function: int getc_unlocked (FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘getc_unlocked’ function is equivalent to the ‘getc’ function
|
except that it does not implicitly lock the stream.
|
|
-- Function: wint_t getwc_unlocked (FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘getwc_unlocked’ function is equivalent to the ‘getwc’ function
|
except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: int getchar (void)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘getchar’ function is equivalent to ‘getc’ with ‘stdin’ as the
|
value of the STREAM argument.
|
|
-- Function: wint_t getwchar (void)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘getwchar’ function is equivalent to ‘getwc’ with ‘stdin’ as
|
the value of the STREAM argument.
|
|
-- Function: int getchar_unlocked (void)
|
Preliminary: | MT-Unsafe race:stdin | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘getchar_unlocked’ function is equivalent to the ‘getchar’
|
function except that it does not implicitly lock the stream.
|
|
-- Function: wint_t getwchar_unlocked (void)
|
Preliminary: | MT-Unsafe race:stdin | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘getwchar_unlocked’ function is equivalent to the ‘getwchar’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
Here is an example of a function that does input using ‘fgetc’. It
|
would work just as well using ‘getc’ instead, or using ‘getchar ()’
|
instead of ‘fgetc (stdin)’. The code would also work the same for the
|
wide character stream functions.
|
|
int
|
y_or_n_p (const char *question)
|
{
|
fputs (question, stdout);
|
while (1)
|
{
|
int c, answer;
|
/* Write a space to separate answer from question. */
|
fputc (' ', stdout);
|
/* Read the first character of the line.
|
This should be the answer character, but might not be. */
|
c = tolower (fgetc (stdin));
|
answer = c;
|
/* Discard rest of input line. */
|
while (c != '\n' && c != EOF)
|
c = fgetc (stdin);
|
/* Obey the answer if it was valid. */
|
if (answer == 'y')
|
return 1;
|
if (answer == 'n')
|
return 0;
|
/* Answer was invalid: ask for valid answer. */
|
fputs ("Please answer y or n:", stdout);
|
}
|
}
|
|
-- Function: int getw (FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function reads a word (that is, an ‘int’) from STREAM. It’s
|
provided for compatibility with SVID. We recommend you use ‘fread’
|
instead (*note Block Input/Output::). Unlike ‘getc’, any ‘int’
|
value could be a valid result. ‘getw’ returns ‘EOF’ when it
|
encounters end-of-file or an error, but there is no way to
|
distinguish this from an input word with value -1.
|
|
|
File: libc.info, Node: Line Input, Next: Unreading, Prev: Character Input, Up: I/O on Streams
|
|
12.9 Line-Oriented Input
|
========================
|
|
Since many programs interpret input on the basis of lines, it is
|
convenient to have functions to read a line of text from a stream.
|
|
Standard C has functions to do this, but they aren’t very safe: null
|
characters and even (for ‘gets’) long lines can confuse them. So the
|
GNU C Library provides the nonstandard ‘getline’ function that makes it
|
easy to read lines reliably.
|
|
Another GNU extension, ‘getdelim’, generalizes ‘getline’. It reads a
|
delimited record, defined as everything through the next occurrence of a
|
specified delimiter character.
|
|
All these functions are declared in ‘stdio.h’.
|
|
-- Function: ssize_t getline (char **LINEPTR, size_t *N, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt heap | AC-Unsafe lock
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
This function reads an entire line from STREAM, storing the text
|
(including the newline and a terminating null character) in a
|
buffer and storing the buffer address in ‘*LINEPTR’.
|
|
Before calling ‘getline’, you should place in ‘*LINEPTR’ the
|
address of a buffer ‘*N’ bytes long, allocated with ‘malloc’. If
|
this buffer is long enough to hold the line, ‘getline’ stores the
|
line in this buffer. Otherwise, ‘getline’ makes the buffer bigger
|
using ‘realloc’, storing the new buffer address back in ‘*LINEPTR’
|
and the increased size back in ‘*N’. *Note Unconstrained
|
Allocation::.
|
|
If you set ‘*LINEPTR’ to a null pointer, and ‘*N’ to zero, before
|
the call, then ‘getline’ allocates the initial buffer for you by
|
calling ‘malloc’. This buffer remains allocated even if ‘getline’
|
encounters errors and is unable to read any bytes.
|
|
In either case, when ‘getline’ returns, ‘*LINEPTR’ is a ‘char *’
|
which points to the text of the line.
|
|
When ‘getline’ is successful, it returns the number of characters
|
read (including the newline, but not including the terminating
|
null). This value enables you to distinguish null characters that
|
are part of the line from the null character inserted as a
|
terminator.
|
|
This function is a GNU extension, but it is the recommended way to
|
read lines from a stream. The alternative standard functions are
|
unreliable.
|
|
If an error occurs or end of file is reached without any bytes
|
read, ‘getline’ returns ‘-1’.
|
|
-- Function: ssize_t getdelim (char **LINEPTR, size_t *N, int
|
DELIMITER, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt heap | AC-Unsafe lock
|
corrupt mem | *Note POSIX Safety Concepts::.
|
|
This function is like ‘getline’ except that the character which
|
tells it to stop reading is not necessarily newline. The argument
|
DELIMITER specifies the delimiter character; ‘getdelim’ keeps
|
reading until it sees that character (or end of file).
|
|
The text is stored in LINEPTR, including the delimiter character
|
and a terminating null. Like ‘getline’, ‘getdelim’ makes LINEPTR
|
bigger if it isn’t big enough.
|
|
‘getline’ is in fact implemented in terms of ‘getdelim’, just like
|
this:
|
|
ssize_t
|
getline (char **lineptr, size_t *n, FILE *stream)
|
{
|
return getdelim (lineptr, n, '\n', stream);
|
}
|
|
-- Function: char * fgets (char *S, int COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘fgets’ function reads characters from the stream STREAM up to
|
and including a newline character and stores them in the string S,
|
adding a null character to mark the end of the string. You must
|
supply COUNT characters worth of space in S, but the number of
|
characters read is at most COUNT − 1. The extra character space is
|
used to hold the null character at the end of the string.
|
|
If the system is already at end of file when you call ‘fgets’, then
|
the contents of the array S are unchanged and a null pointer is
|
returned. A null pointer is also returned if a read error occurs.
|
Otherwise, the return value is the pointer S.
|
|
*Warning:* If the input data has a null character, you can’t tell.
|
So don’t use ‘fgets’ unless you know the data cannot contain a
|
null. Don’t use it to read files edited by the user because, if
|
the user inserts a null character, you should either handle it
|
properly or print a clear error message. We recommend using
|
‘getline’ instead of ‘fgets’.
|
|
-- Function: wchar_t * fgetws (wchar_t *WS, int COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘fgetws’ function reads wide characters from the stream STREAM
|
up to and including a newline character and stores them in the
|
string WS, adding a null wide character to mark the end of the
|
string. You must supply COUNT wide characters worth of space in
|
WS, but the number of characters read is at most COUNT − 1. The
|
extra character space is used to hold the null wide character at
|
the end of the string.
|
|
If the system is already at end of file when you call ‘fgetws’,
|
then the contents of the array WS are unchanged and a null pointer
|
is returned. A null pointer is also returned if a read error
|
occurs. Otherwise, the return value is the pointer WS.
|
|
*Warning:* If the input data has a null wide character (which are
|
null bytes in the input stream), you can’t tell. So don’t use
|
‘fgetws’ unless you know the data cannot contain a null. Don’t use
|
it to read files edited by the user because, if the user inserts a
|
null character, you should either handle it properly or print a
|
clear error message.
|
|
-- Function: char * fgets_unlocked (char *S, int COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fgets_unlocked’ function is equivalent to the ‘fgets’ function
|
except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: wchar_t * fgetws_unlocked (wchar_t *WS, int COUNT, FILE
|
*STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fgetws_unlocked’ function is equivalent to the ‘fgetws’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Deprecated function: char * gets (char *S)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The function ‘gets’ reads characters from the stream ‘stdin’ up to
|
the next newline character, and stores them in the string S. The
|
newline character is discarded (note that this differs from the
|
behavior of ‘fgets’, which copies the newline character into the
|
string). If ‘gets’ encounters a read error or end-of-file, it
|
returns a null pointer; otherwise it returns S.
|
|
*Warning:* The ‘gets’ function is *very dangerous* because it
|
provides no protection against overflowing the string S. The GNU C
|
Library includes it for compatibility only. You should *always*
|
use ‘fgets’ or ‘getline’ instead. To remind you of this, the
|
linker (if using GNU ‘ld’) will issue a warning whenever you use
|
‘gets’.
|
|
|
File: libc.info, Node: Unreading, Next: Block Input/Output, Prev: Line Input, Up: I/O on Streams
|
|
12.10 Unreading
|
===============
|
|
In parser programs it is often useful to examine the next character in
|
the input stream without removing it from the stream. This is called
|
“peeking ahead” at the input because your program gets a glimpse of the
|
input it will read next.
|
|
Using stream I/O, you can peek ahead at input by first reading it and
|
then "unreading" it (also called "pushing it back" on the stream).
|
Unreading a character makes it available to be input again from the
|
stream, by the next call to ‘fgetc’ or other input function on that
|
stream.
|
|
* Menu:
|
|
* Unreading Idea:: An explanation of unreading with pictures.
|
* How Unread:: How to call ‘ungetc’ to do unreading.
|
|
|
File: libc.info, Node: Unreading Idea, Next: How Unread, Up: Unreading
|
|
12.10.1 What Unreading Means
|
----------------------------
|
|
Here is a pictorial explanation of unreading. Suppose you have a stream
|
reading a file that contains just six characters, the letters ‘foobar’.
|
Suppose you have read three characters so far. The situation looks like
|
this:
|
|
f o o b a r
|
^
|
|
so the next input character will be ‘b’.
|
|
If instead of reading ‘b’ you unread the letter ‘o’, you get a
|
situation like this:
|
|
f o o b a r
|
|
|
o--
|
^
|
|
so that the next input characters will be ‘o’ and ‘b’.
|
|
If you unread ‘9’ instead of ‘o’, you get this situation:
|
|
f o o b a r
|
|
|
9--
|
^
|
|
so that the next input characters will be ‘9’ and ‘b’.
|
|
|
File: libc.info, Node: How Unread, Prev: Unreading Idea, Up: Unreading
|
|
12.10.2 Using ‘ungetc’ To Do Unreading
|
--------------------------------------
|
|
The function to unread a character is called ‘ungetc’, because it
|
reverses the action of ‘getc’.
|
|
-- Function: int ungetc (int C, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘ungetc’ function pushes back the character C onto the input
|
stream STREAM. So the next input from STREAM will read C before
|
anything else.
|
|
If C is ‘EOF’, ‘ungetc’ does nothing and just returns ‘EOF’. This
|
lets you call ‘ungetc’ with the return value of ‘getc’ without
|
needing to check for an error from ‘getc’.
|
|
The character that you push back doesn’t have to be the same as the
|
last character that was actually read from the stream. In fact, it
|
isn’t necessary to actually read any characters from the stream
|
before unreading them with ‘ungetc’! But that is a strange way to
|
write a program; usually ‘ungetc’ is used only to unread a
|
character that was just read from the same stream. The GNU C
|
Library supports this even on files opened in binary mode, but
|
other systems might not.
|
|
The GNU C Library only supports one character of pushback—in other
|
words, it does not work to call ‘ungetc’ twice without doing input
|
in between. Other systems might let you push back multiple
|
characters; then reading from the stream retrieves the characters
|
in the reverse order that they were pushed.
|
|
Pushing back characters doesn’t alter the file; only the internal
|
buffering for the stream is affected. If a file positioning
|
function (such as ‘fseek’, ‘fseeko’ or ‘rewind’; *note File
|
Positioning::) is called, any pending pushed-back characters are
|
discarded.
|
|
Unreading a character on a stream that is at end of file clears the
|
end-of-file indicator for the stream, because it makes the
|
character of input available. After you read that character,
|
trying to read again will encounter end of file.
|
|
-- Function: wint_t ungetwc (wint_t WC, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
The ‘ungetwc’ function behaves just like ‘ungetc’ just that it
|
pushes back a wide character.
|
|
Here is an example showing the use of ‘getc’ and ‘ungetc’ to skip
|
over whitespace characters. When this function reaches a non-whitespace
|
character, it unreads that character to be seen again on the next read
|
operation on the stream.
|
|
#include <stdio.h>
|
#include <ctype.h>
|
|
void
|
skip_whitespace (FILE *stream)
|
{
|
int c;
|
do
|
/* No need to check for ‘EOF’ because it is not
|
‘isspace’, and ‘ungetc’ ignores ‘EOF’. */
|
c = getc (stream);
|
while (isspace (c));
|
ungetc (c, stream);
|
}
|
|
|
File: libc.info, Node: Block Input/Output, Next: Formatted Output, Prev: Unreading, Up: I/O on Streams
|
|
12.11 Block Input/Output
|
========================
|
|
This section describes how to do input and output operations on blocks
|
of data. You can use these functions to read and write binary data, as
|
well as to read and write text in fixed-size blocks instead of by
|
characters or lines.
|
|
Binary files are typically used to read and write blocks of data in
|
the same format as is used to represent the data in a running program.
|
In other words, arbitrary blocks of memory—not just character or string
|
objects—can be written to a binary file, and meaningfully read in again
|
by the same program.
|
|
Storing data in binary form is often considerably more efficient than
|
using the formatted I/O functions. Also, for floating-point numbers,
|
the binary form avoids possible loss of precision in the conversion
|
process. On the other hand, binary files can’t be examined or modified
|
easily using many standard file utilities (such as text editors), and
|
are not portable between different implementations of the language, or
|
different kinds of computers.
|
|
These functions are declared in ‘stdio.h’.
|
|
-- Function: size_t fread (void *DATA, size_t SIZE, size_t COUNT, FILE
|
*STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function reads up to COUNT objects of size SIZE into the array
|
DATA, from the stream STREAM. It returns the number of objects
|
actually read, which might be less than COUNT if a read error
|
occurs or the end of the file is reached. This function returns a
|
value of zero (and doesn’t read anything) if either SIZE or COUNT
|
is zero.
|
|
If ‘fread’ encounters end of file in the middle of an object, it
|
returns the number of complete objects read, and discards the
|
partial object. Therefore, the stream remains at the actual end of
|
the file.
|
|
-- Function: size_t fread_unlocked (void *DATA, size_t SIZE, size_t
|
COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fread_unlocked’ function is equivalent to the ‘fread’ function
|
except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
-- Function: size_t fwrite (const void *DATA, size_t SIZE, size_t
|
COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe | AS-Unsafe corrupt | AC-Unsafe lock corrupt
|
| *Note POSIX Safety Concepts::.
|
|
This function writes up to COUNT objects of size SIZE from the
|
array DATA, to the stream STREAM. The return value is normally
|
COUNT, if the call succeeds. Any other value indicates some sort
|
of error, such as running out of space.
|
|
-- Function: size_t fwrite_unlocked (const void *DATA, size_t SIZE,
|
size_t COUNT, FILE *STREAM)
|
Preliminary: | MT-Safe race:stream | AS-Unsafe corrupt | AC-Unsafe
|
corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘fwrite_unlocked’ function is equivalent to the ‘fwrite’
|
function except that it does not implicitly lock the stream.
|
|
This function is a GNU extension.
|
|
|
File: libc.info, Node: Formatted Output, Next: Customizing Printf, Prev: Block Input/Output, Up: I/O on Streams
|
|
12.12 Formatted Output
|
======================
|
|
The functions described in this section (‘printf’ and related functions)
|
provide a convenient way to perform formatted output. You call ‘printf’
|
with a "format string" or "template string" that specifies how to format
|
the values of the remaining arguments.
|
|
Unless your program is a filter that specifically performs line- or
|
character-oriented processing, using ‘printf’ or one of the other
|
related functions described in this section is usually the easiest and
|
most concise way to perform output. These functions are especially
|
useful for printing error messages, tables of data, and the like.
|
|
* Menu:
|
|
* Formatted Output Basics:: Some examples to get you started.
|
* Output Conversion Syntax:: General syntax of conversion
|
specifications.
|
* Table of Output Conversions:: Summary of output conversions and
|
what they do.
|
* Integer Conversions:: Details about formatting of integers.
|
* Floating-Point Conversions:: Details about formatting of
|
floating-point numbers.
|
* Other Output Conversions:: Details about formatting of strings,
|
characters, pointers, and the like.
|
* Formatted Output Functions:: Descriptions of the actual functions.
|
* Dynamic Output:: Functions that allocate memory for the output.
|
* Variable Arguments Output:: ‘vprintf’ and friends.
|
* Parsing a Template String:: What kinds of args does a given template
|
call for?
|
* Example of Parsing:: Sample program using ‘parse_printf_format’.
|
|
|
File: libc.info, Node: Formatted Output Basics, Next: Output Conversion Syntax, Up: Formatted Output
|
|
12.12.1 Formatted Output Basics
|
-------------------------------
|
|
The ‘printf’ function can be used to print any number of arguments. The
|
template string argument you supply in a call provides information not
|
only about the number of additional arguments, but also about their
|
types and what style should be used for printing them.
|
|
Ordinary characters in the template string are simply written to the
|
output stream as-is, while "conversion specifications" introduced by a
|
‘%’ character in the template cause subsequent arguments to be formatted
|
and written to the output stream. For example,
|
|
int pct = 37;
|
char filename[] = "foo.txt";
|
printf ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
|
filename, pct);
|
|
produces output like
|
|
Processing of `foo.txt' is 37% finished.
|
Please be patient.
|
|
This example shows the use of the ‘%d’ conversion to specify that an
|
‘int’ argument should be printed in decimal notation, the ‘%s’
|
conversion to specify printing of a string argument, and the ‘%%’
|
conversion to print a literal ‘%’ character.
|
|
There are also conversions for printing an integer argument as an
|
unsigned value in octal, decimal, or hexadecimal radix (‘%o’, ‘%u’, or
|
‘%x’, respectively); or as a character value (‘%c’).
|
|
Floating-point numbers can be printed in normal, fixed-point notation
|
using the ‘%f’ conversion or in exponential notation using the ‘%e’
|
conversion. The ‘%g’ conversion uses either ‘%e’ or ‘%f’ format,
|
depending on what is more appropriate for the magnitude of the
|
particular number.
|
|
You can control formatting more precisely by writing "modifiers"
|
between the ‘%’ and the character that indicates which conversion to
|
apply. These slightly alter the ordinary behavior of the conversion.
|
For example, most conversion specifications permit you to specify a
|
minimum field width and a flag indicating whether you want the result
|
left- or right-justified within the field.
|
|
The specific flags and modifiers that are permitted and their
|
interpretation vary depending on the particular conversion. They’re all
|
described in more detail in the following sections. Don’t worry if this
|
all seems excessively complicated at first; you can almost always get
|
reasonable free-format output without using any of the modifiers at all.
|
The modifiers are mostly used to make the output look “prettier” in
|
tables.
|
|
|
File: libc.info, Node: Output Conversion Syntax, Next: Table of Output Conversions, Prev: Formatted Output Basics, Up: Formatted Output
|
|
12.12.2 Output Conversion Syntax
|
--------------------------------
|
|
This section provides details about the precise syntax of conversion
|
specifications that can appear in a ‘printf’ template string.
|
|
Characters in the template string that are not part of a conversion
|
specification are printed as-is to the output stream. Multibyte
|
character sequences (*note Character Set Handling::) are permitted in a
|
template string.
|
|
The conversion specifications in a ‘printf’ template string have the
|
general form:
|
|
% [ PARAM-NO $] FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION
|
|
or
|
|
% [ PARAM-NO $] FLAGS WIDTH . * [ PARAM-NO $] TYPE CONVERSION
|
|
For example, in the conversion specifier ‘%-10.8ld’, the ‘-’ is a
|
flag, ‘10’ specifies the field width, the precision is ‘8’, the letter
|
‘l’ is a type modifier, and ‘d’ specifies the conversion style. (This
|
particular type specifier says to print a ‘long int’ argument in decimal
|
notation, with a minimum of 8 digits left-justified in a field at least
|
10 characters wide.)
|
|
In more detail, output conversion specifications consist of an
|
initial ‘%’ character followed in sequence by:
|
|
• An optional specification of the parameter used for this format.
|
Normally the parameters to the ‘printf’ function are assigned to
|
the formats in the order of appearance in the format string. But
|
in some situations (such as message translation) this is not
|
desirable and this extension allows an explicit parameter to be
|
specified.
|
|
The PARAM-NO parts of the format must be integers in the range of 1
|
to the maximum number of arguments present to the function call.
|
Some implementations limit this number to a certain upper bound.
|
The exact limit can be retrieved by the following constant.
|
|
-- Macro: NL_ARGMAX
|
The value of ‘NL_ARGMAX’ is the maximum value allowed for the
|
specification of a positional parameter in a ‘printf’ call.
|
The actual value in effect at runtime can be retrieved by
|
using ‘sysconf’ using the ‘_SC_NL_ARGMAX’ parameter *note
|
Sysconf Definition::.
|
|
Some systems have a quite low limit such as 9 for System V
|
systems. The GNU C Library has no real limit.
|
|
If any of the formats has a specification for the parameter
|
position all of them in the format string shall have one.
|
Otherwise the behavior is undefined.
|
|
• Zero or more "flag characters" that modify the normal behavior of
|
the conversion specification.
|
|
• An optional decimal integer specifying the "minimum field width".
|
If the normal conversion produces fewer characters than this, the
|
field is padded with spaces to the specified width. This is a
|
_minimum_ value; if the normal conversion produces more characters
|
than this, the field is _not_ truncated. Normally, the output is
|
right-justified within the field.
|
|
You can also specify a field width of ‘*’. This means that the
|
next argument in the argument list (before the actual value to be
|
printed) is used as the field width. The value must be an ‘int’.
|
If the value is negative, this means to set the ‘-’ flag (see
|
below) and to use the absolute value as the field width.
|
|
• An optional "precision" to specify the number of digits to be
|
written for the numeric conversions. If the precision is
|
specified, it consists of a period (‘.’) followed optionally by a
|
decimal integer (which defaults to zero if omitted).
|
|
You can also specify a precision of ‘*’. This means that the next
|
argument in the argument list (before the actual value to be
|
printed) is used as the precision. The value must be an ‘int’, and
|
is ignored if it is negative. If you specify ‘*’ for both the
|
field width and precision, the field width argument precedes the
|
precision argument. Other C library versions may not recognize
|
this syntax.
|
|
• An optional "type modifier character", which is used to specify the
|
data type of the corresponding argument if it differs from the
|
default type. (For example, the integer conversions assume a type
|
of ‘int’, but you can specify ‘h’, ‘l’, or ‘L’ for other integer
|
types.)
|
|
• A character that specifies the conversion to be applied.
|
|
The exact options that are permitted and how they are interpreted
|
vary between the different conversion specifiers. See the descriptions
|
of the individual conversions for information about the particular
|
options that they use.
|
|
With the ‘-Wformat’ option, the GNU C compiler checks calls to
|
‘printf’ and related functions. It examines the format string and
|
verifies that the correct number and types of arguments are supplied.
|
There is also a GNU C syntax to tell the compiler that a function you
|
write uses a ‘printf’-style format string. *Note Declaring Attributes
|
of Functions: (gcc.info)Function Attributes, for more information.
|
|
|
File: libc.info, Node: Table of Output Conversions, Next: Integer Conversions, Prev: Output Conversion Syntax, Up: Formatted Output
|
|
12.12.3 Table of Output Conversions
|
-----------------------------------
|
|
Here is a table summarizing what all the different conversions do:
|
|
‘%d’, ‘%i’
|
Print an integer as a signed decimal number. *Note Integer
|
Conversions::, for details. ‘%d’ and ‘%i’ are synonymous for
|
output, but are different when used with ‘scanf’ for input (*note
|
Table of Input Conversions::).
|
|
‘%o’
|
Print an integer as an unsigned octal number. *Note Integer
|
Conversions::, for details.
|
|
‘%u’
|
Print an integer as an unsigned decimal number. *Note Integer
|
Conversions::, for details.
|
|
‘%x’, ‘%X’
|
Print an integer as an unsigned hexadecimal number. ‘%x’ uses
|
lower-case letters and ‘%X’ uses upper-case. *Note Integer
|
Conversions::, for details.
|
|
‘%f’
|
Print a floating-point number in normal (fixed-point) notation.
|
*Note Floating-Point Conversions::, for details.
|
|
‘%e’, ‘%E’
|
Print a floating-point number in exponential notation. ‘%e’ uses
|
lower-case letters and ‘%E’ uses upper-case. *Note Floating-Point
|
Conversions::, for details.
|
|
‘%g’, ‘%G’
|
Print a floating-point number in either normal or exponential
|
notation, whichever is more appropriate for its magnitude. ‘%g’
|
uses lower-case letters and ‘%G’ uses upper-case. *Note
|
Floating-Point Conversions::, for details.
|
|
‘%a’, ‘%A’
|
Print a floating-point number in a hexadecimal fractional notation
|
with the exponent to base 2 represented in decimal digits. ‘%a’
|
uses lower-case letters and ‘%A’ uses upper-case. *Note
|
Floating-Point Conversions::, for details.
|
|
‘%c’
|
Print a single character. *Note Other Output Conversions::.
|
|
‘%C’
|
This is an alias for ‘%lc’ which is supported for compatibility
|
with the Unix standard.
|
|
‘%s’
|
Print a string. *Note Other Output Conversions::.
|
|
‘%S’
|
This is an alias for ‘%ls’ which is supported for compatibility
|
with the Unix standard.
|
|
‘%p’
|
Print the value of a pointer. *Note Other Output Conversions::.
|
|
‘%n’
|
Get the number of characters printed so far. *Note Other Output
|
Conversions::. Note that this conversion specification never
|
produces any output.
|
|
‘%m’
|
Print the string corresponding to the value of ‘errno’. (This is a
|
GNU extension.) *Note Other Output Conversions::.
|
|
‘%%’
|
Print a literal ‘%’ character. *Note Other Output Conversions::.
|
|
If the syntax of a conversion specification is invalid, unpredictable
|
things will happen, so don’t do this. If there aren’t enough function
|
arguments provided to supply values for all the conversion
|
specifications in the template string, or if the arguments are not of
|
the correct types, the results are unpredictable. If you supply more
|
arguments than conversion specifications, the extra argument values are
|
simply ignored; this is sometimes useful.
|
|
|
File: libc.info, Node: Integer Conversions, Next: Floating-Point Conversions, Prev: Table of Output Conversions, Up: Formatted Output
|
|
12.12.4 Integer Conversions
|
---------------------------
|
|
This section describes the options for the ‘%d’, ‘%i’, ‘%o’, ‘%u’, ‘%x’,
|
and ‘%X’ conversion specifications. These conversions print integers in
|
various formats.
|
|
The ‘%d’ and ‘%i’ conversion specifications both print an ‘int’
|
argument as a signed decimal number; while ‘%o’, ‘%u’, and ‘%x’ print
|
the argument as an unsigned octal, decimal, or hexadecimal number
|
(respectively). The ‘%X’ conversion specification is just like ‘%x’
|
except that it uses the characters ‘ABCDEF’ as digits instead of
|
‘abcdef’.
|
|
The following flags are meaningful:
|
|
‘-’
|
Left-justify the result in the field (instead of the normal
|
right-justification).
|
|
‘+’
|
For the signed ‘%d’ and ‘%i’ conversions, print a plus sign if the
|
value is positive.
|
|
‘ ’
|
For the signed ‘%d’ and ‘%i’ conversions, if the result doesn’t
|
start with a plus or minus sign, prefix it with a space character
|
instead. Since the ‘+’ flag ensures that the result includes a
|
sign, this flag is ignored if you supply both of them.
|
|
‘#’
|
For the ‘%o’ conversion, this forces the leading digit to be ‘0’,
|
as if by increasing the precision. For ‘%x’ or ‘%X’, this prefixes
|
a leading ‘0x’ or ‘0X’ (respectively) to the result. This doesn’t
|
do anything useful for the ‘%d’, ‘%i’, or ‘%u’ conversions. Using
|
this flag produces output which can be parsed by the ‘strtoul’
|
function (*note Parsing of Integers::) and ‘scanf’ with the ‘%i’
|
conversion (*note Numeric Input Conversions::).
|
|
‘'’
|
Separate the digits into groups as specified by the locale
|
specified for the ‘LC_NUMERIC’ category; *note General Numeric::.
|
This flag is a GNU extension.
|
|
‘0’
|
Pad the field with zeros instead of spaces. The zeros are placed
|
after any indication of sign or base. This flag is ignored if the
|
‘-’ flag is also specified, or if a precision is specified.
|
|
If a precision is supplied, it specifies the minimum number of digits
|
to appear; leading zeros are produced if necessary. If you don’t
|
specify a precision, the number is printed with as many digits as it
|
needs. If you convert a value of zero with an explicit precision of
|
zero, then no characters at all are produced.
|
|
Without a type modifier, the corresponding argument is treated as an
|
‘int’ (for the signed conversions ‘%i’ and ‘%d’) or ‘unsigned int’ (for
|
the unsigned conversions ‘%o’, ‘%u’, ‘%x’, and ‘%X’). Recall that since
|
‘printf’ and friends are variadic, any ‘char’ and ‘short’ arguments are
|
automatically converted to ‘int’ by the default argument promotions.
|
For arguments of other integer types, you can use these modifiers:
|
|
‘hh’
|
Specifies that the argument is a ‘signed char’ or ‘unsigned char’,
|
as appropriate. A ‘char’ argument is converted to an ‘int’ or
|
‘unsigned int’ by the default argument promotions anyway, but the
|
‘hh’ modifier says to convert it back to a ‘char’ again.
|
|
This modifier was introduced in ISO C99.
|
|
‘h’
|
Specifies that the argument is a ‘short int’ or ‘unsigned short
|
int’, as appropriate. A ‘short’ argument is converted to an ‘int’
|
or ‘unsigned int’ by the default argument promotions anyway, but
|
the ‘h’ modifier says to convert it back to a ‘short’ again.
|
|
‘j’
|
Specifies that the argument is a ‘intmax_t’ or ‘uintmax_t’, as
|
appropriate.
|
|
This modifier was introduced in ISO C99.
|
|
‘l’
|
Specifies that the argument is a ‘long int’ or ‘unsigned long int’,
|
as appropriate. Two ‘l’ characters are like the ‘L’ modifier,
|
below.
|
|
If used with ‘%c’ or ‘%s’ the corresponding parameter is considered
|
as a wide character or wide character string respectively. This
|
use of ‘l’ was introduced in Amendment 1 to ISO C90.
|
|
‘L’
|
‘ll’
|
‘q’
|
Specifies that the argument is a ‘long long int’. (This type is an
|
extension supported by the GNU C compiler. On systems that don’t
|
support extra-long integers, this is the same as ‘long int’.)
|
|
The ‘q’ modifier is another name for the same thing, which comes
|
from 4.4 BSD; a ‘long long int’ is sometimes called a “quad” ‘int’.
|
|
‘t’
|
Specifies that the argument is a ‘ptrdiff_t’.
|
|
This modifier was introduced in ISO C99.
|
|
‘z’
|
‘Z’
|
Specifies that the argument is a ‘size_t’.
|
|
‘z’ was introduced in ISO C99. ‘Z’ is a GNU extension predating
|
this addition and should not be used in new code.
|
|
Here is an example. Using the template string:
|
|
"|%5d|%-5d|%+5d|%+-5d|% 5d|%05d|%5.0d|%5.2d|%d|\n"
|
|
to print numbers using the different options for the ‘%d’ conversion
|
gives results like:
|
|
| 0|0 | +0|+0 | 0|00000| | 00|0|
|
| 1|1 | +1|+1 | 1|00001| 1| 01|1|
|
| -1|-1 | -1|-1 | -1|-0001| -1| -01|-1|
|
|100000|100000|+100000|+100000| 100000|100000|100000|100000|100000|
|
|
In particular, notice what happens in the last case where the number
|
is too large to fit in the minimum field width specified.
|
|
Here are some more examples showing how unsigned integers print under
|
various format options, using the template string:
|
|
"|%5u|%5o|%5x|%5X|%#5o|%#5x|%#5X|%#10.8x|\n"
|
|
| 0| 0| 0| 0| 0| 0| 0| 00000000|
|
| 1| 1| 1| 1| 01| 0x1| 0X1|0x00000001|
|
|100000|303240|186a0|186A0|0303240|0x186a0|0X186A0|0x000186a0|
|
|
|
File: libc.info, Node: Floating-Point Conversions, Next: Other Output Conversions, Prev: Integer Conversions, Up: Formatted Output
|
|
12.12.5 Floating-Point Conversions
|
----------------------------------
|
|
This section discusses the conversion specifications for floating-point
|
numbers: the ‘%f’, ‘%e’, ‘%E’, ‘%g’, and ‘%G’ conversions.
|
|
The ‘%f’ conversion prints its argument in fixed-point notation,
|
producing output of the form [‘-’]DDD‘.’DDD, where the number of digits
|
following the decimal point is controlled by the precision you specify.
|
|
The ‘%e’ conversion prints its argument in exponential notation,
|
producing output of the form [‘-’]D‘.’DDD‘e’[‘+’|‘-’]DD. Again, the
|
number of digits following the decimal point is controlled by the
|
precision. The exponent always contains at least two digits. The ‘%E’
|
conversion is similar but the exponent is marked with the letter ‘E’
|
instead of ‘e’.
|
|
The ‘%g’ and ‘%G’ conversions print the argument in the style of ‘%e’
|
or ‘%E’ (respectively) if the exponent would be less than -4 or greater
|
than or equal to the precision; otherwise they use the ‘%f’ style. A
|
precision of ‘0’, is taken as 1. Trailing zeros are removed from the
|
fractional portion of the result and a decimal-point character appears
|
only if it is followed by a digit.
|
|
The ‘%a’ and ‘%A’ conversions are meant for representing
|
floating-point numbers exactly in textual form so that they can be
|
exchanged as texts between different programs and/or machines. The
|
numbers are represented in the form [‘-’]‘0x’H‘.’HHH‘p’[‘+’|‘-’]DD. At
|
the left of the decimal-point character exactly one digit is print.
|
This character is only ‘0’ if the number is denormalized. Otherwise the
|
value is unspecified; it is implementation dependent how many bits are
|
used. The number of hexadecimal digits on the right side of the
|
decimal-point character is equal to the precision. If the precision is
|
zero it is determined to be large enough to provide an exact
|
representation of the number (or it is large enough to distinguish two
|
adjacent values if the ‘FLT_RADIX’ is not a power of 2, *note Floating
|
Point Parameters::). For the ‘%a’ conversion lower-case characters are
|
used to represent the hexadecimal number and the prefix and exponent
|
sign are printed as ‘0x’ and ‘p’ respectively. Otherwise upper-case
|
characters are used and ‘0X’ and ‘P’ are used for the representation of
|
prefix and exponent string. The exponent to the base of two is printed
|
as a decimal number using at least one digit but at most as many digits
|
as necessary to represent the value exactly.
|
|
If the value to be printed represents infinity or a NaN, the output
|
is [‘-’]‘inf’ or ‘nan’ respectively if the conversion specifier is ‘%a’,
|
‘%e’, ‘%f’, or ‘%g’ and it is [‘-’]‘INF’ or ‘NAN’ respectively if the
|
conversion is ‘%A’, ‘%E’, or ‘%G’.
|
|
The following flags can be used to modify the behavior:
|
|
‘-’
|
Left-justify the result in the field. Normally the result is
|
right-justified.
|
|
‘+’
|
Always include a plus or minus sign in the result.
|
|
‘ ’
|
If the result doesn’t start with a plus or minus sign, prefix it
|
with a space instead. Since the ‘+’ flag ensures that the result
|
includes a sign, this flag is ignored if you supply both of them.
|
|
‘#’
|
Specifies that the result should always include a decimal point,
|
even if no digits follow it. For the ‘%g’ and ‘%G’ conversions,
|
this also forces trailing zeros after the decimal point to be left
|
in place where they would otherwise be removed.
|
|
‘'’
|
Separate the digits of the integer part of the result into groups
|
as specified by the locale specified for the ‘LC_NUMERIC’ category;
|
*note General Numeric::. This flag is a GNU extension.
|
|
‘0’
|
Pad the field with zeros instead of spaces; the zeros are placed
|
after any sign. This flag is ignored if the ‘-’ flag is also
|
specified.
|
|
The precision specifies how many digits follow the decimal-point
|
character for the ‘%f’, ‘%e’, and ‘%E’ conversions. For these
|
conversions, the default precision is ‘6’. If the precision is
|
explicitly ‘0’, this suppresses the decimal point character entirely.
|
For the ‘%g’ and ‘%G’ conversions, the precision specifies how many
|
significant digits to print. Significant digits are the first digit
|
before the decimal point, and all the digits after it. If the precision
|
is ‘0’ or not specified for ‘%g’ or ‘%G’, it is treated like a value of
|
‘1’. If the value being printed cannot be expressed accurately in the
|
specified number of digits, the value is rounded to the nearest number
|
that fits.
|
|
Without a type modifier, the floating-point conversions use an
|
argument of type ‘double’. (By the default argument promotions, any
|
‘float’ arguments are automatically converted to ‘double’.) The
|
following type modifier is supported:
|
|
‘L’
|
An uppercase ‘L’ specifies that the argument is a ‘long double’.
|
|
Here are some examples showing how numbers print using the various
|
floating-point conversions. All of the numbers were printed using this
|
template string:
|
|
"|%13.4a|%13.4f|%13.4e|%13.4g|\n"
|
|
Here is the output:
|
|
| 0x0.0000p+0| 0.0000| 0.0000e+00| 0|
|
| 0x1.0000p-1| 0.5000| 5.0000e-01| 0.5|
|
| 0x1.0000p+0| 1.0000| 1.0000e+00| 1|
|
| -0x1.0000p+0| -1.0000| -1.0000e+00| -1|
|
| 0x1.9000p+6| 100.0000| 1.0000e+02| 100|
|
| 0x1.f400p+9| 1000.0000| 1.0000e+03| 1000|
|
| 0x1.3880p+13| 10000.0000| 1.0000e+04| 1e+04|
|
| 0x1.81c8p+13| 12345.0000| 1.2345e+04| 1.234e+04|
|
| 0x1.86a0p+16| 100000.0000| 1.0000e+05| 1e+05|
|
| 0x1.e240p+16| 123456.0000| 1.2346e+05| 1.235e+05|
|
|
Notice how the ‘%g’ conversion drops trailing zeros.
|
|
|
File: libc.info, Node: Other Output Conversions, Next: Formatted Output Functions, Prev: Floating-Point Conversions, Up: Formatted Output
|
|
12.12.6 Other Output Conversions
|
--------------------------------
|
|
This section describes miscellaneous conversions for ‘printf’.
|
|
The ‘%c’ conversion prints a single character. In case there is no
|
‘l’ modifier the ‘int’ argument is first converted to an ‘unsigned
|
char’. Then, if used in a wide stream function, the character is
|
converted into the corresponding wide character. The ‘-’ flag can be
|
used to specify left-justification in the field, but no other flags are
|
defined, and no precision or type modifier can be given. For example:
|
|
printf ("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');
|
|
prints ‘hello’.
|
|
If there is an ‘l’ modifier present the argument is expected to be of
|
type ‘wint_t’. If used in a multibyte function the wide character is
|
converted into a multibyte character before being added to the output.
|
In this case more than one output byte can be produced.
|
|
The ‘%s’ conversion prints a string. If no ‘l’ modifier is present
|
the corresponding argument must be of type ‘char *’ (or ‘const char *’).
|
If used in a wide stream function the string is first converted to a
|
wide character string. A precision can be specified to indicate the
|
maximum number of characters to write; otherwise characters in the
|
string up to but not including the terminating null character are
|
written to the output stream. The ‘-’ flag can be used to specify
|
left-justification in the field, but no other flags or type modifiers
|
are defined for this conversion. For example:
|
|
printf ("%3s%-6s", "no", "where");
|
|
prints ‘ nowhere ’.
|
|
If there is an ‘l’ modifier present, the argument is expected to be
|
of type ‘wchar_t’ (or ‘const wchar_t *’).
|
|
If you accidentally pass a null pointer as the argument for a ‘%s’
|
conversion, the GNU C Library prints it as ‘(null)’. We think this is
|
more useful than crashing. But it’s not good practice to pass a null
|
argument intentionally.
|
|
The ‘%m’ conversion prints the string corresponding to the error code
|
in ‘errno’. *Note Error Messages::. Thus:
|
|
fprintf (stderr, "can't open `%s': %m\n", filename);
|
|
is equivalent to:
|
|
fprintf (stderr, "can't open `%s': %s\n", filename, strerror (errno));
|
|
The ‘%m’ conversion is a GNU C Library extension.
|
|
The ‘%p’ conversion prints a pointer value. The corresponding
|
argument must be of type ‘void *’. In practice, you can use any type of
|
pointer.
|
|
In the GNU C Library, non-null pointers are printed as unsigned
|
integers, as if a ‘%#x’ conversion were used. Null pointers print as
|
‘(nil)’. (Pointers might print differently in other systems.)
|
|
For example:
|
|
printf ("%p", "testing");
|
|
prints ‘0x’ followed by a hexadecimal number—the address of the string
|
constant ‘"testing"’. It does not print the word ‘testing’.
|
|
You can supply the ‘-’ flag with the ‘%p’ conversion to specify
|
left-justification, but no other flags, precision, or type modifiers are
|
defined.
|
|
The ‘%n’ conversion is unlike any of the other output conversions.
|
It uses an argument which must be a pointer to an ‘int’, but instead of
|
printing anything it stores the number of characters printed so far by
|
this call at that location. The ‘h’ and ‘l’ type modifiers are
|
permitted to specify that the argument is of type ‘short int *’ or ‘long
|
int *’ instead of ‘int *’, but no flags, field width, or precision are
|
permitted.
|
|
For example,
|
|
int nchar;
|
printf ("%d %s%n\n", 3, "bears", &nchar);
|
|
prints:
|
|
3 bears
|
|
and sets ‘nchar’ to ‘7’, because ‘3 bears’ is seven characters.
|
|
The ‘%%’ conversion prints a literal ‘%’ character. This conversion
|
doesn’t use an argument, and no flags, field width, precision, or type
|
modifiers are permitted.
|
|
|
File: libc.info, Node: Formatted Output Functions, Next: Dynamic Output, Prev: Other Output Conversions, Up: Formatted Output
|
|
12.12.7 Formatted Output Functions
|
----------------------------------
|
|
This section describes how to call ‘printf’ and related functions.
|
Prototypes for these functions are in the header file ‘stdio.h’.
|
Because these functions take a variable number of arguments, you _must_
|
declare prototypes for them before using them. Of course, the easiest
|
way to make sure you have all the right prototypes is to just include
|
‘stdio.h’.
|
|
-- Function: int printf (const char *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘printf’ function prints the optional arguments under the
|
control of the template string TEMPLATE to the stream ‘stdout’. It
|
returns the number of characters printed, or a negative value if
|
there was an output error.
|
|
-- Function: int wprintf (const wchar_t *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
The ‘wprintf’ function prints the optional arguments under the
|
control of the wide template string TEMPLATE to the stream
|
‘stdout’. It returns the number of wide characters printed, or a
|
negative value if there was an output error.
|
|
-- Function: int fprintf (FILE *STREAM, const char *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This function is just like ‘printf’, except that the output is
|
written to the stream STREAM instead of ‘stdout’.
|
|
-- Function: int fwprintf (FILE *STREAM, const wchar_t *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This function is just like ‘wprintf’, except that the output is
|
written to the stream STREAM instead of ‘stdout’.
|
|
-- Function: int sprintf (char *S, const char *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This is like ‘printf’, except that the output is stored in the
|
character array S instead of written to a stream. A null character
|
is written to mark the end of the string.
|
|
The ‘sprintf’ function returns the number of characters stored in
|
the array S, not including the terminating null character.
|
|
The behavior of this function is undefined if copying takes place
|
between objects that overlap—for example, if S is also given as an
|
argument to be printed under control of the ‘%s’ conversion. *Note
|
Copying Strings and Arrays::.
|
|
*Warning:* The ‘sprintf’ function can be *dangerous* because it can
|
potentially output more characters than can fit in the allocation
|
size of the string S. Remember that the field width given in a
|
conversion specification is only a _minimum_ value.
|
|
To avoid this problem, you can use ‘snprintf’ or ‘asprintf’,
|
described below.
|
|
-- Function: int swprintf (wchar_t *WS, size_t SIZE, const wchar_t
|
*TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This is like ‘wprintf’, except that the output is stored in the
|
wide character array WS instead of written to a stream. A null
|
wide character is written to mark the end of the string. The SIZE
|
argument specifies the maximum number of characters to produce.
|
The trailing null character is counted towards this limit, so you
|
should allocate at least SIZE wide characters for the string WS.
|
|
The return value is the number of characters generated for the
|
given input, excluding the trailing null. If not all output fits
|
into the provided buffer a negative value is returned. You should
|
try again with a bigger output string. _Note:_ this is different
|
from how ‘snprintf’ handles this situation.
|
|
Note that the corresponding narrow stream function takes fewer
|
parameters. ‘swprintf’ in fact corresponds to the ‘snprintf’
|
function. Since the ‘sprintf’ function can be dangerous and should
|
be avoided the ISO C committee refused to make the same mistake
|
again and decided to not define a function exactly corresponding to
|
‘sprintf’.
|
|
-- Function: int snprintf (char *S, size_t SIZE, const char *TEMPLATE,
|
…)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
The ‘snprintf’ function is similar to ‘sprintf’, except that the
|
SIZE argument specifies the maximum number of characters to
|
produce. The trailing null character is counted towards this
|
limit, so you should allocate at least SIZE characters for the
|
string S. If SIZE is zero, nothing, not even the null byte, shall
|
be written and S may be a null pointer.
|
|
The return value is the number of characters which would be
|
generated for the given input, excluding the trailing null. If
|
this value is greater than or equal to SIZE, not all characters
|
from the result have been stored in S. You should try again with a
|
bigger output string. Here is an example of doing this:
|
|
/* Construct a message describing the value of a variable
|
whose name is NAME and whose value is VALUE. */
|
char *
|
make_message (char *name, char *value)
|
{
|
/* Guess we need no more than 100 chars of space. */
|
int size = 100;
|
char *buffer = (char *) xmalloc (size);
|
int nchars;
|
if (buffer == NULL)
|
return NULL;
|
|
/* Try to print in the allocated space. */
|
nchars = snprintf (buffer, size, "value of %s is %s",
|
name, value);
|
if (nchars >= size)
|
{
|
/* Reallocate buffer now that we know
|
how much space is needed. */
|
size = nchars + 1;
|
buffer = (char *) xrealloc (buffer, size);
|
|
if (buffer != NULL)
|
/* Try again. */
|
snprintf (buffer, size, "value of %s is %s",
|
name, value);
|
}
|
/* The last call worked, return the string. */
|
return buffer;
|
}
|
|
In practice, it is often easier just to use ‘asprintf’, below.
|
|
*Attention:* In versions of the GNU C Library prior to 2.1 the
|
return value is the number of characters stored, not including the
|
terminating null; unless there was not enough space in S to store
|
the result in which case ‘-1’ is returned. This was changed in
|
order to comply with the ISO C99 standard.
|
|
|
File: libc.info, Node: Dynamic Output, Next: Variable Arguments Output, Prev: Formatted Output Functions, Up: Formatted Output
|
|
12.12.8 Dynamically Allocating Formatted Output
|
-----------------------------------------------
|
|
The functions in this section do formatted output and place the results
|
in dynamically allocated memory.
|
|
-- Function: int asprintf (char **PTR, const char *TEMPLATE, …)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This function is similar to ‘sprintf’, except that it dynamically
|
allocates a string (as with ‘malloc’; *note Unconstrained
|
Allocation::) to hold the output, instead of putting the output in
|
a buffer you allocate in advance. The PTR argument should be the
|
address of a ‘char *’ object, and a successful call to ‘asprintf’
|
stores a pointer to the newly allocated string at that location.
|
|
The return value is the number of characters allocated for the
|
buffer, or less than zero if an error occurred. Usually this means
|
that the buffer could not be allocated.
|
|
Here is how to use ‘asprintf’ to get the same result as the
|
‘snprintf’ example, but more easily:
|
|
/* Construct a message describing the value of a variable
|
whose name is NAME and whose value is VALUE. */
|
char *
|
make_message (char *name, char *value)
|
{
|
char *result;
|
if (asprintf (&result, "value of %s is %s", name, value) < 0)
|
return NULL;
|
return result;
|
}
|
|
-- Function: int obstack_printf (struct obstack *OBSTACK, const char
|
*TEMPLATE, …)
|
Preliminary: | MT-Safe race:obstack locale | AS-Unsafe corrupt heap
|
| AC-Unsafe corrupt mem | *Note POSIX Safety Concepts::.
|
|
This function is similar to ‘asprintf’, except that it uses the
|
obstack OBSTACK to allocate the space. *Note Obstacks::.
|
|
The characters are written onto the end of the current object. To
|
get at them, you must finish the object with ‘obstack_finish’
|
(*note Growing Objects::).
|
|
|
File: libc.info, Node: Variable Arguments Output, Next: Parsing a Template String, Prev: Dynamic Output, Up: Formatted Output
|
|
12.12.9 Variable Arguments Output Functions
|
-------------------------------------------
|
|
The functions ‘vprintf’ and friends are provided so that you can define
|
your own variadic ‘printf’-like functions that make use of the same
|
internals as the built-in formatted output functions.
|
|
The most natural way to define such functions would be to use a
|
language construct to say, “Call ‘printf’ and pass this template plus
|
all of my arguments after the first five.” But there is no way to do
|
this in C, and it would be hard to provide a way, since at the C
|
language level there is no way to tell how many arguments your function
|
received.
|
|
Since that method is impossible, we provide alternative functions,
|
the ‘vprintf’ series, which lets you pass a ‘va_list’ to describe “all
|
of my arguments after the first five.”
|
|
When it is sufficient to define a macro rather than a real function,
|
the GNU C compiler provides a way to do this much more easily with
|
macros. For example:
|
|
#define myprintf(a, b, c, d, e, rest...) \
|
printf (mytemplate , ## rest)
|
|
*Note (cpp)Variadic Macros::, for details. But this is limited to
|
macros, and does not apply to real functions at all.
|
|
Before calling ‘vprintf’ or the other functions listed in this
|
section, you _must_ call ‘va_start’ (*note Variadic Functions::) to
|
initialize a pointer to the variable arguments. Then you can call
|
‘va_arg’ to fetch the arguments that you want to handle yourself. This
|
advances the pointer past those arguments.
|
|
Once your ‘va_list’ pointer is pointing at the argument of your
|
choice, you are ready to call ‘vprintf’. That argument and all
|
subsequent arguments that were passed to your function are used by
|
‘vprintf’ along with the template that you specified separately.
|
|
*Portability Note:* The value of the ‘va_list’ pointer is
|
undetermined after the call to ‘vprintf’, so you must not use ‘va_arg’
|
after you call ‘vprintf’. Instead, you should call ‘va_end’ to retire
|
the pointer from service. You can call ‘va_start’ again and begin
|
fetching the arguments from the start of the variable argument list.
|
(Alternatively, you can use ‘va_copy’ to make a copy of the ‘va_list’
|
pointer before calling ‘vfprintf’.) Calling ‘vprintf’ does not destroy
|
the argument list of your function, merely the particular pointer that
|
you passed to it.
|
|
Prototypes for these functions are declared in ‘stdio.h’.
|
|
-- Function: int vprintf (const char *TEMPLATE, va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This function is similar to ‘printf’ except that, instead of taking
|
a variable number of arguments directly, it takes an argument list
|
pointer AP.
|
|
-- Function: int vwprintf (const wchar_t *TEMPLATE, va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This function is similar to ‘wprintf’ except that, instead of
|
taking a variable number of arguments directly, it takes an
|
argument list pointer AP.
|
|
-- Function: int vfprintf (FILE *STREAM, const char *TEMPLATE, va_list
|
AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This is the equivalent of ‘fprintf’ with the variable argument list
|
specified directly as for ‘vprintf’.
|
|
-- Function: int vfwprintf (FILE *STREAM, const wchar_t *TEMPLATE,
|
va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe corrupt heap | AC-Unsafe
|
mem lock corrupt | *Note POSIX Safety Concepts::.
|
|
This is the equivalent of ‘fwprintf’ with the variable argument
|
list specified directly as for ‘vwprintf’.
|
|
-- Function: int vsprintf (char *S, const char *TEMPLATE, va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This is the equivalent of ‘sprintf’ with the variable argument list
|
specified directly as for ‘vprintf’.
|
|
-- Function: int vswprintf (wchar_t *WS, size_t SIZE, const wchar_t
|
*TEMPLATE, va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This is the equivalent of ‘swprintf’ with the variable argument
|
list specified directly as for ‘vwprintf’.
|
|
-- Function: int vsnprintf (char *S, size_t SIZE, const char *TEMPLATE,
|
va_list AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
This is the equivalent of ‘snprintf’ with the variable argument
|
list specified directly as for ‘vprintf’.
|
|
-- Function: int vasprintf (char **PTR, const char *TEMPLATE, va_list
|
AP)
|
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem |
|
*Note POSIX Safety Concepts::.
|
|
The ‘vasprintf’ function is the equivalent of ‘asprintf’ with the
|
variable argument list specified directly as for ‘vprintf’.
|
|
-- Function: int obstack_vprintf (struct obstack *OBSTACK, const char
|
*TEMPLATE, va_list AP)
|
Preliminary: | MT-Safe race:obstack locale | AS-Unsafe corrupt heap
|
| AC-Unsafe corrupt mem | *Note POSIX Safety Concepts::.
|
|
The ‘obstack_vprintf’ function is the equivalent of
|
‘obstack_printf’ with the variable argument list specified directly
|
as for ‘vprintf’.
|
|
Here’s an example showing how you might use ‘vfprintf’. This is a
|
function that prints error messages to the stream ‘stderr’, along with a
|
prefix indicating the name of the program (*note Error Messages::, for a
|
description of ‘program_invocation_short_name’).
|
|
#include <stdio.h>
|
#include <stdarg.h>
|
|
void
|
eprintf (const char *template, ...)
|
{
|
va_list ap;
|
extern char *program_invocation_short_name;
|
|
fprintf (stderr, "%s: ", program_invocation_short_name);
|
va_start (ap, template);
|
vfprintf (stderr, template, ap);
|
va_end (ap);
|
}
|
|
You could call ‘eprintf’ like this:
|
|
eprintf ("file `%s' does not exist\n", filename);
|
|
In GNU C, there is a special construct you can use to let the
|
compiler know that a function uses a ‘printf’-style format string. Then
|
it can check the number and types of arguments in each call to the
|
function, and warn you when they do not match the format string. For
|
example, take this declaration of ‘eprintf’:
|
|
void eprintf (const char *template, ...)
|
__attribute__ ((format (printf, 1, 2)));
|
|
This tells the compiler that ‘eprintf’ uses a format string like
|
‘printf’ (as opposed to ‘scanf’; *note Formatted Input::); the format
|
string appears as the first argument; and the arguments to satisfy the
|
format begin with the second. *Note Declaring Attributes of Functions:
|
(gcc.info)Function Attributes, for more information.
|
|
|
File: libc.info, Node: Parsing a Template String, Next: Example of Parsing, Prev: Variable Arguments Output, Up: Formatted Output
|
|
12.12.10 Parsing a Template String
|
----------------------------------
|
|
You can use the function ‘parse_printf_format’ to obtain information
|
about the number and types of arguments that are expected by a given
|
template string. This function permits interpreters that provide
|
interfaces to ‘printf’ to avoid passing along invalid arguments from the
|
user’s program, which could cause a crash.
|
|
All the symbols described in this section are declared in the header
|
file ‘printf.h’.
|
|
-- Function: size_t parse_printf_format (const char *TEMPLATE, size_t
|
N, int *ARGTYPES)
|
Preliminary: | MT-Safe locale | AS-Safe | AC-Safe | *Note POSIX
|
Safety Concepts::.
|
|
This function returns information about the number and types of
|
arguments expected by the ‘printf’ template string TEMPLATE. The
|
information is stored in the array ARGTYPES; each element of this
|
array describes one argument. This information is encoded using
|
the various ‘PA_’ macros, listed below.
|
|
The argument N specifies the number of elements in the array
|
ARGTYPES. This is the maximum number of elements that
|
‘parse_printf_format’ will try to write.
|
|
‘parse_printf_format’ returns the total number of arguments
|
required by TEMPLATE. If this number is greater than N, then the
|
information returned describes only the first N arguments. If you
|
want information about additional arguments, allocate a bigger
|
array and call ‘parse_printf_format’ again.
|
|
The argument types are encoded as a combination of a basic type and
|
modifier flag bits.
|
|
-- Macro: int PA_FLAG_MASK
|
This macro is a bitmask for the type modifier flag bits. You can
|
write the expression ‘(argtypes[i] & PA_FLAG_MASK)’ to extract just
|
the flag bits for an argument, or ‘(argtypes[i] & ~PA_FLAG_MASK)’
|
to extract just the basic type code.
|
|
Here are symbolic constants that represent the basic types; they
|
stand for integer values.
|
|
‘PA_INT’
|
This specifies that the base type is ‘int’.
|
|
‘PA_CHAR’
|
This specifies that the base type is ‘int’, cast to ‘char’.
|
|
‘PA_STRING’
|
This specifies that the base type is ‘char *’, a null-terminated
|
string.
|
|
‘PA_POINTER’
|
This specifies that the base type is ‘void *’, an arbitrary
|
pointer.
|
|
‘PA_FLOAT’
|
This specifies that the base type is ‘float’.
|
|
‘PA_DOUBLE’
|
This specifies that the base type is ‘double’.
|
|
‘PA_LAST’
|
You can define additional base types for your own programs as
|
offsets from ‘PA_LAST’. For example, if you have data types ‘foo’
|
and ‘bar’ with their own specialized ‘printf’ conversions, you
|
could define encodings for these types as:
|
|
#define PA_FOO PA_LAST
|
#define PA_BAR (PA_LAST + 1)
|
|
Here are the flag bits that modify a basic type. They are combined
|
with the code for the basic type using inclusive-or.
|
|
‘PA_FLAG_PTR’
|
If this bit is set, it indicates that the encoded type is a pointer
|
to the base type, rather than an immediate value. For example,
|
‘PA_INT|PA_FLAG_PTR’ represents the type ‘int *’.
|
|
‘PA_FLAG_SHORT’
|
If this bit is set, it indicates that the base type is modified
|
with ‘short’. (This corresponds to the ‘h’ type modifier.)
|
|
‘PA_FLAG_LONG’
|
If this bit is set, it indicates that the base type is modified
|
with ‘long’. (This corresponds to the ‘l’ type modifier.)
|
|
‘PA_FLAG_LONG_LONG’
|
If this bit is set, it indicates that the base type is modified
|
with ‘long long’. (This corresponds to the ‘L’ type modifier.)
|
|
‘PA_FLAG_LONG_DOUBLE’
|
This is a synonym for ‘PA_FLAG_LONG_LONG’, used by convention with
|
a base type of ‘PA_DOUBLE’ to indicate a type of ‘long double’.
|
|
For an example of using these facilities, see *note Example of
|
Parsing::.
|
|
|
File: libc.info, Node: Example of Parsing, Prev: Parsing a Template String, Up: Formatted Output
|
|
12.12.11 Example of Parsing a Template String
|
---------------------------------------------
|
|
Here is an example of decoding argument types for a format string. We
|
assume this is part of an interpreter which contains arguments of type
|
‘NUMBER’, ‘CHAR’, ‘STRING’ and ‘STRUCTURE’ (and perhaps others which are
|
not valid here).
|
|
/* Test whether the NARGS specified objects
|
in the vector ARGS are valid
|
for the format string FORMAT:
|
if so, return 1.
|
If not, return 0 after printing an error message. */
|
|
int
|
validate_args (char *format, int nargs, OBJECT *args)
|
{
|
int *argtypes;
|
int nwanted;
|
|
/* Get the information about the arguments.
|
Each conversion specification must be at least two characters
|
long, so there cannot be more specifications than half the
|
length of the string. */
|
|
argtypes = (int *) alloca (strlen (format) / 2 * sizeof (int));
|
nwanted = parse_printf_format (string, nelts, argtypes);
|
|
/* Check the number of arguments. */
|
if (nwanted > nargs)
|
{
|
error ("too few arguments (at least %d required)", nwanted);
|
return 0;
|
}
|
|
/* Check the C type wanted for each argument
|
and see if the object given is suitable. */
|
for (i = 0; i < nwanted; i++)
|
{
|
int wanted;
|
|
if (argtypes[i] & PA_FLAG_PTR)
|
wanted = STRUCTURE;
|
else
|
switch (argtypes[i] & ~PA_FLAG_MASK)
|
{
|
case PA_INT:
|
case PA_FLOAT:
|
case PA_DOUBLE:
|
wanted = NUMBER;
|
break;
|
case PA_CHAR:
|
wanted = CHAR;
|
break;
|
case PA_STRING:
|
wanted = STRING;
|
break;
|
case PA_POINTER:
|
wanted = STRUCTURE;
|
break;
|
}
|
if (TYPE (args[i]) != wanted)
|
{
|
error ("type mismatch for arg number %d", i);
|
return 0;
|
}
|
}
|
return 1;
|
}
|
|
|
File: libc.info, Node: Customizing Printf, Next: Formatted Input, Prev: Formatted Output, Up: I/O on Streams
|
|
12.13 Customizing ‘printf’
|
==========================
|
|
The GNU C Library lets you define your own custom conversion specifiers
|
for ‘printf’ template strings, to teach ‘printf’ clever ways to print
|
the important data structures of your program.
|
|
The way you do this is by registering the conversion with the
|
function ‘register_printf_function’; see *note Registering New
|
Conversions::. One of the arguments you pass to this function is a
|
pointer to a handler function that produces the actual output; see *note
|
Defining the Output Handler::, for information on how to write this
|
function.
|
|
You can also install a function that just returns information about
|
the number and type of arguments expected by the conversion specifier.
|
*Note Parsing a Template String::, for information about this.
|
|
The facilities of this section are declared in the header file
|
‘printf.h’.
|
|
* Menu:
|
|
* Registering New Conversions:: Using ‘register_printf_function’
|
to register a new output conversion.
|
* Conversion Specifier Options:: The handler must be able to get
|
the options specified in the
|
template when it is called.
|
* Defining the Output Handler:: Defining the handler and arginfo
|
functions that are passed as arguments
|
to ‘register_printf_function’.
|
* Printf Extension Example:: How to define a ‘printf’
|
handler function.
|
* Predefined Printf Handlers:: Predefined ‘printf’ handlers.
|
|
*Portability Note:* The ability to extend the syntax of ‘printf’
|
template strings is a GNU extension. ISO standard C has nothing
|
similar.
|
|
|
File: libc.info, Node: Registering New Conversions, Next: Conversion Specifier Options, Up: Customizing Printf
|
|
12.13.1 Registering New Conversions
|
-----------------------------------
|
|
The function to register a new output conversion is
|
‘register_printf_function’, declared in ‘printf.h’.
|
|
-- Function: int register_printf_function (int SPEC, printf_function
|
HANDLER-FUNCTION, printf_arginfo_function ARGINFO-FUNCTION)
|
Preliminary: | MT-Unsafe const:printfext | AS-Unsafe heap lock |
|
AC-Unsafe mem lock | *Note POSIX Safety Concepts::.
|
|
This function defines the conversion specifier character SPEC.
|
Thus, if SPEC is ‘'Y'’, it defines the conversion ‘%Y’. You can
|
redefine the built-in conversions like ‘%s’, but flag characters
|
like ‘#’ and type modifiers like ‘l’ can never be used as
|
conversions; calling ‘register_printf_function’ for those
|
characters has no effect. It is advisable not to use lowercase
|
letters, since the ISO C standard warns that additional lowercase
|
letters may be standardized in future editions of the standard.
|
|
The HANDLER-FUNCTION is the function called by ‘printf’ and friends
|
when this conversion appears in a template string. *Note Defining
|
the Output Handler::, for information about how to define a
|
function to pass as this argument. If you specify a null pointer,
|
any existing handler function for SPEC is removed.
|
|
The ARGINFO-FUNCTION is the function called by
|
‘parse_printf_format’ when this conversion appears in a template
|
string. *Note Parsing a Template String::, for information about
|
this.
|
|
*Attention:* In the GNU C Library versions before 2.0 the
|
ARGINFO-FUNCTION function did not need to be installed unless the
|
user used the ‘parse_printf_format’ function. This has changed.
|
Now a call to any of the ‘printf’ functions will call this function
|
when this format specifier appears in the format string.
|
|
The return value is ‘0’ on success, and ‘-1’ on failure (which
|
occurs if SPEC is out of range).
|
|
You can redefine the standard output conversions, but this is
|
probably not a good idea because of the potential for confusion.
|
Library routines written by other people could break if you do
|
this.
|
|
|
File: libc.info, Node: Conversion Specifier Options, Next: Defining the Output Handler, Prev: Registering New Conversions, Up: Customizing Printf
|
|
12.13.2 Conversion Specifier Options
|
------------------------------------
|
|
If you define a meaning for ‘%A’, what if the template contains ‘%+23A’
|
or ‘%-#A’? To implement a sensible meaning for these, the handler when
|
called needs to be able to get the options specified in the template.
|
|
Both the HANDLER-FUNCTION and ARGINFO-FUNCTION accept an argument
|
that points to a ‘struct printf_info’, which contains information about
|
the options appearing in an instance of the conversion specifier. This
|
data type is declared in the header file ‘printf.h’.
|
|
-- Type: struct printf_info
|
This structure is used to pass information about the options
|
appearing in an instance of a conversion specifier in a ‘printf’
|
template string to the handler and arginfo functions for that
|
specifier. It contains the following members:
|
|
‘int prec’
|
This is the precision specified. The value is ‘-1’ if no
|
precision was specified. If the precision was given as ‘*’,
|
the ‘printf_info’ structure passed to the handler function
|
contains the actual value retrieved from the argument list.
|
But the structure passed to the arginfo function contains a
|
value of ‘INT_MIN’, since the actual value is not known.
|
|
‘int width’
|
This is the minimum field width specified. The value is ‘0’
|
if no width was specified. If the field width was given as
|
‘*’, the ‘printf_info’ structure passed to the handler
|
function contains the actual value retrieved from the argument
|
list. But the structure passed to the arginfo function
|
contains a value of ‘INT_MIN’, since the actual value is not
|
known.
|
|
‘wchar_t spec’
|
This is the conversion specifier character specified. It’s
|
stored in the structure so that you can register the same
|
handler function for multiple characters, but still have a way
|
to tell them apart when the handler function is called.
|
|
‘unsigned int is_long_double’
|
This is a boolean that is true if the ‘L’, ‘ll’, or ‘q’ type
|
modifier was specified. For integer conversions, this
|
indicates ‘long long int’, as opposed to ‘long double’ for
|
floating point conversions.
|
|
‘unsigned int is_char’
|
This is a boolean that is true if the ‘hh’ type modifier was
|
specified.
|
|
‘unsigned int is_short’
|
This is a boolean that is true if the ‘h’ type modifier was
|
specified.
|
|
‘unsigned int is_long’
|
This is a boolean that is true if the ‘l’ type modifier was
|
specified.
|
|
‘unsigned int alt’
|
This is a boolean that is true if the ‘#’ flag was specified.
|
|
‘unsigned int space’
|
This is a boolean that is true if the ‘ ’ flag was specified.
|
|
‘unsigned int left’
|
This is a boolean that is true if the ‘-’ flag was specified.
|
|
‘unsigned int showsign’
|
This is a boolean that is true if the ‘+’ flag was specified.
|
|
‘unsigned int group’
|
This is a boolean that is true if the ‘'’ flag was specified.
|
|
‘unsigned int extra’
|
This flag has a special meaning depending on the context. It
|
could be used freely by the user-defined handlers but when
|
called from the ‘printf’ function this variable always
|
contains the value ‘0’.
|
|
‘unsigned int wide’
|
This flag is set if the stream is wide oriented.
|
|
‘wchar_t pad’
|
This is the character to use for padding the output to the
|
minimum field width. The value is ‘'0'’ if the ‘0’ flag was
|
specified, and ‘' '’ otherwise.
|