Next: Introduction [Contents][Index]
_close_r—Reentrant version of close_execve_r—Reentrant version of execve_fork_r—Reentrant version of fork_wait_r—Reentrant version of wait_fstat_r—Reentrant version of fstat_link_r—Reentrant version of link_lseek_r—Reentrant version of lseek_open_r—Reentrant version of open_read_r—Reentrant version of read_sbrk_r—Reentrant version of sbrk_kill_r—Reentrant version of kill_getpid_r—Reentrant version of getpid_stat_r—Reentrant version of stat_times_r—Reentrant version of times_unlink_r—Reentrant version of unlink_write_r—Reentrant version of write_Exit—end program execution with no cleanup processinga64l, l64a—convert between radix-64 ASCII string and longabort—abnormal termination of a programabs—integer absolute value (magnitude)assert—macro for debugging diagnosticsatexit—request execution of functions at program exitatof, atoff—string to double or floatatoi, atol—string to integeratoll—convert a string to a long long integerbsearch—binary searchcalloc—allocate space for arraysdiv—divide two integersecvt, ecvtf, fcvt, fcvtf—double or float to stringgcvt, gcvtf—format double or float as stringecvtbuf, fcvtbuf—double or float to string__env_lock, __env_unlock—lock environ variableexit—end program executiongetenv—look up environment variableitoa—integer to stringlabs—long integer absolute valueldiv—divide two long integersllabs—compute the absolute value of an long long integer.lldiv—divide two long long integersmalloc, realloc, free—manage memorymallinfo, malloc_stats, mallopt—malloc support__malloc_lock, __malloc_unlock—lock malloc poolmblen—minimal multibyte length functionmbsrtowcs, mbsnrtowcs—convert a character string to a wide-character stringmbstowcs—minimal multibyte string to wide char convertermbtowc—minimal multibyte to wide char converteron_exit—request execution of function with argument at program exitqsort—sort an arrayrand, srand—pseudo-random numbersrandom, srandom—pseudo-random numbersrand48, drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48—pseudo-random number generators and initialization routinesrpmatch—determine whether response to question is affirmative or negativestrtod, strtof, strtold, strtod_l, strtof_l, strtold_l—string to double or floatstrtol, strtol_l—string to longstrtoll, strtoll_l—string to long longstrtoul, strtoul_l—string to unsigned longstrtoull, strtoull_l—string to unsigned long longwcsrtombs, wcsnrtombs—convert a wide-character string to a character stringwcstod, wcstof, wcstold, wcstod_l, wcstof_l, wcstold_l—wide char string to double or floatwcstol, wcstol_l—wide string to longwcstoll, wcstoll_l—wide string to long longwcstoul, wcstoul_l—wide string to unsigned longwcstoull, wcstoull_l—wide string to unsigned long longsystem—execute command stringutoa—unsigned integer to stringwcstombs—minimal wide char string to multibyte string converterwctomb—minimal wide char to multibyte converterisalnum, isalnum_l—alphanumeric character predicateisalpha, isalpha_l—alphabetic character predicateisascii, isascii_l—ASCII character predicateisblank, isblank_l—blank character predicateiscntrl, iscntrl_l—control character predicateisdigit, isdigit_l—decimal digit predicateislower, islower_l—lowercase character predicateisprint, isgraph, isprint_l, isgraph_l—printable character predicatesispunct, ispunct_l—punctuation character predicateisspace, isspace_l—whitespace character predicateisupper, isupper_l—uppercase character predicateisxdigit, isxdigit_l—hexadecimal digit predicatetoascii, toascii_l—force integers to ASCII rangetolower, tolower_l—translate characters to lowercasetoupper, toupper_l—translate characters to uppercaseiswalnum, iswalnum_l—alphanumeric wide character testiswalpha, iswalpha_l—alphabetic wide character testiswcntrl, iswcntrl_l—control wide character testiswblank, iswblank_l—blank wide character testiswdigit, iswdigit_l—decimal digit wide character testiswgraph, iswgraph_l—graphic wide character testiswlower, iswlower_l—lowercase wide character testiswprint, iswprint_l—printable wide character testiswpunct, iswpunct_l—punctuation wide character testiswspace, iswspace_l—whitespace wide character testiswupper, iswupper_l—uppercase wide character testiswxdigit, iswxdigit_l—hexadecimal digit wide character testiswctype, iswctype_l—extensible wide-character testwctype, wctype_l—get wide-character classification typetowlower, towlower_l—translate wide characters to lowercasetowupper, towupper_l—translate wide characters to uppercasetowctrans, towctrans_l—extensible wide-character translationwctrans, wctrans_l—get wide-character translation typeclearerr, clearerr_unlocked—clear file or stream error indicatordiprintf, vdiprintf—print to a file descriptor (integer only)dprintf, vdprintf—print to a file descriptorfclose—close a filefcloseall—close all filesfdopen—turn open file into a streamfeof, feof_unlocked—test for end of fileferror, ferror_unlocked—test whether read/write error has occurredfflush, fflush_unlocked—flush buffered file outputfgetc, fgetc_unlocked—get a character from a file or streamfgetpos—record position in a stream or filefgets, fgets_unlocked—get character string from a file or streamfgetwc, getwc, fgetwc_unlocked, getwc_unlocked—get a wide character from a file or streamfgetws, fgetws_unlocked—get wide character string from a file or streamfileno, fileno_unlocked—return file descriptor associated with streamfmemopen—open a stream around a fixed-length stringfopen—open a filefopencookie—open a stream with custom callbacksfpurge—discard pending file I/Ofputc, fputc_unlocked—write a character on a stream or filefputs, fputs_unlocked—write a character string in a file or streamfputwc, putwc, fputwc_unlocked, putwc_unlocked—write a wide character on a stream or filefputws, fputws_unlocked—write a wide character string in a file or streamfread, fread_unlocked—read array elements from a filefreopen—open a file using an existing file descriptorfseek, fseeko—set file position__fsetlocking—set or query locking mode on FILE streamfsetpos—restore position of a stream or fileftell, ftello—return position in a stream or filefunopen, fropen, fwopen—open a stream with custom callbacksfwide—set and determine the orientation of a FILE streamfwrite, fwrite_unlocked—write array elementsgetc—read a character (macro)getc_unlocked—non-thread-safe version of getc (macro)getchar—read a character (macro)getchar_unlocked—non-thread-safe version of getchar (macro)getdelim—read a line up to a specified line delimitergetline—read a line from a filegets—get character string (obsolete, use fgets instead)getw—read a word (int)getwchar, getwchar_unlocked—read a wide character from standard inputmktemp, mkstemp, mkostemp, mkstemps,open_memstream, open_wmemstream—open a write stream around an arbitrary-length stringperror—print an error message on standard errorputc—write a character (macro)putc_unlocked—non-thread-safe version of putc (macro)putchar—write a character (macro)putchar_unlocked—non-thread-safe version of putchar (macro)puts—write a character stringputw—write a word (int)putwchar, putwchar_unlocked—write a wide character to standard outputremove—delete a file’s namerename—rename a filerewind—reinitialize a file or streamsetbuf—specify full buffering for a file or streamsetbuffer—specify full buffering for a file or stream with sizesetlinebuf—specify line buffering for a file or streamsetvbuf—specify file or stream bufferingsiprintf, fiprintf, iprintf, sniprintf, asiprintf, asniprintf—format output (integer only)siscanf, fiscanf, iscanf—scan and format non-floating inputsprintf, fprintf, printf, snprintf, asprintf, asnprintf—format outputsscanf, fscanf, scanf—scan and format inputstdio_ext,__fbufsize,__fpending,__flbf,__freadable,__fwritable,__freading,__fwriting—access internals of FILE structureswprintf, fwprintf, wprintf—wide character format outputswscanf, fwscanf, wscanf—scan and format wide character inputtmpfile—create a temporary filetmpnam, tempnam—name for a temporary fileungetc—push data back into a streamungetwc—push wide character data back into a streamvfprintf, vprintf, vsprintf, vsnprintf, vasprintf, vasnprintf—format argument listvfscanf, vscanf, vsscanf—format argument listvfwprintf, vwprintf, vswprintf—wide character format argument listvfwscanf, vwscanf, vswscanf—scan and format argument list from wide character inputviprintf, vfiprintf, vsiprintf, vsniprintf, vasiprintf, vasniprintf—format argument list (integer only)viscanf, vfiscanf, vsiscanf—format argument listfdopen64—turn open large file into a streamfopen64—open a large filefreopen64—open a large file using an existing file descriptorftello64—return position in a stream or filefseeko64—set file position for large filefgetpos64—record position in a large stream or filefsetpos64—restore position of a large stream or filetmpfile64—create a large temporary filebcmp—compare two memory areasbcopy—copy memory regionsbzero—initialize memory to zeroindex—search for character in stringmemccpy—copy memory regions with end-token checkmemchr—find character in memorymemcmp—compare two memory areasmemcpy—copy memory regionsmemmem—find memory segmentmemmove—move possibly overlapping memorymempcpy—copy memory regions and return end pointermemrchr—reverse search for character in memorymemset—set an area of memoryrawmemchr—find character in memoryrindex—reverse search for character in stringstpcpy—copy string returning a pointer to its endstpncpy—counted copy string returning a pointer to its endstrcasecmp—case-insensitive character string comparestrcasestr—case-insensitive character string searchstrcat—concatenate stringsstrchr—search for character in stringstrchrnul—search for character in stringstrcmp—character string comparestrcoll—locale-specific character string comparestrcpy—copy stringstrcspn—count characters not in stringstrerror, strerror_l—convert error number to stringstrerror_r—convert error number to string and copy to bufferstrlen—character string lengthstrlwr—force string to lowercasestrncasecmp—case-insensitive character string comparestrncat—concatenate stringsstrncmp—character string comparestrncpy—counted copy stringstrnstr—find string segmentstrnlen—character string lengthstrpbrk—find characters in stringstrrchr—reverse search for character in stringstrsignal—convert signal number to stringstrspn—find initial matchstrstr—find string segmentstrtok, strtok_r, strsep—get next token from a stringstrupr—force string to uppercasestrverscmp—version string comparestrxfrm—transform stringswab—swap adjacent byteswcscasecmp—case-insensitive wide character string comparewcsdup—wide character string duplicatewcsncasecmp—case-insensitive wide character string comparewmemchr—find a wide character in memorywmemcmp—compare wide characters in memorywmemcpy—copy wide characters in memorywmemmove—copy wide characters in memory with overlapping areaswmempcpy—copy wide characters in memory and return end pointerwmemset—set wide characters in memorywcscat—concatenate two wide-character stringswcschr—wide-character string scanning operationwcscmp—compare two wide-character stringswcscoll—locale-specific wide-character string comparewcscpy—copy a wide-character stringwcpcpy—copy a wide-character string returning a pointer to its endwcscspn—get length of a complementary wide substringwcsftime—convert date and time to a formatted wide-character stringwcslcat—concatenate wide-character strings to specified lengthwcslcpy—copy a wide-character string to specified lengthwcslen—get wide-character string lengthwcsncat—concatenate part of two wide-character stringswcsncmp—compare part of two wide-character stringswcsncpy—copy part of a wide-character stringwcpncpy—copy part of a wide-character string returning a pointer to its endwcsnlen—get fixed-size wide-character string lengthwcspbrk—-scan wide-character string for a wide-character codewcsrchr—wide-character string scanning operationwcsspn—get length of a wide substringwcsstr—find a wide-character substringwcstok—get next token from a stringwcswidth—number of column positions of a wide-character stringwcsxfrm—locale-specific wide-character string transformationwcwidth—number of column positions of a wide-character codeasctime—format time as stringclock—cumulative processor timectime—convert time to local and format as stringdifftime—subtract two timesgmtime—convert time to UTC traditional formlocaltime—convert time to local representationmktime—convert time to arithmetic representationstrftime, strftime_l—convert date and time to a formatted stringtime—get current calendar time (as single number)__tz_lock, __tz_unlock—lock time zone global variablestzset—set timezone characteristics from TZ environment variableffs—find first bit set in a word__retarget_lock_init, __retarget_lock_init_recursive, __retarget_lock_close, __retarget_lock_close_recursive, __retarget_lock_acquire, __retarget_lock_acquire_recursive, __retarget_lock_try_acquire, __retarget_lock_try_acquire_recursive, __retarget_lock_release, __retarget_lock_release_recursive—locking routinesunctrl—get printable representation of a charactericonv, iconv_open, iconv_close—charset conversion routinesNext: System Calls, Previous: The Red Hat newlib C Library, Up: The Red Hat newlib C Library [Contents][Index]
This reference manual describes the functions provided by the Red Hat“newlib” version of the standard ANSI C library. This document is notintended as an overview or a tutorial for the C library. Each libraryfunction is listed with a synopsis of its use, a brief description,return values (including error handling), and portability issues.
Some of the library functions depend on support from the underlyingoperating system and may not be available on every platform. Forembedded systems in particular, many of these underlying operatingsystem services may not be available or may not be fully functional.The specific operating system subroutines required for a particularlibrary function are listed in the “Portability” section of thefunction description. See System Calls, for a description of therelevant operating system calls.
Next: Standard Utility Functions (stdlib.h), Previous: Introduction, Up: The Red Hat newlib C Library [Contents][Index]
The C subroutine library depends on a handful of subroutine calls foroperating system services. If you use the C library on a system thatcomplies with the POSIX.1 standard (also known as IEEE 1003.1), most ofthese subroutines are supplied with your operating system.
If some of these subroutines are not provided with your system—inthe extreme case, if you are developing software for a “bare board”system, without an OS—you will at least need to provide do-nothingstubs (or subroutines with minimal functionality) to allow yourprograms to link with the subroutines in libc.a.
Next: Reentrant covers for OS subroutines, Up: System Calls [Contents][Index]
This is the complete set of system definitions (primarily subroutines)required; the examples shown implement the minimal functionalityrequired to allow libc to link, and fail gracefully where OSservices are not available. 
Graceful failure is permitted by returning an error code. A minorcomplication arises here: the C library must be compatible withdevelopment environments that supply fully functional versions of thesesubroutines. Such environments usually return error codes in a globalerrno. However, the Red Hat newlib C library provides a macrodefinition for errno in the header file errno.h, as partof its support for reentrant routines (see Reentrancy).
The bridge between these two interpretations of errno isstraightforward: the C library routines with OS interface callscapture the errno values returned globally, and record them inthe appropriate field of the reentrancy structure (so that you can querythem using the errno macro from errno.h).
This mechanism becomes visible when you write stub routines for OSinterfaces. You must include errno.h, then disable the macro,like this:
#include <errno.h>#undef errnoextern int errno;
The examples in this chapter include this treatment of errno.
_exit ¶Exit a program without cleaning up files. If your system doesn’tprovide this, it is best to avoid linking with subroutines that requireit (exit, system).
close ¶Close a file. Minimal implementation:
int close(int file) { return -1;}environ ¶A pointer to a list of environment variables and their values. For aminimal environment, this empty list is adequate:
char *__env[1] = { 0 };char **environ = __env;execve ¶Transfer control to a new process. Minimal implementation (for a systemwithout processes):
#include <errno.h>#undef errnoextern int errno;int execve(char *name, char **argv, char **env) { errno = ENOMEM; return -1;}fork ¶Create a new process. Minimal implementation (for a system without processes):
#include <errno.h>#undef errnoextern int errno;int fork(void) { errno = EAGAIN; return -1;}fstat ¶Status of an open file. For consistency with other minimalimplementations in these examples, all files are regarded as characterspecial devices. The sys/stat.h header file required isdistributed in the include subdirectory for this C library.
#include <sys/stat.h>int fstat(int file, struct stat *st) { st->st_mode = S_IFCHR; return 0;}getpid ¶Process-ID; this is sometimes used to generate strings unlikely toconflict with other processes. Minimal implementation, for a systemwithout processes:
int getpid(void) { return 1;}isatty ¶Query whether output stream is a terminal. For consistency with theother minimal implementations, which only support output tostdout, this minimal implementation is suggested:
int isatty(int file) { return 1;}kill ¶Send a signal. Minimal implementation:
#include <errno.h>#undef errnoextern int errno;int kill(int pid, int sig) { errno = EINVAL; return -1;}link ¶Establish a new name for an existing file. Minimal implementation:
#include <errno.h>#undef errnoextern int errno;int link(char *old, char *new) { errno = EMLINK; return -1;}lseek ¶Set position in a file. Minimal implementation:
int lseek(int file, int ptr, int dir) { return 0;}open ¶Open a file. Minimal implementation:
int open(const char *name, int flags, int mode) { return -1;}read ¶Read from a file. Minimal implementation:
int read(int file, char *ptr, int len) { return 0;}sbrk ¶Increase program data space. As malloc and related functionsdepend on this, it is useful to have a working implementation. Thefollowing suffices for a standalone system; it exploits the symbol_end automatically defined by the GNU linker.
caddr_t sbrk(int incr) { extern char _end;	/* Defined by the linker */ static char *heap_end; char *prev_heap_end; if (heap_end == 0) { heap_end = &_end; } prev_heap_end = heap_end; if (heap_end + incr > stack_ptr) { write (1, "Heap and stack collision\n", 25); abort (); } heap_end += incr; return (caddr_t) prev_heap_end;}stat ¶Status of a file (by name). Minimal implementation:
int stat(char *file, struct stat *st) { st->st_mode = S_IFCHR; return 0;}times ¶Timing information for current process. Minimal implementation:
int times(struct tms *buf) { return -1;}unlink ¶Remove a file’s directory entry. Minimal implementation:
#include <errno.h>#undef errnoextern int errno;int unlink(char *name) { errno = ENOENT; return -1;}wait ¶Wait for a child process. Minimal implementation:
#include <errno.h>#undef errnoextern int errno;int wait(int *status) { errno = ECHILD; return -1;}write ¶Write to a file. libc subroutines will use thissystem routine for output to all files, includingstdout—so if you need to generate any output, for example to aserial port for debugging, you should make your minimal writecapable of doing this. The following minimal implementation is anincomplete example; it relies on a outbyte subroutine (notshown; typically, you must write this in assembler from examplesprovided by your hardware manufacturer) to actually perform the output.
int write(int file, char *ptr, int len) { int todo; for (todo = 0; todo < len; todo++) { outbyte (*ptr++); } return len;}Previous: Definitions for OS interface, Up: System Calls [Contents][Index]
Since the system subroutines are used by other library routines thatrequire reentrancy, libc.a provides cover routines (for example,the reentrant version of fork is _fork_r). These coverroutines are consistent with the other reentrant subroutines in thislibrary, and achieve reentrancy by using a reserved global data block(see Reentrancy).
_close_r—Reentrant version of close_execve_r—Reentrant version of execve_fork_r—Reentrant version of fork_wait_r—Reentrant version of wait_fstat_r—Reentrant version of fstat_link_r—Reentrant version of link_lseek_r—Reentrant version of lseek_open_r—Reentrant version of open_read_r—Reentrant version of read_sbrk_r—Reentrant version of sbrk_kill_r—Reentrant version of kill_getpid_r—Reentrant version of getpid_stat_r—Reentrant version of stat_times_r—Reentrant version of times_unlink_r—Reentrant version of unlink_write_r—Reentrant version of writeNext: _execve_r—Reentrant version of execve, Up: Reentrant covers for OS subroutines   [Contents][Index]
_close_r—Reentrant version of closeSynopsis
#include <reent.h>int _close_r(struct _reent *ptr, int fd);
Description
This is a reentrant version of close. Ittakes a pointer to the global data block, which holdserrno.
Next: _fork_r—Reentrant version of fork, Previous: _close_r—Reentrant version of close, Up: Reentrant covers for OS subroutines   [Contents][Index]
_execve_r—Reentrant version of execveSynopsis
#include <reent.h>int _execve_r(struct _reent *ptr, const char *name, char *const argv[], char *const env[]);
Description
This is a reentrant version of execve. Ittakes a pointer to the global data block, which holdserrno.
Next: _wait_r—Reentrant version of wait, Previous: _execve_r—Reentrant version of execve, Up: Reentrant covers for OS subroutines   [Contents][Index]
_fork_r—Reentrant version of forkSynopsis
#include <reent.h>int _fork_r(struct _reent *ptr);
Description
This is a reentrant version of fork. Ittakes a pointer to the global data block, which holdserrno.
Next: _fstat_r—Reentrant version of fstat, Previous: _fork_r—Reentrant version of fork, Up: Reentrant covers for OS subroutines   [Contents][Index]
_wait_r—Reentrant version of waitSynopsis
#include <reent.h>int _wait_r(struct _reent *ptr, int *status);
Description
This is a reentrant version of wait. Ittakes a pointer to the global data block, which holdserrno.
Next: _link_r—Reentrant version of link, Previous: _wait_r—Reentrant version of wait, Up: Reentrant covers for OS subroutines   [Contents][Index]
_fstat_r—Reentrant version of fstatSynopsis
#include <reent.h>int _fstat_r(struct _reent *ptr, int fd, struct stat *pstat);
Description
This is a reentrant version of fstat. Ittakes a pointer to the global data block, which holdserrno.
Next: _lseek_r—Reentrant version of lseek, Previous: _fstat_r—Reentrant version of fstat, Up: Reentrant covers for OS subroutines   [Contents][Index]
_link_r—Reentrant version of linkSynopsis
#include <reent.h>int _link_r(struct _reent *ptr, const char *old, const char *new);
Description
This is a reentrant version of link. Ittakes a pointer to the global data block, which holdserrno.
Next: _open_r—Reentrant version of open, Previous: _link_r—Reentrant version of link, Up: Reentrant covers for OS subroutines   [Contents][Index]
_lseek_r—Reentrant version of lseekSynopsis
#include <reent.h>off_t _lseek_r(struct _reent *ptr, int fd, off_t pos, int whence);
Description
This is a reentrant version of lseek. Ittakes a pointer to the global data block, which holdserrno.
Next: _read_r—Reentrant version of read, Previous: _lseek_r—Reentrant version of lseek, Up: Reentrant covers for OS subroutines   [Contents][Index]
_open_r—Reentrant version of openSynopsis
#include <reent.h>int _open_r(struct _reent *ptr, const char *file, int flags, int mode);
Description
This is a reentrant version of open. Ittakes a pointer to the global data block, which holdserrno.
Next: _sbrk_r—Reentrant version of sbrk, Previous: _open_r—Reentrant version of open, Up: Reentrant covers for OS subroutines   [Contents][Index]
_read_r—Reentrant version of readSynopsis
#include <reent.h>_ssize_t _read_r(struct _reent *ptr, int fd, void *buf, size_t cnt);
Description
This is a reentrant version of read. Ittakes a pointer to the global data block, which holdserrno.
Next: _kill_r—Reentrant version of kill, Previous: _read_r—Reentrant version of read, Up: Reentrant covers for OS subroutines   [Contents][Index]
_sbrk_r—Reentrant version of sbrkSynopsis
#include <reent.h>void *_sbrk_r(struct _reent *ptr, ptrdiff_t incr);
Description
This is a reentrant version of sbrk. Ittakes a pointer to the global data block, which holdserrno.
Next: _getpid_r—Reentrant version of getpid, Previous: _sbrk_r—Reentrant version of sbrk, Up: Reentrant covers for OS subroutines   [Contents][Index]
_kill_r—Reentrant version of killSynopsis
#include <reent.h>int _kill_r(struct _reent *ptr, int pid, int sig);
Description
This is a reentrant version of kill. Ittakes a pointer to the global data block, which holdserrno.
Next: _stat_r—Reentrant version of stat, Previous: _kill_r—Reentrant version of kill, Up: Reentrant covers for OS subroutines   [Contents][Index]
_getpid_r—Reentrant version of getpidSynopsis
#include <reent.h>int _getpid_r(struct _reent *ptr);
Description
This is a reentrant version of getpid. Ittakes a pointer to the global data block, which holdserrno.
We never need errno, of course, but for consistency westill must have the reentrant pointer argument.
Next: _times_r—Reentrant version of times, Previous: _getpid_r—Reentrant version of getpid, Up: Reentrant covers for OS subroutines   [Contents][Index]
_stat_r—Reentrant version of statSynopsis
#include <reent.h>int _stat_r(struct _reent *ptr, const char *file, struct stat *pstat);
Description
This is a reentrant version of stat. Ittakes a pointer to the global data block, which holdserrno.
Next: _unlink_r—Reentrant version of unlink, Previous: _stat_r—Reentrant version of stat, Up: Reentrant covers for OS subroutines   [Contents][Index]
_times_r—Reentrant version of timesSynopsis
#include <reent.h>#include <sys/times.h>clock_t _times_r(struct _reent *ptr, struct tms *ptms);
Description
This is a reentrant version of times. Ittakes a pointer to the global data block, which holdserrno.
Next: _write_r—Reentrant version of write, Previous: _times_r—Reentrant version of times, Up: Reentrant covers for OS subroutines   [Contents][Index]
_unlink_r—Reentrant version of unlinkSynopsis
#include <reent.h>int _unlink_r(struct _reent *ptr, const char *file);
Description
This is a reentrant version of unlink. Ittakes a pointer to the global data block, which holdserrno.
Previous: _unlink_r—Reentrant version of unlink, Up: Reentrant covers for OS subroutines   [Contents][Index]
_write_r—Reentrant version of writeSynopsis
#include <reent.h>_ssize_t _write_r(struct _reent *ptr, int fd, const void *buf, size_t cnt);
Description
This is a reentrant version of write. Ittakes a pointer to the global data block, which holdserrno.
Next: Character Type Macros and Functions (ctype.h), Previous: System Calls, Up: The Red Hat newlib C Library [Contents][Index]
This chapter groups utility functions useful in a variety of programs.The corresponding declarations are in the header file stdlib.h.
_Exit—end program execution with no cleanup processinga64l, l64a—convert between radix-64 ASCII string and longabort—abnormal termination of a programabs—integer absolute value (magnitude)assert—macro for debugging diagnosticsatexit—request execution of functions at program exitatof, atoff—string to double or floatatoi, atol—string to integeratoll—convert a string to a long long integerbsearch—binary searchcalloc—allocate space for arraysdiv—divide two integersecvt, ecvtf, fcvt, fcvtf—double or float to stringgcvt, gcvtf—format double or float as stringecvtbuf, fcvtbuf—double or float to string__env_lock, __env_unlock—lock environ variableexit—end program executiongetenv—look up environment variableitoa—integer to stringlabs—long integer absolute valueldiv—divide two long integersllabs—compute the absolute value of an long long integer.lldiv—divide two long long integersmalloc, realloc, free—manage memorymallinfo, malloc_stats, mallopt—malloc support__malloc_lock, __malloc_unlock—lock malloc poolmblen—minimal multibyte length functionmbsrtowcs, mbsnrtowcs—convert a character string to a wide-character stringmbstowcs—minimal multibyte string to wide char convertermbtowc—minimal multibyte to wide char converteron_exit—request execution of function with argument at program exitqsort—sort an arrayrand, srand—pseudo-random numbersrandom, srandom—pseudo-random numbersrand48, drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48—pseudo-random number generators and initialization routinesrpmatch—determine whether response to question is affirmative or negativestrtod, strtof, strtold, strtod_l, strtof_l, strtold_l—string to double or floatstrtol, strtol_l—string to longstrtoll, strtoll_l—string to long longstrtoul, strtoul_l—string to unsigned longstrtoull, strtoull_l—string to unsigned long longwcsrtombs, wcsnrtombs—convert a wide-character string to a character stringwcstod, wcstof, wcstold, wcstod_l, wcstof_l, wcstold_l—wide char string to double or floatwcstol, wcstol_l—wide string to longwcstoll, wcstoll_l—wide string to long longwcstoul, wcstoul_l—wide string to unsigned longwcstoull, wcstoull_l—wide string to unsigned long longsystem—execute command stringutoa—unsigned integer to stringwcstombs—minimal wide char string to multibyte string converterwctomb—minimal wide char to multibyte converterNext: a64l, l64a—convert between radix-64 ASCII string and long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
_Exit—end program execution with no cleanup processingSynopsis
#include <stdlib.h>void _Exit(int code);
Description
Use _Exit to return control from a program to the host operatingenvironment. Use the argument code to pass an exit status to theoperating environment: two particular values, EXIT_SUCCESS andEXIT_FAILURE, are defined in ‘stdlib.h’ to indicate success orfailure in a portable fashion.
_Exit differs from exit in that it does not run anyapplication-defined cleanup functions registered with atexit andit does not clean up files and streams. It is identical to _exit.
Returns_Exit does not return to its caller.
Portability_Exit is defined by the C99 standard.
Supporting OS subroutines required: _exit.
Next: abort—abnormal termination of a program, Previous: _Exit—end program execution with no cleanup processing, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
a64l, l64a—convert between radix-64 ASCII string and longSynopsis
#include <stdlib.h>long a64l(const char *input);char *l64a(long input);
Description
Conversion is performed between long and radix-64 characters. Thel64a routine transforms up to 32 bits of input value starting fromleast significant bits to the most significant bits. The input valueis split up into a maximum of 5 groups of 6 bits and possibly onegroup of 2 bits (bits 31 and 30).
Each group of 6 bits forms a value from 0–63 which is translated intoa character as follows:
When the remaining bits are zero or all bits have been translated, anull terminator is appended to the string. An input value of 0results in the empty string.
The a64l function performs the reverse translation. Eachcharacter is used to generate a 6-bit value for up to 30 bits and thena 2-bit value to complete a 32-bit result. The null terminator meansthat the remaining digits are 0. An empty input string or NULL stringresults in 0L. An invalid string results in undefined behavior. Ifthe size of a long is greater than 32 bits, the result is sign-extended.
Returnsl64a returns a null-terminated string of 0 to 6 characters.a64l returns the 32-bit translated value from the input character string.
Portabilityl64a and a64l are non-ANSI and are defined by the Single Unix Specification.
Supporting OS subroutines required: None.
Next: abs—integer absolute value (magnitude), Previous: a64l, l64a—convert between radix-64 ASCII string and long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
abort—abnormal termination of a programSynopsis
#include <stdlib.h>void abort(void);
Description
Use abort to signal that your program has detected a condition itcannot deal with. Normally, abort ends your program’s execution.
Before terminating your program, abort raises the exception SIGABRT(using ‘raise(SIGABRT)’). If you have used signal to registeran exception handler for this condition, that handler has theopportunity to retain control, thereby avoiding program termination.
In this implementation, abort does not perform any stream- orfile-related cleanup (the host environment may do so; if not, you canarrange for your program to do its own cleanup with a SIGABRTexception handler).
Returnsabort does not return to its caller.
Portability
ANSI C requires abort.
Supporting OS subroutines required: _exit and optionally, write.
Next: assert—macro for debugging diagnostics, Previous: abort—abnormal termination of a program, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
abs—integer absolute value (magnitude)Synopsis
#include <stdlib.h>int abs(int i);
Descriptionabs returnsthe absolute value of i (also called the magnitudeof i). That is, if i is negative, the result is the oppositeof i, but if i is nonnegative the result is i.
The similar function labs uses and returns long rather than int values.
Returns
The result is a nonnegative integer.
Portabilityabs is ANSI.
No supporting OS subroutines are required.
Next: atexit—request execution of functions at program exit, Previous: abs—integer absolute value (magnitude), Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
assert—macro for debugging diagnosticsSynopsis
#include <assert.h>void assert(int expression);
Description
Use this macro to embed debuggging diagnostic statements inyour programs. The argument expression should be anexpression which evaluates to true (nonzero) when your programis working as you intended.
When expression evaluates to false (zero), assertcalls abort, after first printing a message showing whatfailed and where:
Assertion failed: expression, file filename, line lineno, function: func
If the name of the current function is not known (for example,when using a C89 compiler that does not understand __func__),the function location is omitted.
The macro is defined to permit you to turn off all uses ofassert at compile time by defining NDEBUG as apreprocessor variable. If you do this, the assert macroexpands to
(void(0))
Returnsassert does not return a value.
Portability
The assert macro is required by ANSI, as is the behaviorwhen NDEBUG is defined.
Supporting OS subroutines required (only if enabled): close, fstat,getpid, isatty, kill, lseek, read, sbrk, write.
Next: atof, atoff—string to double or float, Previous: assert—macro for debugging diagnostics, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
atexit—request execution of functions at program exitSynopsis
#include <stdlib.h>int atexit (void (*function)(void));
Description
You can use atexit to enroll functions in a list of functions thatwill be called when your program terminates normally. The argument isa pointer to a user-defined function (which must not require arguments andmust not return a result).
The functions are kept in a LIFO stack; that is, the last functionenrolled by atexit will be the first to execute when your programexits.
There is no built-in limit to the number of functions you can enrollin this list; however, after every group of 32 functions is enrolled,atexit will call malloc to get space for the next part of thelist. The initial list of 32 functions is statically allocated, soyou can always count on at least that many slots available.
Returnsatexit returns 0 if it succeeds in enrolling your function,-1 if it fails (possible only if no space was available formalloc to extend the list of functions).
Portabilityatexit is required by the ANSI standard, which also specifies thatimplementations must support enrolling at least 32 functions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: atoi, atol—string to integer, Previous: atexit—request execution of functions at program exit, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
atof, atoff—string to double or floatSynopsis
#include <stdlib.h>double atof(const char *s);float atoff(const char *s);
Descriptionatof converts the initial portion of a string to a double.atoff converts the initial portion of a string to a float.
The functions parse the character string s,locating a substring which can be converted to a floating-pointvalue. The substring must match the format:
[+|-]digits[.][digits][(e|E)[+|-]digits]
The substring converted is the longest initialfragment of s that has the expected format, beginning withthe first non-whitespace character. The substringis empty if str is empty, consists entirelyof whitespace, or if the first non-whitespace character issomething other than +, -, ., or a digit.
atof(s) is implemented as strtod(s, NULL).atoff(s) is implemented as strtof(s, NULL).
Returnsatof returns the converted substring value, if any, as adouble; or 0.0, if no conversion could be performed.If the correct value is out of the range of representable values, plusor minus HUGE_VAL is returned, and ERANGE is stored inerrno.If the correct value would cause underflow, 0.0 is returnedand ERANGE is stored in errno.
atoff obeys the same rules as atof, except that itreturns a float.
Portabilityatof is ANSI C. atof, atoi, and atol are subsumed by strodand strol, but are used extensively in existing code. These functions areless reliable, but may be faster if the argument is verified to be in a validrange.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: atoll—convert a string to a long long integer, Previous: atof, atoff—string to double or float, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
atoi, atol—string to integerSynopsis
#include <stdlib.h>int atoi(const char *s);long atol(const char *s);int _atoi_r(struct _reent *ptr, const char *s);long _atol_r(struct _reent *ptr, const char *s);
Descriptionatoi converts the initial portion of a string to an int.atol converts the initial portion of a string to a long.
atoi(s) is implemented as (int)strtol(s, NULL, 10).atol(s) is implemented as strtol(s, NULL, 10).
_atoi_r and _atol_r are reentrant versions of atoi andatol respectively, passing the reentrancy struct pointer.
Returns
The functions return the converted value, if any. If no conversion wasmade, 0 is returned.
Portabilityatoi, atol are ANSI.
No supporting OS subroutines are required.
Next: bsearch—binary search, Previous: atoi, atol—string to integer, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
atoll—convert a string to a long long integerSynopsis
#include <stdlib.h>long long atoll(const char *str);long long _atoll_r(struct _reent *ptr, const char *str);
Description
The function atoll converts the initial portion of the stringpointed to by *str to a type long long. A call toatoll(str) in this implementation is equivalent tostrtoll(str, (char **)NULL, 10) including behavior on error.
The alternate function _atoll_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returns
The converted value.
Portabilityatoll is ISO 9899 (C99) and POSIX 1003.1-2001 compatable.
No supporting OS subroutines are required.
Next: calloc—allocate space for arrays, Previous: atoll—convert a string to a long long integer, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
bsearch—binary searchSynopsis
#include <stdlib.h>void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));
Descriptionbsearch searches an array beginning at base for any elementthat matches key, using binary search. nmemb is the elementcount of the array; size is the size of each element.
The array must be sorted in ascending order with respect to thecomparison function compar (which you supply as the last argument ofbsearch).
You must define the comparison function (*compar) to have twoarguments; its result must be negative if the first argument isless than the second, zero if the two arguments match, andpositive if the first argument is greater than the second (where“less than” and “greater than” refer to whatever arbitraryordering is appropriate).
Returns
Returns a pointer to an element of array that matches key. Ifmore than one matching element is available, the result may point toany of them.
Portabilitybsearch is ANSI.
No supporting OS subroutines are required.
Next: div—divide two integers, Previous: bsearch—binary search, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
calloc—allocate space for arraysSynopsis
#include <stdlib.h>void *calloc(size_t n, size_t s);void *_calloc_r(void *reent, size_t n, size_t s);
Description
Use calloc to request a block of memory sufficient to hold anarray of n elements, each of which has size s.
The memory allocated by calloc comes out of the same memory poolused by malloc, but the memory block is initialized to all zerobytes. (To avoid the overhead of initializing the space, usemalloc instead.)
The alternate function _calloc_r is reentrant.The extra argument reent is a pointer to a reentrancy structure.
Returns
If successful, a pointer to the newly allocated space.
If unsuccessful, NULL.
Portabilitycalloc is ANSI.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: ecvt, ecvtf, fcvt, fcvtf—double or float to string, Previous: calloc—allocate space for arrays, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
div—divide two integersSynopsis
#include <stdlib.h>div_t div(int n, int d);
Description
Dividen/d,returning quotient and remainder as two integers in a structure div_t.
Returns
The result is represented with the structure
 typedef struct { int quot; int rem; } div_t;where the quot field represents the quotient, and rem theremainder. For nonzero d, if ‘r = div(n,d);’ thenn equals ‘r.rem + d*r.quot’.
To divide long rather than int values, use the similarfunction ldiv.
Portabilitydiv is ANSI.
No supporting OS subroutines are required.
Next: gcvt, gcvtf—format double or float as string, Previous: div—divide two integers, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
ecvt, ecvtf, fcvt, fcvtf—double or float to stringSynopsis
#include <stdlib.h>char *ecvt(double val, int chars, int *decpt, int *sgn);char *ecvtf(float val, int chars, int *decpt, int *sgn);char *fcvt(double val, int decimals, int *decpt, int *sgn);char *fcvtf(float val, int decimals, int *decpt, int *sgn);
Descriptionecvt and fcvt produce (null-terminated) strings of digitsrepresentating the double number val.ecvtf and fcvtf produce the corresponding characterrepresentations of float numbers.
(The stdlib functions ecvtbuf and fcvtbuf are reentrantversions of ecvt and fcvt.)
The only difference between ecvt and fcvt is theinterpretation of the second argument (chars or decimals).For ecvt, the second argument chars specifies the total numberof characters to write (which is also the number of significant digitsin the formatted string, since these two functions write only digits).For fcvt, the second argument decimals specifies the number ofcharacters to write after the decimal point; all digits for the integerpart of val are always included.
Since ecvt and fcvt write only digits in the output string,they record the location of the decimal point in *decpt, andthe sign of the number in *sgn. After formatting a number,*decpt contains the number of digits to the left of thedecimal point. *sgn contains 0 if the number is positive,and 1 if it is negative.
Returns
All four functions return a pointer to the new string containing acharacter representation of val.
Portability
None of these functions are ANSI C.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: ecvtbuf, fcvtbuf—double or float to string, Previous: ecvt, ecvtf, fcvt, fcvtf—double or float to string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
gcvt, gcvtf—format double or float as stringSynopsis
#include <stdlib.h>char *gcvt(double val, int precision, char *buf);char *gcvtf(float val, int precision, char *buf);
Descriptiongcvt writes a fully formatted number as a null-terminatedstring in the buffer *buf. gcvtf produces correspondingcharacter representations of float numbers.
gcvt uses the same rules as the printf format‘%.precisiong’—only negative values are signed (with‘-’), and either exponential or ordinary decimal-fraction formatis chosen depending on the number of significant digits (specified byprecision).
Returns
The result is a pointer to the formatted representation of val(the same as the argument buf).
Portability
Neither function is ANSI C.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: __env_lock, __env_unlock—lock environ variable, Previous: gcvt, gcvtf—format double or float as string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
ecvtbuf, fcvtbuf—double or float to stringSynopsis
#include <stdio.h>char *ecvtbuf(double val, int chars, int *decpt, int *sgn, char *buf);char *fcvtbuf(double val, int decimals, int *decpt, int *sgn, char *buf);
Descriptionecvtbuf and fcvtbuf produce (null-terminated) stringsof digits representating the double number val.
The only difference between ecvtbuf and fcvtbuf is theinterpretation of the second argument (chars ordecimals). For ecvtbuf, the second argument charsspecifies the total number of characters to write (which isalso the number of significant digits in the formatted string,since these two functions write only digits). For fcvtbuf,the second argument decimals specifies the number ofcharacters to write after the decimal point; all digits forthe integer part of val are always included.
Since ecvtbuf and fcvtbuf write only digits in theoutput string, they record the location of the decimal pointin *decpt, and the sign of the number in *sgn.After formatting a number, *decpt contains the numberof digits to the left of the decimal point. *sgncontains 0 if the number is positive, and 1 if it isnegative. For both functions, you supply a pointer buf toan area of memory to hold the converted string.
Returns
Both functions return a pointer to buf, the stringcontaining a character representation of val.
Portability
Neither function is ANSI C.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: exit—end program execution, Previous: ecvtbuf, fcvtbuf—double or float to string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
__env_lock, __env_unlock—lock environ variableSynopsis
#include <envlock.h>void __env_lock (struct _reent *reent);void __env_unlock (struct _reent *reent);
Description
The setenv family of routines call these functions when they need tomodify the environ variable. The version of these routines supplied in thelibrary use the lock API defined in sys/lock.h. If multiple threads ofexecution can call setenv, or if setenv can be called reentrantly,then you need to define your own versions of these functions in order tosafely lock the memory pool during a call. If you do not, the memory poolmay become corrupted.
A call to setenv may call __env_lock recursively; that is,the sequence of calls may go __env_lock, __env_lock,__env_unlock, __env_unlock. Any implementation of theseroutines must be careful to avoid causing a thread to wait for a lockthat it already holds.
Next: getenv—look up environment variable, Previous: __env_lock, __env_unlock—lock environ variable, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
exit—end program executionSynopsis
#include <stdlib.h>void exit(int code);
Description
Use exit to return control from a program to the host operatingenvironment. Use the argument code to pass an exit status to theoperating environment: two particular values, EXIT_SUCCESS andEXIT_FAILURE, are defined in ‘stdlib.h’ to indicate success orfailure in a portable fashion.
exit does two kinds of cleanup before ending execution of yourprogram. First, it calls all application-defined cleanup functionsyou have enrolled with atexit. Second, files and streams arecleaned up: any pending output is delivered to the host system, eachopen file or stream is closed, and files created by tmpfile aredeleted.
Returnsexit does not return to its caller.
Portability
ANSI C requires exit, and specifies that EXIT_SUCCESS andEXIT_FAILURE must be defined.
Supporting OS subroutines required: _exit.
Next: itoa—integer to string, Previous: exit—end program execution, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
getenv—look up environment variableSynopsis
#include <stdlib.h>char *getenv(const char *name);
Descriptiongetenv searches the list of environment variable names and values(using the global pointer “char **environ”) for a variable whosename matches the string at name. If a variable name matches,getenv returns a pointer to the associated value.
Returns
A pointer to the (string) value of the environment variable, orNULL if there is no such environment variable.
Portabilitygetenv is ANSI, but the rules for properly forming names of environmentvariables vary from one system to another.
getenv requires a global pointer environ.
Next: labs—long integer absolute value, Previous: getenv—look up environment variable, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
itoa—integer to stringSynopsis
#include <stdlib.h>char *itoa(int value, char *str, int base);char *__itoa(int value, char *str, int base);
Descriptionitoa converts the integer value to a null-terminated stringusing the specified base, which must be between 2 and 36, inclusive.If base is 10, value is treated as signed and the string will beprefixed with ’-’ if negative. For all other bases, value is treated asunsigned. str should be an array long enough to contain the convertedvalue, which in the worst case is sizeof(int)*8+1 bytes. 
Returns
A pointer to the string, str, or NULL if base is invalid.
Portabilityitoa is non-ANSI.
No supporting OS subroutine calls are required.
Next: ldiv—divide two long integers, Previous: itoa—integer to string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
labs—long integer absolute valueSynopsis
#include <stdlib.h>long labs(long i);
Descriptionlabs returnsthe absolute value of i (also called the magnitudeof i). That is, if i is negative, the result is the oppositeof i, but if i is nonnegative the result is i.
The similar function abs uses and returns int rather thanlong values.
Returns
The result is a nonnegative long integer.
Portabilitylabs is ANSI.
No supporting OS subroutine calls are required.
Next: llabs—compute the absolute value of an long long integer., Previous: labs—long integer absolute value, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
ldiv—divide two long integersSynopsis
#include <stdlib.h>ldiv_t ldiv(long n, long d);
Description
Dividen/d,returning quotient and remainder as two long integers in a structure ldiv_t.
Returns
The result is represented with the structure
 typedef struct { long quot; long rem; } ldiv_t;where the quot field represents the quotient, and rem theremainder. For nonzero d, if ‘r = ldiv(n,d);’ thenn equals ‘r.rem + d*r.quot’.
To divide int rather than long values, use the similarfunction div.
Portabilityldiv is ANSI.
No supporting OS subroutines are required.
Next: lldiv—divide two long long integers, Previous: ldiv—divide two long integers, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
llabs—compute the absolute value of an long long integer.Synopsis
#include <stdlib.h>long long llabs(long long j);
Description
The llabs function computes the absolute value of the long long integerargument j (also called the magnitude of j).
The similar function labs uses and returns long rather thanlong long values.
Returns
A nonnegative long long integer.
Portabilityllabs is ISO 9899 (C99) compatable.
No supporting OS subroutines are required.
Next: malloc, realloc, free—manage memory, Previous: llabs—compute the absolute value of an long long integer., Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
lldiv—divide two long long integersSynopsis
#include <stdlib.h>lldiv_t lldiv(long long n, long long d);
Description
Dividen/d,returning quotient and remainder as two long long integers in a structure lldiv_t.
Returns
The result is represented with the structure
 typedef struct { long long quot; long long rem; } lldiv_t;where the quot field represents the quotient, and rem theremainder. For nonzero d, if ‘r = ldiv(n,d);’ thenn equals ‘r.rem + d*r.quot’.
To divide long rather than long long values, use the similarfunction ldiv.
Portabilitylldiv is ISO 9899 (C99) compatable.
No supporting OS subroutines are required.
Next: mallinfo, malloc_stats, mallopt—malloc support, Previous: lldiv—divide two long long integers, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
malloc, realloc, free—manage memorySynopsis
#include <stdlib.h>void *malloc(size_t nbytes);void *realloc(void *aptr, size_t nbytes);void *reallocf(void *aptr, size_t nbytes);void free(void *aptr);void *memalign(size_t align, size_t nbytes);size_t malloc_usable_size(void *aptr);void *_malloc_r(void *reent, size_t nbytes);void *_realloc_r(void *reent, void *aptr, size_t nbytes);void *_reallocf_r(void *reent, void *aptr, size_t nbytes);void _free_r(void *reent, void *aptr);void *_memalign_r(void *reent, size_t align, size_t nbytes);size_t _malloc_usable_size_r(void *reent, void *aptr);
Description
These functions manage a pool of system memory.
Use malloc to request allocation of an object with at leastnbytes bytes of storage available. If the space is available,malloc returns a pointer to a newly allocated block as its result.
If you already have a block of storage allocated by malloc, butyou no longer need all the space allocated to it, you can make itsmaller by calling realloc with both the object pointer and thenew desired size as arguments. realloc guarantees that thecontents of the smaller object match the beginning of the original object.
Similarly, if you need more space for an object, use realloc torequest the larger size; again, realloc guarantees that thebeginning of the new, larger object matches the contents of theoriginal object.
When you no longer need an object originally allocated by mallocor realloc (or the related function calloc), return it to thememory storage pool by calling free with the address of the objectas the argument. You can also use realloc for this purpose bycalling it with 0 as the nbytes argument.
The reallocf function behaves just like realloc except if thefunction is required to allocate new storage and this fails. In thiscase reallocf will free the original object passed in whereasrealloc will not.
The memalign function returns a block of size nbytes alignedto a align boundary. The align argument must be a power oftwo.
The malloc_usable_size function takes a pointer to a blockallocated by malloc. It returns the amount of space that isavailable in the block. This may or may not be more than the sizerequested from malloc, due to alignment or minimum sizeconstraints.
The alternate functions _malloc_r, _realloc_r, _reallocf_r, _free_r, _memalign_r, and _malloc_usable_size_r are reentrantversions. The extra argument reent is a pointer to a reentrancy structure.
If you have multiple threads of execution which may call any of theseroutines, or if any of these routines may be called reentrantly, thenyou must provide implementations of the __malloc_lock and__malloc_unlock functions for your system. See the documentationfor those functions.
These functions operate by calling the function _sbrk_r orsbrk, which allocates space. You may need to provide one of thesefunctions for your system. _sbrk_r is called with a positivevalue to allocate more space, and with a negative value to releasepreviously allocated space if it is no longer required.See Definitions for OS interface.
Returnsmalloc returns a pointer to the newly allocated space, ifsuccessful; otherwise it returns NULL. If your application needsto generate empty objects, you may use malloc(0) for this purpose.
realloc returns a pointer to the new block of memory, or NULLif a new block could not be allocated. NULL is also the resultwhen you use ‘realloc(aptr,0)’ (which has the same effect as‘free(aptr)’). You should always check the result ofrealloc; successful reallocation is not guaranteed even whenyou request a smaller object.
free does not return a result.
memalign returns a pointer to the newly allocated space.
malloc_usable_size returns the usable size.
Portabilitymalloc, realloc, and free are specified by the ANSI Cstandard, but other conforming implementations of malloc maybehave differently when nbytes is zero.
memalign is part of SVR4.
malloc_usable_size is not portable.
Supporting OS subroutines required: sbrk. 
Next: __malloc_lock, __malloc_unlock—lock malloc pool, Previous: malloc, realloc, free—manage memory, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
mallinfo, malloc_stats, mallopt—malloc supportSynopsis
#include <malloc.h>struct mallinfo mallinfo(void);void malloc_stats(void);int mallopt(int parameter, value);struct mallinfo _mallinfo_r(void *reent);void _malloc_stats_r(void *reent);int _mallopt_r(void *reent, int parameter, value);
Descriptionmallinfo returns a structure describing the current state ofmemory allocation. The structure is defined in malloc.h. Thefollowing fields are defined: arena is the total amount of spacein the heap; ordblks is the number of chunks which are not in use;uordblks is the total amount of space allocated by malloc;fordblks is the total amount of space not in use; keepcost isthe size of the top most memory block.
malloc_stats print some statistics about memory allocation onstandard error.
mallopt takes a parameter and a value. The parameters are definedin malloc.h, and may be one of the following: M_TRIM_THRESHOLDsets the maximum amount of unused space in the top most block beforereleasing it back to the system in free (the space is released bycalling _sbrk_r with a negative argument); M_TOP_PAD is theamount of padding to allocate whenever _sbrk_r is called toallocate more space.
The alternate functions _mallinfo_r, _malloc_stats_r, and_mallopt_r are reentrant versions. The extra argument reentis a pointer to a reentrancy structure.
Returnsmallinfo returns a mallinfo structure. The structure is definedin malloc.h.
malloc_stats does not return a result.
mallopt returns zero if the parameter could not be set, ornon-zero if it could be set.
Portabilitymallinfo and mallopt are provided by SVR4, but mallopttakes different parameters on different systems. malloc_stats isnot portable.
Next: mblen—minimal multibyte length function, Previous: mallinfo, malloc_stats, mallopt—malloc support, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
__malloc_lock, __malloc_unlock—lock malloc poolSynopsis
#include <malloc.h>void __malloc_lock (struct _reent *reent);void __malloc_unlock (struct _reent *reent);
Description
The malloc family of routines call these functions when they need to lockthe memory pool. The version of these routines supplied in the library usethe lock API defined in sys/lock.h. If multiple threads of execution cancall malloc, or if malloc can be called reentrantly, then you need todefine your own versions of these functions in order to safely lock thememory pool during a call. If you do not, the memory pool may becomecorrupted.
A call to malloc may call __malloc_lock recursively; that is,the sequence of calls may go __malloc_lock, __malloc_lock,__malloc_unlock, __malloc_unlock. Any implementation of theseroutines must be careful to avoid causing a thread to wait for a lockthat it already holds.
Next: mbsrtowcs, mbsnrtowcs—convert a character string to a wide-character string, Previous: __malloc_lock, __malloc_unlock—lock malloc pool, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
mblen—minimal multibyte length functionSynopsis
#include <stdlib.h>int mblen(const char *s, size_t n);
Description
When _MB_CAPABLE is not defined, this is a minimal ANSI-conformingimplementation of mblen. In this case, theonly “multi-byte character sequences” recognized are single bytes,and thus 1 is returned unless s is the null pointer orhas a length of 0 or is the empty string.
When _MB_CAPABLE is defined, this routine calls _mbtowc_r to performthe conversion, passing a state variable to allow state dependentdecoding. The result is based on the locale setting which maybe restricted to a defined set of locales.
Returns
This implementation of mblen returns 0 ifs is NULL or the empty string; it returns 1 if not _MB_CAPABLE orthe character is a single-byte character; it returns -1if the multi-byte character is invalid; otherwise it returnsthe number of bytes in the multibyte character.
Portabilitymblen is required in the ANSI C standard. However, the preciseeffects vary with the locale.
mblen requires no supporting OS subroutines.
Next: mbstowcs—minimal multibyte string to wide char converter, Previous: mblen—minimal multibyte length function, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
mbsrtowcs, mbsnrtowcs—convert a character string to a wide-character stringSynopsis
#include <wchar.h>size_t mbsrtowcs(wchar_t *__restrict dst, const char **__restrict src, size_t len, mbstate_t *__restrict ps);#include <wchar.h>size_t _mbsrtowcs_r(struct _reent *ptr, wchar_t *dst, const char **src, size_t len, mbstate_t *ps);#include <wchar.h>size_t mbsnrtowcs(wchar_t *__ restrict dst, const char **__restrict src, size_t nms, size_t len, mbstate_t *__restrict ps);#include <wchar.h>size_t _mbsnrtowcs_r(struct _reent *ptr, wchar_t *dst, const char **src, size_t nms, size_t len, mbstate_t *ps);
Description
The mbsrtowcs function converts a sequence of multibyte characterspointed to indirectly by src into a sequence of corresponding widecharacters and stores at most len of them in the wchar_t array pointedto by dst, until it encounters a terminating null character (’\0’).
If dst is NULL, no characters are stored.
If dst is not NULL, the pointer pointed to by src is updated to pointto the character after the one that conversion stopped at. If conversionstops because a null character is encountered, *src is set to NULL.
The mbstate_t argument, ps, is used to keep track of the shift state. Ifit is NULL, mbsrtowcs uses an internal, static mbstate_t object, whichis initialized to the initial conversion state at program startup.
The mbsnrtowcs function behaves identically to mbsrtowcs, except thatconversion stops after reading at most nms bytes from the buffer pointedto by src.
Returns
The mbsrtowcs and mbsnrtowcs functions return the number of widecharacters stored in the array pointed to by dst if successful, otherwiseit returns (size_t)-1.
Portabilitymbsrtowcs is defined by the C99 standard.mbsnrtowcs is defined by the POSIX.1-2008 standard.
Next: mbtowc—minimal multibyte to wide char converter, Previous: mbsrtowcs, mbsnrtowcs—convert a character string to a wide-character string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
mbstowcs—minimal multibyte string to wide char converterSynopsis
#include <stdlib.h>int mbstowcs(wchar_t *restrict pwc, const char *restrict s, size_t n);
Description
When _MB_CAPABLE is not defined, this is a minimal ANSI-conformingimplementation of mbstowcs. In this case, theonly “multi-byte character sequences” recognized are single bytes,and they are “converted” to wide-char versions simply by byteextension.
When _MB_CAPABLE is defined, this routine calls _mbstowcs_r to performthe conversion, passing a state variable to allow state dependentdecoding. The result is based on the locale setting which maybe restricted to a defined set of locales.
Returns
This implementation of mbstowcs returns 0 ifs is NULL or is the empty string;it returns -1 if _MB_CAPABLE and one of themulti-byte characters is invalid or incomplete;otherwise it returns the minimum of: n or thenumber of multi-byte characters in s plus 1 (tocompensate for the nul character).If the return value is -1, the state of the pwc string isindeterminate. If the input has a length of 0, the outputstring will be modified to contain a wchar_t nul terminator.
Portabilitymbstowcs is required in the ANSI C standard. However, the preciseeffects vary with the locale.
mbstowcs requires no supporting OS subroutines.
Next: on_exit—request execution of function with argument at program exit, Previous: mbstowcs—minimal multibyte string to wide char converter, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
mbtowc—minimal multibyte to wide char converterSynopsis
#include <stdlib.h>int mbtowc(wchar_t *restrict pwc, const char *restrict s, size_t n);
Description
When _MB_CAPABLE is not defined, this is a minimal ANSI-conformingimplementation of mbtowc. In this case,only “multi-byte character sequences” recognized are single bytes,and they are “converted” to themselves.Each call to mbtowc copies one character from *s to*pwc, unless s is a null pointer. The argument nis ignored.
When _MB_CAPABLE is defined, this routine calls _mbtowc_r to performthe conversion, passing a state variable to allow state dependentdecoding. The result is based on the locale setting which maybe restricted to a defined set of locales.
Returns
This implementation of mbtowc returns 0 ifs is NULL or is the empty string;it returns 1 if not _MB_CAPABLE orthe character is a single-byte character; it returns -1if n is 0 or the multi-byte character is invalid;otherwise it returns the number of bytes in the multibyte character.If the return value is -1, no changes are made to the pwcoutput string. If the input is the empty string, a wchar_t nulis placed in the output string and 0 is returned. If the inputhas a length of 0, no changes are made to the pwc output string.
Portabilitymbtowc is required in the ANSI C standard. However, the preciseeffects vary with the locale.
mbtowc requires no supporting OS subroutines.
Next: qsort—sort an array, Previous: mbtowc—minimal multibyte to wide char converter, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
on_exit—request execution of function with argument at program exitSynopsis
#include <stdlib.h>int on_exit (void (*function)(int, void *), void *arg);
Description
You can use on_exit to enroll functions in a list of functions thatwill be called when your program terminates normally. The argument isa pointer to a user-defined function which takes two arguments. Thefirst is the status code passed to exit and the second argument is of typepointer to void. The function must not return a result. The valueof arg is registered and passed as the argument to function.
The functions are kept in a LIFO stack; that is, the last functionenrolled by atexit or on_exit will be the first to execute whenyour program exits. You can intermix functions using atexit andon_exit.
There is no built-in limit to the number of functions you can enrollin this list; however, after every group of 32 functions is enrolled,atexit/on_exit will call malloc to get space for the next partof the list. The initial list of 32 functions is statically allocated, soyou can always count on at least that many slots available.
Returnson_exit returns 0 if it succeeds in enrolling your function,-1 if it fails (possible only if no space was available formalloc to extend the list of functions).
Portabilityon_exit is a non-standard glibc extension
Supporting OS subroutines required: None
Next: rand, srand—pseudo-random numbers, Previous: on_exit—request execution of function with argument at program exit, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
qsort—sort an arraySynopsis
#include <stdlib.h>void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *) );
Descriptionqsort sorts an array (beginning at base) of nmemb objects.size describes the size of each element of the array.
You must supply a pointer to a comparison function, using the argumentshown as compar. (This permits sorting objects of unknownproperties.) Define the comparison function to accept two arguments,each a pointer to an element of the array starting at base. Theresult of (*compar) must be negative if the first argument isless than the second, zero if the two arguments match, and positive ifthe first argument is greater than the second (where “less than” and“greater than” refer to whatever arbitrary ordering is appropriate).
The array is sorted in place; that is, when qsort returns, thearray elements beginning at base have been reordered.
Returnsqsort does not return a result.
Portabilityqsort is required by ANSI (without specifying the sorting algorithm).
Next: random, srandom—pseudo-random numbers, Previous: qsort—sort an array, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
rand, srand—pseudo-random numbersSynopsis
#include <stdlib.h>int rand(void);void srand(unsigned int seed);int rand_r(unsigned int *seed);
Descriptionrand returns a different integer each time it is called; eachinteger is chosen by an algorithm designed to be unpredictable, sothat you can use rand when you require a random number.The algorithm depends on a static variable called the “random seed”;starting with a given value of the random seed always produces thesame sequence of numbers in successive calls to rand.
You can set the random seed using srand; it does nothing beyondstoring its argument in the static variable used by rand. You canexploit this to make the pseudo-random sequence less predictable, ifyou wish, by using some other unpredictable value (often the leastsignificant parts of a time-varying value) as the random seed beforebeginning a sequence of calls to rand; or, if you wish to ensure(for example, while debugging) that successive runs of your programuse the same “random” numbers, you can use srand to set the samerandom seed at the outset.
Returnsrand returns the next pseudo-random integer in sequence; it is anumber between 0 and RAND_MAX (inclusive).
srand does not return a result.
Notesrand and srand are unsafe for multi-threaded applications.rand_r is thread-safe and should be used instead.
Portabilityrand is required by ANSI, but the algorithm for pseudo-randomnumber generation is not specified; therefore, even if you usethe same random seed, you cannot expect the same sequence of resultson two different systems.
rand requires no supporting OS subroutines.
Next: rand48, drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48—pseudo-random number generators and initialization routines, Previous: rand, srand—pseudo-random numbers, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
random, srandom—pseudo-random numbersSynopsis
#define _XOPEN_SOURCE 500#include <stdlib.h>long int random(void);void srandom(unsigned int seed);
Descriptionrandom returns a different integer each time it is called; eachinteger is chosen by an algorithm designed to be unpredictable, sothat you can use random when you require a random number.The algorithm depends on a static variable called the “random seed”;starting with a given value of the random seed always produces thesame sequence of numbers in successive calls to random.
You can set the random seed using srandom; it does nothing beyondstoring its argument in the static variable used by rand. You canexploit this to make the pseudo-random sequence less predictable, ifyou wish, by using some other unpredictable value (often the leastsignificant parts of a time-varying value) as the random seed beforebeginning a sequence of calls to rand; or, if you wish to ensure(for example, while debugging) that successive runs of your programuse the same “random” numbers, you can use srandom to set the samerandom seed at the outset.
Returnsrandom returns the next pseudo-random integer in sequence; it is anumber between 0 and RAND_MAX (inclusive).
srandom does not return a result.
Notesrandom and srandom are unsafe for multi-threaded applications.
_XOPEN_SOURCE may be any value >= 500.
Portabilityrandom is required by XSI. This implementation uses the samealgorithm as rand.
random requires no supporting OS subroutines.
Next: rpmatch—determine whether response to question is affirmative or negative, Previous: random, srandom—pseudo-random numbers, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
rand48, drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48—pseudo-random number generators and initialization routinesSynopsis
#include <stdlib.h>double drand48(void);double erand48(unsigned short xseed[3]);long lrand48(void);long nrand48(unsigned short xseed[3]);long mrand48(void);long jrand48(unsigned short xseed[3]);void srand48(long seed);unsigned short *seed48(unsigned short xseed[3]);void lcong48(unsigned short p[7]);
Description
The rand48 family of functions generates pseudo-random numbersusing a linear congruential algorithm working on integers 48 bits in size.The particular formula employed isr(n+1) = (a * r(n) + c) mod mwhere the default values arefor the multiplicand a = 0xfdeece66d = 25214903917 andthe addend c = 0xb = 11. The modulo is always fixed at m = 2 ** 48.r(n) is called the seed of the random number generator.
For all the six generator routines described next, the firstcomputational step is to perform a single iteration of the algorithm.
drand48 and erand48return values of type double. The full 48 bits of r(n+1) areloaded into the mantissa of the returned value, with the exponent setsuch that the values produced lie in the interval [0.0, 1.0].
lrand48 and nrand48return values of type long in the range[0, 2**31-1]. The high-order (31) bits ofr(n+1) are loaded into the lower bits of the returned value, withthe topmost (sign) bit set to zero.
mrand48 and jrand48return values of type long in the range[-2**31, 2**31-1]. The high-order (32) bits ofr(n+1) are loaded into the returned value.
drand48, lrand48, and mrand48use an internal buffer to store r(n). For these functionsthe initial value of r(0) = 0x1234abcd330e = 20017429951246.
On the other hand, erand48, nrand48, and jrand48use a user-supplied buffer to store the seed r(n),which consists of an array of 3 shorts, where the zeroth memberholds the least significant bits.
All functions share the same multiplicand and addend.
srand48 is used to initialize the internal buffer r(n) ofdrand48, lrand48, and mrand48such that the 32 bits of the seed value are copied into the upper 32 bitsof r(n), with the lower 16 bits of r(n) arbitrarily being set to 0x330e.Additionally, the constant multiplicand and addend of the algorithm arereset to the default values given above.
seed48 also initializes the internal buffer r(n) ofdrand48, lrand48, and mrand48,but here all 48 bits of the seed can be specified in an array of 3 shorts,where the zeroth member specifies the lowest bits. Again,the constant multiplicand and addend of the algorithm arereset to the default values given above.seed48 returns a pointer to an array of 3 shorts which containsthe old seed.This array is statically allocated, thus its contents are lost aftereach new call to seed48.
Finally, lcong48 allows full control over the multiplicand andaddend used in drand48, erand48, lrand48, nrand48,mrand48, and jrand48,and the seed used in drand48, lrand48, and mrand48.An array of 7 shorts is passed as parameter; the first three shorts areused to initialize the seed; the second three are used to initialize themultiplicand; and the last short is used to initialize the addend.It is thus not possible to use values greater than 0xffff as the addend.
Note that all three methods of seeding the random number generatoralways also set the multiplicand and addend for any of the sixgenerator calls.
For a more powerful random number generator, see random.
Portability
SUS requires these functions.
No supporting OS subroutines are required.
Next: strtod, strtof, strtold, strtod_l, strtof_l, strtold_l—string to double or float, Previous: rand48, drand48, erand48, lrand48, nrand48, mrand48, jrand48, srand48, seed48, lcong48—pseudo-random number generators and initialization routines, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
rpmatch—determine whether response to question is affirmative or negativeSynopsis
#include <stdlib.h>int rpmatch(const char *response);
Description
The rpmatch function determines whether response is an affirmativeor negative response to a question according to the current locale.
Returnsrpmatch returns 1 if response is affirmative, 0 if negative, or -1if not recognized as either.
Portabilityrpmatch is a BSD extension also found in glibc.
Notes
No supporting OS subroutines are required.
Next: strtol, strtol_l—string to long, Previous: rpmatch—determine whether response to question is affirmative or negative, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
strtod, strtof, strtold, strtod_l, strtof_l, strtold_l—string to double or floatSynopsis
#include <stdlib.h>double strtod(const char *restrict str, char **restrict tail);float strtof(const char *restrict str, char **restrict tail);long double strtold(const char *restrict str, char **restrict tail);#include <stdlib.h>double strtod_l(const char *restrict str, char **restrict tail, locale_t locale);float strtof_l(const char *restrict str, char **restrict tail, locale_t locale);long double strtold_l(const char *restrict str, char **restrict tail, locale_t locale);double _strtod_r(void *reent, const char *restrict str, char **restrict tail);
Descriptionstrtod, strtof, strtold parse the character stringstr, producing a substring which can be converted to a double,float, or long double value, respectively. The substring convertedis the longest initial subsequence of str, beginning with thefirst non-whitespace character, that has one of these formats:
[+|-]digits[.[digits]][(e|E)[+|-]digits][+|-].digits[(e|E)[+|-]digits][+|-](i|I)(n|N)(f|F)[(i|I)(n|N)(i|I)(t|T)(y|Y)][+|-](n|N)(a|A)(n|N)[<(>[hexdigits]<)>][+|-]0(x|X)hexdigits[.[hexdigits]][(p|P)[+|-]digits][+|-]0(x|X).hexdigits[(p|P)[+|-]digits]
The substring contains no characters if str is empty, consistsentirely of whitespace, or if the first non-whitespacecharacter is something other than +, -, ., or adigit, and cannot be parsed as infinity or NaN. If the platformdoes not support NaN, then NaN is treated as an empty substring.If the substring is empty, no conversion is done, andthe value of str is stored in *tail. Otherwise,the substring is converted, and a pointer to the final string(which will contain at least the terminating null character ofstr) is stored in *tail. If you want noassignment to *tail, pass a null pointer as tail.
This implementation returns the nearest machine number to theinput decimal string. Ties are broken by using the IEEEround-even rule. However, strtof is currently subject todouble rounding errors.
strtod_l, strtof_l, strtold_l are like strtod,strtof, strtold but perform the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour isundefined.
The alternate function _strtod_r is a reentrant version.The extra argument reent is a pointer to a reentrancy structure.
Returns
These functions return the converted substring value, if any. Ifno conversion could be performed, 0 is returned. If the correctvalue is out of the range of representable values, plus or minusHUGE_VAL (HUGE_VALF, HUGE_VALL) is returned, andERANGE is stored in errno. If the correct value would causeunderflow, 0 is returned and ERANGE is stored in errno.
Portabilitystrtod is ANSI.strtof, strtold are C99.strtod_l, strtof_l, strtold_l are GNU extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: strtoll, strtoll_l—string to long long, Previous: strtod, strtof, strtold, strtod_l, strtof_l, strtold_l—string to double or float, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
strtol, strtol_l—string to longSynopsis
#include <stdlib.h>long strtol(const char *restrict s, char **restrict ptr, int base);#include <stdlib.h>long strtol_l(const char *restrict s, char **restrict ptr, int base, locale_t locale);long _strtol_r(void *reent, const char *restrict s, char **restrict ptr,int base);
Description
The function strtol converts the string *s toa long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof characters resembling an integer in the radix specified by base;and a trailing portion consisting of zero or more unparseable characters,and always including the terminating null character. Then, it attemptsto convert the subject string into a long and returns theresult.
If the value of base is 0, the subject string is expected to looklike a normal C integer constant: an optional sign, a possible ‘0x’indicating a hexadecimal base, and a number. If base is between2 and 36, the expected form of the subject is a sequence of lettersand digits representing an integer in the radix specified by base,with an optional plus or minus sign. The letters a–z (or,equivalently, A–Z) are used to signify values from 10 to 35;only letters whose ascribed values are less than base arepermitted. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible letter or digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,strtol attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. If the subject string begins witha minus sign, the value is negated. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (or not in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
strtol_l is like strtol but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
The alternate function _strtol_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsstrtol, strtol_l return the converted value, if any. If noconversion was made, 0 is returned.
strtol, strtol_l return LONG_MAX or LONG_MIN if themagnitude of the converted value is too large, and sets errnoto ERANGE.
Portabilitystrtol is ANSI.strtol_l is a GNU extension.
No supporting OS subroutines are required.
Next: strtoul, strtoul_l—string to unsigned long, Previous: strtol, strtol_l—string to long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
strtoll, strtoll_l—string to long longSynopsis
#include <stdlib.h>long long strtoll(const char *restrict s, char **restrict ptr, int base);#include <stdlib.h>long long strtoll_l(const char *restrict s, char **restrict ptr, int base, locale_t locale);long long _strtoll_r(void *reent, const char *restrict s, char **restrict ptr, int base);
Description
The function strtoll converts the string *s toa long long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof characters resembling an integer in the radix specified by base;and a trailing portion consisting of zero or more unparseable characters,and always including the terminating null character. Then, it attemptsto convert the subject string into a long long and returns theresult.
If the value of base is 0, the subject string is expected to looklike a normal C integer constant: an optional sign, a possible ‘0x’indicating a hexadecimal base, and a number. If base is between2 and 36, the expected form of the subject is a sequence of lettersand digits representing an integer in the radix specified by base,with an optional plus or minus sign. The letters a–z (or,equivalently, A–Z) are used to signify values from 10 to 35;only letters whose ascribed values are less than base arepermitted. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible letter or digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,strtoll attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. If the subject string begins witha minus sign, the value is negated. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (or not in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
strtoll_l is like strtoll but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
The alternate function _strtoll_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsstrtoll, strtoll_l return the converted value, if any. If noconversion was made, 0 is returned.
strtoll, strtoll_l return LONG_LONG_MAX or LONG_LONG_MINif the magnitude of the converted value is too large, and sets errnoto ERANGE.
Portabilitystrtoll is ANSI.strtoll_l is a GNU extension.
No supporting OS subroutines are required.
Next: strtoull, strtoull_l—string to unsigned long long, Previous: strtoll, strtoll_l—string to long long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
strtoul, strtoul_l—string to unsigned longSynopsis
#include <stdlib.h>unsigned long strtoul(const char *restrict s, char **restrict ptr, int base);#include <stdlib.h>unsigned long strtoul_l(const char *restrict s, char **restrict ptr, int base, locale_t locale);unsigned long _strtoul_r(void *reent, const char *restrict s, char **restrict ptr, int base);
Description
The function strtoul converts the string *s toan unsigned long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof the digits meaningful in the radix specified by base(for example, 0 through 7 if the value of base is 8);and a trailing portion consisting of one or more unparseable characters,which always includes the terminating null character. Then, it attemptsto convert the subject string into an unsigned long integer, and returns theresult.
If the value of base is zero, the subject string is expected to looklike a normal C integer constant (save that no optional sign is permitted):a possible 0x indicating hexadecimal radix, and a number.If base is between 2 and 36, the expected form of the subject is asequence of digits (which may include letters, depending on thebase) representing an integer in the radix specified by base.The letters a–z (or A–Z) are used as digits valued from10 to 35. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,strtoul attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (that is, if *s does not startwith a substring in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
strtoul_l is like strtoul but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
The alternate function _strtoul_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsstrtoul, strtoul_l return the converted value, if any. If noconversion was made, 0 is returned.
strtoul, strtoul_l return ULONG_MAX if the magnitude of theconverted value is too large, and sets errno to ERANGE.
Portabilitystrtoul is ANSI.strtoul_l is a GNU extension.
strtoul requires no supporting OS subroutines.
Next: wcsrtombs, wcsnrtombs—convert a wide-character string to a character string, Previous: strtoul, strtoul_l—string to unsigned long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
strtoull, strtoull_l—string to unsigned long longSynopsis
#include <stdlib.h>unsigned long long strtoull(const char *restrict s, char **restrict ptr, int base);#include <stdlib.h>unsigned long long strtoull_l(const char *restrict s, char **restrict ptr, int base, locale_t locale);unsigned long long _strtoull_r(void *reent, const char *restrict s, char **restrict ptr, int base);
Description
The function strtoull converts the string *s toan unsigned long long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof the digits meaningful in the radix specified by base(for example, 0 through 7 if the value of base is 8);and a trailing portion consisting of one or more unparseable characters,which always includes the terminating null character. Then, it attemptsto convert the subject string into an unsigned long long integer, and returns theresult.
If the value of base is zero, the subject string is expected to looklike a normal C integer constant (save that no optional sign is permitted):a possible 0x indicating hexadecimal radix, and a number.If base is between 2 and 36, the expected form of the subject is asequence of digits (which may include letters, depending on thebase) representing an integer in the radix specified by base.The letters a–z (or A–Z) are used as digits valued from10 to 35. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,strtoull attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (that is, if *s does not startwith a substring in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
strtoull_l is like strtoull but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
The alternate function _strtoull_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsstrtoull, strtoull_l return the converted value, if any. If noconversion was made, 0 is returned.
strtoull, strtoull_l return ULONG_LONG_MAX if the magnitudeof the converted value is too large, and sets errno to ERANGE.
Portabilitystrtoull is ANSI.strtoull_l is a GNU extension.
strtoull requires no supporting OS subroutines.
Next: wcstod, wcstof, wcstold, wcstod_l, wcstof_l, wcstold_l—wide char string to double or float, Previous: strtoull, strtoull_l—string to unsigned long long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcsrtombs, wcsnrtombs—convert a wide-character string to a character stringSynopsis
#include <wchar.h>size_t wcsrtombs(char *__restrict dst, const wchar_t **__restrict src, size_t len, mbstate_t *__restrict ps);#include <wchar.h>size_t _wcsrtombs_r(struct _reent *ptr, char *dst, const wchar_t **src, size_t len, mbstate_t *ps);#include <wchar.h>size_t wcsnrtombs(char *__restrict dst, const wchar_t **__restrict src, size_t nwc, size_t len, mbstate_t *__restrict ps);#include <wchar.h>size_t _wcsnrtombs_r(struct _reent *ptr, char *dst, const wchar_t **src, size_t nwc, size_t len, mbstate_t *ps);
Description
The wcsrtombs function converts a string of wide characters indirectlypointed to by src to a corresponding multibyte character string stored inthe array pointed to by dst. No more than len bytes are written todst.
If dst is NULL, no characters are stored.
If dst is not NULL, the pointer pointed to by src is updated to pointto the character after the one that conversion stopped at. If conversionstops because a null character is encountered, *src is set to NULL.
The mbstate_t argument, ps, is used to keep track of the shift state. Ifit is NULL, wcsrtombs uses an internal, static mbstate_t object, whichis initialized to the initial conversion state at program startup.
The wcsnrtombs function behaves identically to wcsrtombs, except thatconversion stops after reading at most nwc characters from the bufferpointed to by src.
Returns
The wcsrtombs and wcsnrtombs functions return the number of bytesstored in the array pointed to by dst (not including any terminatingnull), if successful, otherwise it returns (size_t)-1.
Portabilitywcsrtombs is defined by C99 standard.wcsnrtombs is defined by the POSIX.1-2008 standard.
Next: wcstol, wcstol_l—wide string to long, Previous: wcsrtombs, wcsnrtombs—convert a wide-character string to a character string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstod, wcstof, wcstold, wcstod_l, wcstof_l, wcstold_l—wide char string to double or floatSynopsis
#include <stdlib.h>double wcstod(const wchar_t *__restrict str, wchar_t **__restrict tail);float wcstof(const wchar_t *__restrict str, wchar_t **__restrict tail);long double wcstold(const wchar_t *__restrict str, wchar_t **__restrict tail);#include <stdlib.h>double wcstod_l(const wchar_t *__restrict str, wchar_t **__restrict tail, locale_t locale);float wcstof_l(const wchar_t *__restrict str, wchar_t **__restrict tail, locale_t locale);long double wcstold_l(const wchar_t *__restrict str, wchar_t **__restrict tail, locale_t locale);double _wcstod_r(void *reent, const wchar_t *str, wchar_t **tail);float _wcstof_r(void *reent, const wchar_t *str, wchar_t **tail);
Descriptionwcstod, wcstof, wcstold parse the wide-character stringstr, producing a substring which can be converted to a double,float, or long double value. The substring converted is the longestinitial subsequence of str, beginning with the first non-whitespacecharacter, that has one of these formats:
[+|-]digits[.[digits]][(e|E)[+|-]digits][+|-].digits[(e|E)[+|-]digits][+|-](i|I)(n|N)(f|F)[(i|I)(n|N)(i|I)(t|T)(y|Y)][+|-](n|N)(a|A)(n|N)[<(>[hexdigits]<)>][+|-]0(x|X)hexdigits[.[hexdigits]][(p|P)[+|-]digits][+|-]0(x|X).hexdigits[(p|P)[+|-]digits]
The substring contains no characters if str is empty, consistsentirely of whitespace, or if the first non-whitespacecharacter is something other than +, -, ., or adigit, and cannot be parsed as infinity or NaN. If the platformdoes not support NaN, then NaN is treated as an empty substring.If the substring is empty, no conversion is done, andthe value of str is stored in *tail. Otherwise,the substring is converted, and a pointer to the final string(which will contain at least the terminating null character ofstr) is stored in *tail. If you want noassignment to *tail, pass a null pointer as tail.
This implementation returns the nearest machine number to theinput decimal string. Ties are broken by using the IEEEround-even rule. However, wcstof is currently subject todouble rounding errors.
wcstod_l, wcstof_l, wcstold_l are like wcstod,wcstof, wcstold but perform the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour isundefined.
The alternate functions _wcstod_r and _wcstof_r arereentrant versions of wcstod and wcstof, respectively.The extra argument reent is a pointer to a reentrancy structure.
Returns
Return the converted substring value, if any. Ifno conversion could be performed, 0 is returned. If thecorrect value is out of the range of representable values,plus or minus HUGE_VAL is returned, and ERANGE isstored in errno. If the correct value would cause underflow, 0is returned and ERANGE is stored in errno.
Portabilitywcstod is ANSI.wcstof, wcstold are C99.wcstod_l, wcstof_l, wcstold_l are GNU extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: wcstoll, wcstoll_l—wide string to long long, Previous: wcstod, wcstof, wcstold, wcstod_l, wcstof_l, wcstold_l—wide char string to double or float, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstol, wcstol_l—wide string to longSynopsis
#include <wchar.h>long wcstol(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base);#include <wchar.h>long wcstol_l(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base, locale_t locale);long _wcstol_r(void *reent, const wchar_t *s, wchar_t **ptr, int base);
Description
The function wcstol converts the wide string *s toa long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof characters resembling an integer in the radix specified by base;and a trailing portion consisting of zero or more unparseable characters,and always including the terminating null character. Then, it attemptsto convert the subject string into a long and returns theresult.
If the value of base is 0, the subject string is expected to looklike a normal C integer constant: an optional sign, a possible ‘0x’indicating a hexadecimal base, and a number. If base is between2 and 36, the expected form of the subject is a sequence of lettersand digits representing an integer in the radix specified by base,with an optional plus or minus sign. The letters a–z (or,equivalently, A–Z) are used to signify values from 10 to 35;only letters whose ascribed values are less than base arepermitted. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible letter or digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,wcstol attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. If the subject string begins witha minus sign, the value is negated. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (or not in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
The alternate function _wcstol_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
wcstol_l is like wcstol but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswcstol, wcstol_l return the converted value, if any. If noconversion was made, 0 is returned.
wcstol, wcstol_l return LONG_MAX or LONG_MIN if themagnitude of the converted value is too large, and sets errnoto ERANGE.
Portabilitywcstol is ANSI.wcstol_l is a GNU extension.
No supporting OS subroutines are required.
Next: wcstoul, wcstoul_l—wide string to unsigned long, Previous: wcstol, wcstol_l—wide string to long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstoll, wcstoll_l—wide string to long longSynopsis
#include <wchar.h>long long wcstoll(const wchar_t *__restrict s, wchar_t **__restrict ptr,int base);#include <wchar.h>long long wcstoll_l(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base, locale_t locale);long long _wcstoll_r(void *reent, const wchar_t *s, wchar_t **ptr, int base);
Description
The function wcstoll converts the wide string *s toa long long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof characters resembling an integer in the radix specified by base;and a trailing portion consisting of zero or more unparseable characters,and always including the terminating null character. Then, it attemptsto convert the subject string into a long long and returns theresult.
If the value of base is 0, the subject string is expected to looklike a normal C integer constant: an optional sign, a possible ‘0x’indicating a hexadecimal base, and a number. If base is between2 and 36, the expected form of the subject is a sequence of lettersand digits representing an integer in the radix specified by base,with an optional plus or minus sign. The letters a–z (or,equivalently, A–Z) are used to signify values from 10 to 35;only letters whose ascribed values are less than base arepermitted. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible letter or digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,wcstoll attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. If the subject string begins witha minus sign, the value is negated. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (or not in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
The alternate function _wcstoll_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
wcstoll_l is like wcstoll but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswcstoll, wcstoll_l return the converted value, if any. If noconversion was made, 0 is returned.
wcstoll, wcstoll_l return LONG_LONG_MAX or LONG_LONG_MINif the magnitude of the converted value is too large, and sets errnoto ERANGE.
Portabilitywcstoll is ANSI.wcstoll_l is a GNU extension.
No supporting OS subroutines are required.
Next: wcstoull, wcstoull_l—wide string to unsigned long long, Previous: wcstoll, wcstoll_l—wide string to long long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstoul, wcstoul_l—wide string to unsigned longSynopsis
#include <wchar.h>unsigned long wcstoul(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base);#include <wchar.h>unsigned long wcstoul_l(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base, locale_t locale);unsigned long _wcstoul_r(void *reent, const wchar_t *s, wchar_t **ptr, int base);
Description
The function wcstoul converts the wide string *s toan unsigned long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof the digits meaningful in the radix specified by base(for example, 0 through 7 if the value of base is 8);and a trailing portion consisting of one or more unparseable characters,which always includes the terminating null character. Then, it attemptsto convert the subject string into an unsigned long integer, and returns theresult.
If the value of base is zero, the subject string is expected to looklike a normal C integer constant (save that no optional sign is permitted):a possible 0x indicating hexadecimal radix, and a number.If base is between 2 and 36, the expected form of the subject is asequence of digits (which may include letters, depending on thebase) representing an integer in the radix specified by base.The letters a–z (or A–Z) are used as digits valued from10 to 35. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,wcstoul attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (that is, if *s does not startwith a substring in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
The alternate function _wcstoul_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
wcstoul_l is like wcstoul but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswcstoul, wcstoul_l return the converted value, if any. If noconversion was made, 0 is returned.
wcstoul, wcstoul_l return ULONG_MAX if the magnitude of theconverted value is too large, and sets errno to ERANGE.
Portabilitywcstoul is ANSI.wcstoul_l is a GNU extension.
wcstoul requires no supporting OS subroutines.
Next: system—execute command string, Previous: wcstoul, wcstoul_l—wide string to unsigned long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstoull, wcstoull_l—wide string to unsigned long longSynopsis
#include <wchar.h>unsigned long long wcstoull(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base);#include <wchar.h>unsigned long long wcstoull_l(const wchar_t *__restrict s, wchar_t **__restrict ptr, int base, locale_t locale);unsigned long long _wcstoull_r(void *reent, const wchar_t *s, wchar_t **ptr, int base);
Description
The function wcstoull converts the wide string *s toan unsigned long long. First, it breaks down the string into three parts:leading whitespace, which is ignored; a subject string consistingof the digits meaningful in the radix specified by base(for example, 0 through 7 if the value of base is 8);and a trailing portion consisting of one or more unparseable characters,which always includes the terminating null character. Then, it attemptsto convert the subject string into an unsigned long long integer, and returns theresult.
If the value of base is zero, the subject string is expected to looklike a normal C integer constant: an optional sign (+ or -),a possible 0x indicating hexadecimal radix or a possible <0> indicatingoctal radix, and a number.If base is between 2 and 36, the expected form of the subject is asequence of digits (which may include letters, depending on thebase) representing an integer in the radix specified by base.The letters a–z (or A–Z) are used as digits valued from10 to 35. If base is 16, a leading 0x is permitted.
The subject sequence is the longest initial sequence of the inputstring that has the expected form, starting with the firstnon-whitespace character. If the string is empty or consists entirelyof whitespace, or if the first non-whitespace character is not apermissible digit, the subject string is empty.
If the subject string is acceptable, and the value of base is zero,wcstoull attempts to determine the radix from the input string. Astring with a leading 0x is treated as a hexadecimal value; a string witha leading 0 and no x is treated as octal; all other strings aretreated as decimal. If base is between 2 and 36, it is used as theconversion radix, as described above. Finally, a pointer to the firstcharacter past the converted subject string is stored in ptr, ifptr is not NULL.
If the subject string is empty (that is, if *s does not startwith a substring in acceptable form), no conversionis performed and the value of s is stored in ptr (if ptr isnot NULL).
The alternate function _wcstoull_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
wcstoull_l is like wcstoull but performs the conversion based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswcstoull, wcstoull_l return 0 and sets errno to EINVALif the value of base is not supported.
wcstoull, wcstoull_l return the converted value, if any. If noconversion was made, 0 is returned.
wcstoull, wcstoull_l return ULLONG_MAX if the magnitude ofthe converted value is too large, and sets errno to ERANGE.
Portabilitywcstoull is ANSI.wcstoull_l is a GNU extension.
wcstoull requires no supporting OS subroutines.
Next: utoa—unsigned integer to string, Previous: wcstoull, wcstoull_l—wide string to unsigned long long, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
system—execute command stringSynopsis
#include <stdlib.h>int system(char *s);int _system_r(void *reent, char *s);
Description
Use system to pass a command string *s to /bin/sh onyour system, and wait for it to finish executing.
Use “system(NULL)” to test whether your system has /bin/shavailable.
The alternate function _system_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnssystem(NULL) returns a non-zero value if /bin/sh is available, and0 if it is not.
With a command argument, the result of system is the exit statusreturned by /bin/sh.
Portability
ANSI C requires system, but leaves the nature and effects of acommand processor undefined. ANSI C does, however, specify thatsystem(NULL) return zero or nonzero to report on the existence ofa command processor.
POSIX.2 requires system, and requires that it invoke a sh.Where sh is found is left unspecified.
Supporting OS subroutines required: _exit, _execve, _fork_r,_wait_r.
Next: wcstombs—minimal wide char string to multibyte string converter, Previous: system—execute command string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
utoa—unsigned integer to stringSynopsis
#include <stdlib.h>char *utoa(unsigned value, char *str, int base);char *__utoa(unsigned value, char *str, int base);
Descriptionutoa converts the unsigned integer [<value>] to a null-terminated stringusing the specified base, which must be between 2 and 36, inclusive.str should be an array long enough to contain the convertedvalue, which in the worst case is sizeof(int)*8+1 bytes. 
Returns
A pointer to the string, str, or NULL if base is invalid.
Portabilityutoa is non-ANSI.
No supporting OS subroutine calls are required.
Next: wctomb—minimal wide char to multibyte converter, Previous: utoa—unsigned integer to string, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wcstombs—minimal wide char string to multibyte string converterSynopsis
#include <stdlib.h>size_t wcstombs(char *restrict s, const wchar_t *restrict pwc, size_t n);
Description
When _MB_CAPABLE is not defined, this is a minimal ANSI-conformingimplementation of wcstombs. In this case,all wide-characters are expected to represent single bytes and soare converted simply by casting to char.
When _MB_CAPABLE is defined, this routine calls _wcstombs_r to performthe conversion, passing a state variable to allow state dependentdecoding. The result is based on the locale setting which maybe restricted to a defined set of locales.
Returns
This implementation of wcstombs returns 0 ifs is NULL or is the empty string;it returns -1 if _MB_CAPABLE and one of thewide-char characters does not represent a valid multi-byte character;otherwise it returns the minimum of: n or thenumber of bytes that are transferred to s, not including thenul terminator.
If the return value is -1, the state of the pwc string isindeterminate. If the input has a length of 0, the outputstring will be modified to contain a wchar_t nul terminator ifn > 0.
Portabilitywcstombs is required in the ANSI C standard. However, the preciseeffects vary with the locale.
wcstombs requires no supporting OS subroutines.
Previous: wcstombs—minimal wide char string to multibyte string converter, Up: Standard Utility Functions (stdlib.h)   [Contents][Index]
wctomb—minimal wide char to multibyte converterSynopsis
#include <stdlib.h>int wctomb(char *s, wchar_t wchar);
Description
When _MB_CAPABLE is not defined, this is a minimal ANSI-conformingimplementation of wctomb. Theonly “wide characters” recognized are single bytes,and they are “converted” to themselves. 
When _MB_CAPABLE is defined, this routine calls _wctomb_r to performthe conversion, passing a state variable to allow state dependentdecoding. The result is based on the locale setting which maybe restricted to a defined set of locales.
Each call to wctomb modifies *s unless s is a nullpointer or _MB_CAPABLE is defined and wchar is invalid.
Returns
This implementation of wctomb returns 0 ifs is NULL; it returns -1 if _MB_CAPABLE is enabledand the wchar is not a valid multi-byte character, it returns 1if _MB_CAPABLE is not defined or the wchar is in reality a singlebyte character, otherwise it returns the number of bytes in themulti-byte character.
Portabilitywctomb is required in the ANSI C standard. However, the preciseeffects vary with the locale.
wctomb requires no supporting OS subroutines.
Next: Input and Output (stdio.h), Previous: Standard Utility Functions (stdlib.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter groups macros (which are also available as subroutines)to classify characters into several categories (alphabetic,numeric, control characters, whitespace, and so on), or to performsimple character mappings.
The header file ctype.h defines the macros.
isalnum, isalnum_l—alphanumeric character predicateisalpha, isalpha_l—alphabetic character predicateisascii, isascii_l—ASCII character predicateisblank, isblank_l—blank character predicateiscntrl, iscntrl_l—control character predicateisdigit, isdigit_l—decimal digit predicateislower, islower_l—lowercase character predicateisprint, isgraph, isprint_l, isgraph_l—printable character predicatesispunct, ispunct_l—punctuation character predicateisspace, isspace_l—whitespace character predicateisupper, isupper_l—uppercase character predicateisxdigit, isxdigit_l—hexadecimal digit predicatetoascii, toascii_l—force integers to ASCII rangetolower, tolower_l—translate characters to lowercasetoupper, toupper_l—translate characters to uppercaseiswalnum, iswalnum_l—alphanumeric wide character testiswalpha, iswalpha_l—alphabetic wide character testiswcntrl, iswcntrl_l—control wide character testiswblank, iswblank_l—blank wide character testiswdigit, iswdigit_l—decimal digit wide character testiswgraph, iswgraph_l—graphic wide character testiswlower, iswlower_l—lowercase wide character testiswprint, iswprint_l—printable wide character testiswpunct, iswpunct_l—punctuation wide character testiswspace, iswspace_l—whitespace wide character testiswupper, iswupper_l—uppercase wide character testiswxdigit, iswxdigit_l—hexadecimal digit wide character testiswctype, iswctype_l—extensible wide-character testwctype, wctype_l—get wide-character classification typetowlower, towlower_l—translate wide characters to lowercasetowupper, towupper_l—translate wide characters to uppercasetowctrans, towctrans_l—extensible wide-character translationwctrans, wctrans_l—get wide-character translation typeNext: isalpha, isalpha_l—alphabetic character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isalnum, isalnum_l—alphanumeric character predicateSynopsis
#include <ctype.h>int isalnum(int c);#include <ctype.h>int isalnum_l(int c, locale_t locale);
Descriptionisalnum is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for alphabetic ornumeric ASCII characters, and 0 for other arguments. It is definedonly if c is representable as an unsigned char or if c is EOF.
isalnum_l is like isalnum but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isalnum’ or ‘#undef isalnum_l’.
Returnsisalnum,isalnum_l return non-zero if c is a letter or a digit.
Portabilityisalnum is ANSI C.isalnum_l is POSIX-1.2008.
No OS subroutines are required.
Next: isascii, isascii_l—ASCII character predicate, Previous: isalnum, isalnum_l—alphanumeric character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isalpha, isalpha_l—alphabetic character predicateSynopsis
#include <ctype.h>int isalpha(int c);#include <ctype.h>int isalpha_l(int c, locale_t locale);
Descriptionisalpha is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero when c represents analphabetic ASCII character, and 0 otherwise. It is defined only ifc is representable as an unsigned char or if c is EOF.
isalpha_l is like isalpha but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isalpha’ or ‘#undef isalpha_l’.
Returnsisalpha, isalpha_l return non-zero if c is a letter.
Portabilityisalpha is ANSI C.isalpha_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: isblank, isblank_l—blank character predicate, Previous: isalpha, isalpha_l—alphabetic character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isascii, isascii_l—ASCII character predicateSynopsis
#include <ctype.h>int isascii(int c);#include <ctype.h>int isascii_l(int c, locale_t locale);
Descriptionisascii is a macro which returns non-zero when c is an ASCIIcharacter, and 0 otherwise. It is defined for all integer values.
isascii_l is like isascii but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isascii’ or ‘#undef isascii_l’.
Returnsisascii, isascii_l return non-zero if the low order byte of cis in the range 0 to 127 (0x00–0x7F).
Portabilityisascii is ANSI C.isascii_l is a GNU extension.
No supporting OS subroutines are required.
Next: iscntrl, iscntrl_l—control character predicate, Previous: isascii, isascii_l—ASCII character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isblank, isblank_l—blank character predicateSynopsis
#include <ctype.h>int isblank(int c);#include <ctype.h>int isblank_l(int c, locale_t locale);
Descriptionisblank is a function which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for blank characters, and 0for other characters. It is defined only if c is representable as anunsigned char or if c is EOF.
isblank_l is like isblank but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsisblank, isblank_l return non-zero if c is a blank character.
Portabilityisblank is C99.isblank_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: isdigit, isdigit_l—decimal digit predicate, Previous: isblank, isblank_l—blank character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iscntrl, iscntrl_l—control character predicateSynopsis
#include <ctype.h>int iscntrl(int c);#include <ctype.h>int iscntrl_l(int c, locale_t locale);
Descriptioniscntrl is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for control characters, and 0for other characters. It is defined only if c is representable as anunsigned char or if c is EOF.
iscntrl_l is like iscntrl but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef iscntrl’ or ‘#undef iscntrl_l’.
Returnsiscntrl, iscntrl_l return non-zero if c is a delete characteror ordinary control character.
Portabilityiscntrl is ANSI C.iscntrl_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: islower, islower_l—lowercase character predicate, Previous: iscntrl, iscntrl_l—control character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isdigit, isdigit_l—decimal digit predicateSynopsis
#include <ctype.h>int isdigit(int c);#include <ctype.h>int isdigit_l(int c, locale_t locale);
Descriptionisdigit is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for decimal digits, and 0 forother characters. It is defined only if c is representable as anunsigned char or if c is EOF.
isdigit_l is like isdigit but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isdigit’ or ‘#undef isdigit_l’.
Returnsisdigit, isdigit_l return non-zero if c is a decimal digit(0–9).
Portabilityisdigit is ANSI C.isdigit_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: isprint, isgraph, isprint_l, isgraph_l—printable character predicates, Previous: isdigit, isdigit_l—decimal digit predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
islower, islower_l—lowercase character predicateSynopsis
#include <ctype.h>int islower(int c);#include <ctype.h>int islower_l(int c, locale_t locale);
Descriptionislower is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for minuscules(lowercase alphabetic characters), and 0 for other characters.It is defined only if c is representable as an unsigned char or ifc is EOF.
islower_l is like islower but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef islower’ or ‘#undef islower_l’.
Returnsislower, islower_l return non-zero if c is a lowercase letter.
Portabilityislower is ANSI C.islower_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: ispunct, ispunct_l—punctuation character predicate, Previous: islower, islower_l—lowercase character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isprint, isgraph, isprint_l, isgraph_l—printable character predicatesSynopsis
#include <ctype.h>int isprint(int c);int isgraph(int c);#include <ctype.h>int isprint_l(int c, locale_t locale);int isgraph_l(int c, locale_t locale);
Descriptionisprint is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for printable characters,and 0 for other character arguments. It is defined only if c isrepresentable as an unsigned char or if c is EOF.
isgraph behaves identically to isprint, except that space charactersare excluded.
isprint_l, isgraph_l are like isprint, isgraph but performthe check based on the locale specified by the locale object locale. Iflocale is LC_GLOBAL_LOCALE or not a valid locale object, the behaviouris undefined.
You can use a compiled subroutine instead of the macro definition byundefining either macro using ‘#undef isprint’ or ‘#undef isgraph’,or ‘#undef isprint_l’ or ‘#undef isgraph_l’.
Returnsisprint, isprint_l return non-zero if c is a printing character.isgraph, isgraph_l return non-zero if c is a printing characterexcept spaces.
Portabilityisprint and isgraph are ANSI C.
No supporting OS subroutines are required.
Next: isspace, isspace_l—whitespace character predicate, Previous: isprint, isgraph, isprint_l, isgraph_l—printable character predicates, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
ispunct, ispunct_l—punctuation character predicateSynopsis
#include <ctype.h>int ispunct(int c);#include <ctype.h>int ispunct_l(int c, locale_t locale);
Descriptionispunct is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for printablepunctuation characters, and 0 for other characters. It is defined onlyif c is representable as an unsigned char or if c is EOF.
ispunct_l is like ispunct but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef ispunct’ or ‘#undef ispunct_l’.
Returnsispunct, ispunct_l return non-zero if c is a printablepunctuation character.
Portabilityispunct is ANSI C.ispunct_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: isupper, isupper_l—uppercase character predicate, Previous: ispunct, ispunct_l—punctuation character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isspace, isspace_l—whitespace character predicateSynopsis
#include <ctype.h>int isspace(int c);#include <ctype.h>int isspace_l(int c, locale_t locale);
Descriptionisspace is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for whitespacecharacters, and 0 for other characters. It is defined only when isascii(c) is true or c is EOF.
isspace_l is like isspace but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isspace’ or ‘#undef isspace_l’.
Returnsisspace, isspace_l return non-zero if c is a space, tab,carriage return, new line, vertical tab, or formfeed (0x09–0x0D,0x20), or one of the other space characters in non-ASCII charsets.
Portabilityisspace is ANSI C.isspace_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: isxdigit, isxdigit_l—hexadecimal digit predicate, Previous: isspace, isspace_l—whitespace character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isupper, isupper_l—uppercase character predicateSynopsis
#include <ctype.h>int isupper(int c);#include <ctype.h>int isupper_l(int c, locale_t locale);
Descriptionisupper is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for uppercase letters(A–Z), and 0 for other characters.
isupper_l is like isupper but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isupper’ or ‘#undef isupper_l’.
Returnsisupper, isupper_l return non-zero if c is an uppercase letter.
Portabilityisupper is ANSI C.isupper_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: toascii, toascii_l—force integers to ASCII range, Previous: isupper, isupper_l—uppercase character predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
isxdigit, isxdigit_l—hexadecimal digit predicateSynopsis
#include <ctype.h>int isxdigit(int c);#include <ctype.h>int isxdigit_l(int c, locale_t locale);
Descriptionisxdigit is a macro which classifies singlebyte charset values by tablelookup. It is a predicate returning non-zero for hexadecimal digits,and 0 for other characters. It is defined only if c isrepresentable as an unsigned char or if c is EOF.
isxdigit_l is like isxdigit but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining the macro using ‘#undef isxdigit’ or ‘#undef isxdigit_l’.
Returnsisxdigit, isxdigit_l return non-zero if c is a hexadecimal digit(0–9, a–f, or A–F).
Portabilityisxdigit is ANSI C.isxdigit_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: tolower, tolower_l—translate characters to lowercase, Previous: isxdigit, isxdigit_l—hexadecimal digit predicate, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
toascii, toascii_l—force integers to ASCII rangeSynopsis
#include <ctype.h>int toascii(int c);#include <ctype.h>int toascii_l(int c, locale_t locale);
Descriptiontoascii is a macro which coerces integers to the ASCII range (0–127) by zeroing any higher-order bits.
toascii_l is like toascii but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining this macro using ‘#undef toascii’ or ‘#undef toascii_l’.
Returnstoascii, toascii_l return integers between 0 and 127.
Portabilitytoascii is X/Open, BSD and POSIX-1.2001, but marked obsolete inPOSIX-1.2008.toascii_l is a GNU extension.
No supporting OS subroutines are required.
Next: toupper, toupper_l—translate characters to uppercase, Previous: toascii, toascii_l—force integers to ASCII range, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
tolower, tolower_l—translate characters to lowercaseSynopsis
#include <ctype.h>int tolower(int c);int _tolower(int c);#include <ctype.h>int tolower_l(int c, locale_t locale);
Descriptiontolower is a macro which converts uppercase characters to lowercase,leaving all other characters unchanged. It is only defined whenc is an integer in the range EOF to 255.
tolower_l is like tolower but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining this macro using ‘#undef tolower’ or ‘#undef tolower_l’.
_tolower performs the same conversion as tolower, but shouldonly be used when c is known to be an uppercase character (A–Z).
Returnstolower, tolower_l return the lowercase equivalent of c whenc is an uppercase character, and c otherwise.
_tolower returns the lowercase equivalent of c when it is acharacter between A and Z. If c is not one of thesecharacters, the behaviour of _tolower is undefined.
Portabilitytolower is ANSI C. _tolower is not recommended for portable programs.tolower_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswalnum, iswalnum_l—alphanumeric wide character test, Previous: tolower, tolower_l—translate characters to lowercase, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
toupper, toupper_l—translate characters to uppercaseSynopsis
#include <ctype.h>int toupper(int c);int _toupper(int c);#include <ctype.h>int toupper_l(int c, locale_t locale);
Descriptiontoupper is a macro which converts lowercase characters to uppercase,leaving all other characters unchanged. It is only defined whenc is an integer in the range EOF to 255.
toupper_l is like toupper but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
You can use a compiled subroutine instead of the macro definition byundefining this macro using ‘#undef toupper’ or ‘#undef toupper_l’.
_toupper performs the same conversion as toupper, but shouldonly be used when c is known to be a lowercase character (a–z).
Returnstoupper, toupper_l return the uppercase equivalent of c whenc is a lowercase character, and c otherwise.
_toupper returns the uppercase equivalent of c when it is acharacter between a and z. If c is not one of thesecharacters, the behaviour of _toupper is undefined.
Portabilitytoupper is ANSI C. _toupper is not recommended for portable programs.toupper_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswalpha, iswalpha_l—alphabetic wide character test, Previous: toupper, toupper_l—translate characters to uppercase, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswalnum, iswalnum_l—alphanumeric wide character testSynopsis
#include <wctype.h>int iswalnum(wint_t c);#include <wctype.h>int iswalnum_l(wint_t c, locale_t locale);
Descriptioniswalnum is a function which classifies wide-character values thatare alphanumeric.
iswalnum_l is like iswalnum but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswalnum, iswalnum_l return non-zero if c is a alphanumericwide character.
Portabilityiswalnum is C99.iswalnum_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswcntrl, iswcntrl_l—control wide character test, Previous: iswalnum, iswalnum_l—alphanumeric wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswalpha, iswalpha_l—alphabetic wide character testSynopsis
#include <wctype.h>int iswalpha(wint_t c);#include <wctype.h>int iswalpha_l(wint_t c, locale_t locale);
Descriptioniswalpha is a function which classifies wide-character values thatare alphabetic.
iswalpha_l is like iswalpha but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswalpha, iswalpha_l return non-zero if c is an alphabeticwide character.
Portabilityiswalpha is C99.iswalpha_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswblank, iswblank_l—blank wide character test, Previous: iswalpha, iswalpha_l—alphabetic wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswcntrl, iswcntrl_l—control wide character testSynopsis
#include <wctype.h>int iswcntrl(wint_t c);#include <wctype.h>int iswcntrl_l(wint_t c, locale_t locale);
Descriptioniswcntrl is a function which classifies wide-character values thatare categorized as control characters.
iswcntrl_l is like iswcntrl but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswcntrl, iswcntrl_l return non-zero if c is a control wide character.
Portabilityiswcntrl is C99.iswcntrl_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswdigit, iswdigit_l—decimal digit wide character test, Previous: iswcntrl, iswcntrl_l—control wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswblank, iswblank_l—blank wide character testSynopsis
#include <wctype.h>int iswblank(wint_t c);#include <wctype.h>int iswblank_l(wint_t c, locale_t locale);
Descriptioniswblank is a function which classifies wide-character values thatare categorized as blank.
iswblank_l is like iswblank but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswblank, iswblank_l return non-zero if c is a blank wide character.
Portabilityiswblank is C99.iswblank_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswgraph, iswgraph_l—graphic wide character test, Previous: iswblank, iswblank_l—blank wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswdigit, iswdigit_l—decimal digit wide character testSynopsis
#include <wctype.h>int iswdigit(wint_t c);#include <wctype.h>int iswdigit_l(wint_t c, locale_t locale);
Descriptioniswdigit is a function which classifies wide-character values thatare decimal digits.
iswdigit_l is like iswdigit but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswdigit, iswdigit_l return non-zero if c is a decimal digit wide character.
Portabilityiswdigit is C99.iswdigit_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswlower, iswlower_l—lowercase wide character test, Previous: iswdigit, iswdigit_l—decimal digit wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswgraph, iswgraph_l—graphic wide character testSynopsis
#include <wctype.h>int iswgraph(wint_t c);#include <wctype.h>int iswgraph_l(wint_t c, locale_t locale);
Descriptioniswgraph is a function which classifies wide-character values thatare graphic.
iswgraph_l is like iswgraph but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswgraph, iswgraph_l return non-zero if c is a graphic wide character.
Portabilityiswgraph is C99.iswgraph_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswprint, iswprint_l—printable wide character test, Previous: iswgraph, iswgraph_l—graphic wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswlower, iswlower_l—lowercase wide character testSynopsis
#include <wctype.h>int iswlower(wint_t c);#include <wctype.h>int iswlower_l(wint_t c, locale_t locale);
Descriptioniswlower is a function which classifies wide-character values thatare categorized as lowercase.
iswlower_l is like iswlower but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswlower, iswlower_l return non-zero if c is a lowercase wide character.
Portabilityiswlower is C99.iswlower_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswpunct, iswpunct_l—punctuation wide character test, Previous: iswlower, iswlower_l—lowercase wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswprint, iswprint_l—printable wide character testSynopsis
#include <wctype.h>int iswprint(wint_t c);#include <wctype.h>int iswprint_l(wint_t c, locale_t locale);
Descriptioniswprint is a function which classifies wide-character values thatare printable.
iswprint_l is like iswprint but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswprint, iswprint_l return non-zero if c is a printable wide character.
Portabilityiswprint is C99.iswprint_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswspace, iswspace_l—whitespace wide character test, Previous: iswprint, iswprint_l—printable wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswpunct, iswpunct_l—punctuation wide character testSynopsis
#include <wctype.h>int iswpunct(wint_t c);#include <wctype.h>int iswpunct_l(wint_t c, locale_t locale);
Descriptioniswpunct is a function which classifies wide-character values thatare punctuation.
iswpunct_l is like iswpunct but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswpunct, iswpunct_l return non-zero if c is a punctuation wide character.
Portabilityiswpunct is C99.iswpunct_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswupper, iswupper_l—uppercase wide character test, Previous: iswpunct, iswpunct_l—punctuation wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswspace, iswspace_l—whitespace wide character testSynopsis
#include <wctype.h>int iswspace(wint_t c);#include <wctype.h>int iswspace_l(wint_t c, locale_t locale);
Descriptioniswspace is a function which classifies wide-character values thatare categorized as whitespace.
iswspace_l is like iswspace but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswspace, iswspace_l return non-zero if c is a whitespace wide character.
Portabilityiswspace is C99.iswspace_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswxdigit, iswxdigit_l—hexadecimal digit wide character test, Previous: iswspace, iswspace_l—whitespace wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswupper, iswupper_l—uppercase wide character testSynopsis
#include <wctype.h>int iswupper(wint_t c);#include <wctype.h>int iswupper_l(wint_t c, locale_t locale);
Descriptioniswupper is a function which classifies wide-character values thatare categorized as uppercase.
iswupper_l is like iswupper but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswupper, iswupper_l return non-zero if c is an uppercase wide character.
Portabilityiswupper is C99.iswupper_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: iswctype, iswctype_l—extensible wide-character test, Previous: iswupper, iswupper_l—uppercase wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswxdigit, iswxdigit_l—hexadecimal digit wide character testSynopsis
#include <wctype.h>int iswxdigit(wint_t c);#include <wctype.h>int iswxdigit_l(wint_t c, locale_t locale);
Descriptioniswxdigit is a function which classifies wide character values thatare hexadecimal digits.
iswxdigit_l is like iswxdigit but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswxdigit, iswxdigit_l return non-zero if c is a hexadecimal digit wide character.
Portabilityiswxdigit is C99.iswxdigit_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: wctype, wctype_l—get wide-character classification type, Previous: iswxdigit, iswxdigit_l—hexadecimal digit wide character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
iswctype, iswctype_l—extensible wide-character testSynopsis
#include <wctype.h>int iswctype(wint_t c, wctype_t desc);#include <wctype.h>int iswctype_l(wint_t c, wctype_t desc, locale_t locale);
Descriptioniswctype is a function which classifies wide-character values using thewide-character test specified by desc.
iswctype_l is like iswctype but performs the check based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnsiswctype, iswctype_l return non-zero if and only if c matchesthe test specified by desc. If desc is unknown, zero is returned.
Portabilityiswctype is C99.iswctype_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: towlower, towlower_l—translate wide characters to lowercase, Previous: iswctype, iswctype_l—extensible wide-character test, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
wctype, wctype_l—get wide-character classification typeSynopsis
#include <wctype.h>wctype_t wctype(const char *c);#include <wctype.h>wctype_t wctype_l(const char *c, locale_t locale);
Descriptionwctype is a function which takes a string c and gives backthe appropriate wctype_t type value associated with the string,if one exists. The following values are guaranteed to be recognized:"alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower", "print","punct", "space", "upper", and "xdigit".
wctype_l is like wctype but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswctype, wctype_l return 0 and sets errno to EINVAL if thegiven name is invalid. Otherwise, it returns a valid non-zero wctype_tvalue.
Portabilitywctype is C99.wctype_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: towupper, towupper_l—translate wide characters to uppercase, Previous: wctype, wctype_l—get wide-character classification type, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
towlower, towlower_l—translate wide characters to lowercaseSynopsis
#include <wctype.h>wint_t towlower(wint_t c);#include <wctype.h>wint_t towlower_l(wint_t c, locale_t locale);
Descriptiontowlower is a function which converts uppercase wide characters tolowercase, leaving all other characters unchanged.
towlower_l is like towlower but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnstowlower, towlower_l return the lowercase equivalent of c when it is auppercase wide character; otherwise, it returns the input character.
Portabilitytowlower is C99.towlower_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: towctrans, towctrans_l—extensible wide-character translation, Previous: towlower, towlower_l—translate wide characters to lowercase, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
towupper, towupper_l—translate wide characters to uppercaseSynopsis
#include <wctype.h>wint_t towupper(wint_t c);#include <wctype.h>wint_t towupper_l(wint_t c, locale_t locale);
Descriptiontowupper is a function which converts lowercase wide characters touppercase, leaving all other characters unchanged.
towupper_l is like towupper but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnstowupper, towupper_l return the uppercase equivalent of c when it is alowercase wide character, otherwise, it returns the input character.
Portabilitytowupper is C99.towupper_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: wctrans, wctrans_l—get wide-character translation type, Previous: towupper, towupper_l—translate wide characters to uppercase, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
towctrans, towctrans_l—extensible wide-character translationSynopsis
#include <wctype.h>wint_t towctrans(wint_t c, wctrans_t w);#include <wctype.h>wint_t towctrans_l(wint_t c, wctrans_t w, locale_t locale);
Descriptiontowctrans is a function which converts wide characters based ona specified translation type w. If the translation type isinvalid or cannot be applied to the current character, no changeto the character is made.
towctrans_l is like towctrans but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnstowctrans, towctrans_l return the translated equivalent of cwhen it is a valid for the given translation, otherwise, it returns theinput character. When the translation type is invalid, errno isset to EINVAL.
Portabilitytowctrans is C99.towctrans_l is POSIX-1.2008.
No supporting OS subroutines are required.
Previous: towctrans, towctrans_l—extensible wide-character translation, Up: Character Type Macros and Functions (ctype.h)   [Contents][Index]
wctrans, wctrans_l—get wide-character translation typeSynopsis
#include <wctype.h>wctrans_t wctrans(const char *c);#include <wctype.h>wctrans_t wctrans_l(const char *c, locale_t locale);
Descriptionwctrans is a function which takes a string c and gives backthe appropriate wctrans_t type value associated with the string,if one exists. The following values are guaranteed to be recognized:"tolower" and "toupper".
wctrans_l is like wctrans but performs the function based on thelocale specified by the locale object locale. If locale isLC_GLOBAL_LOCALE or not a valid locale object, the behaviour is undefined.
Returnswctrans, wctrans_l return 0 and sets errno to EINVAL if thegiven name is invalid. Otherwise, it returns a valid non-zero wctrans_tvalue.
Portabilitywctrans is C99.wctrans_l is POSIX-1.2008.
No supporting OS subroutines are required.
Next: Large File Input and Output (stdio.h), Previous: Character Type Macros and Functions (ctype.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter comprises functions to manage filesor other input/output streams. Among these functions are subroutinesto generate or scan strings according to specifications from a format string.
The underlying facilities for input and output depend on the hostsystem, but these functions provide a uniform interface.
The corresponding declarations are in stdio.h.
The reentrant versions of these functions use macros
_stdin_r(reent)_stdout_r(reent)_stderr_r(reent)
instead of the globals stdin, stdout, andstderr. The argument reent is a pointer to a reentrancystructure.
clearerr, clearerr_unlocked—clear file or stream error indicatordiprintf, vdiprintf—print to a file descriptor (integer only)dprintf, vdprintf—print to a file descriptorfclose—close a filefcloseall—close all filesfdopen—turn open file into a streamfeof, feof_unlocked—test for end of fileferror, ferror_unlocked—test whether read/write error has occurredfflush, fflush_unlocked—flush buffered file outputfgetc, fgetc_unlocked—get a character from a file or streamfgetpos—record position in a stream or filefgets, fgets_unlocked—get character string from a file or streamfgetwc, getwc, fgetwc_unlocked, getwc_unlocked—get a wide character from a file or streamfgetws, fgetws_unlocked—get wide character string from a file or streamfileno, fileno_unlocked—return file descriptor associated with streamfmemopen—open a stream around a fixed-length stringfopen—open a filefopencookie—open a stream with custom callbacksfpurge—discard pending file I/Ofputc, fputc_unlocked—write a character on a stream or filefputs, fputs_unlocked—write a character string in a file or streamfputwc, putwc, fputwc_unlocked, putwc_unlocked—write a wide character on a stream or filefputws, fputws_unlocked—write a wide character string in a file or streamfread, fread_unlocked—read array elements from a filefreopen—open a file using an existing file descriptorfseek, fseeko—set file position__fsetlocking—set or query locking mode on FILE streamfsetpos—restore position of a stream or fileftell, ftello—return position in a stream or filefunopen, fropen, fwopen—open a stream with custom callbacksfwide—set and determine the orientation of a FILE streamfwrite, fwrite_unlocked—write array elementsgetc—read a character (macro)getc_unlocked—non-thread-safe version of getc (macro)getchar—read a character (macro)getchar_unlocked—non-thread-safe version of getchar (macro)getdelim—read a line up to a specified line delimitergetline—read a line from a filegets—get character string (obsolete, use fgets instead)getw—read a word (int)getwchar, getwchar_unlocked—read a wide character from standard inputmktemp, mkstemp, mkostemp, mkstemps,open_memstream, open_wmemstream—open a write stream around an arbitrary-length stringperror—print an error message on standard errorputc—write a character (macro)putc_unlocked—non-thread-safe version of putc (macro)putchar—write a character (macro)putchar_unlocked—non-thread-safe version of putchar (macro)puts—write a character stringputw—write a word (int)putwchar, putwchar_unlocked—write a wide character to standard outputremove—delete a file’s namerename—rename a filerewind—reinitialize a file or streamsetbuf—specify full buffering for a file or streamsetbuffer—specify full buffering for a file or stream with sizesetlinebuf—specify line buffering for a file or streamsetvbuf—specify file or stream bufferingsiprintf, fiprintf, iprintf, sniprintf, asiprintf, asniprintf—format output (integer only)siscanf, fiscanf, iscanf—scan and format non-floating inputsprintf, fprintf, printf, snprintf, asprintf, asnprintf—format outputsscanf, fscanf, scanf—scan and format inputstdio_ext,__fbufsize,__fpending,__flbf,__freadable,__fwritable,__freading,__fwriting—access internals of FILE structureswprintf, fwprintf, wprintf—wide character format outputswscanf, fwscanf, wscanf—scan and format wide character inputtmpfile—create a temporary filetmpnam, tempnam—name for a temporary fileungetc—push data back into a streamungetwc—push wide character data back into a streamvfprintf, vprintf, vsprintf, vsnprintf, vasprintf, vasnprintf—format argument listvfscanf, vscanf, vsscanf—format argument listvfwprintf, vwprintf, vswprintf—wide character format argument listvfwscanf, vwscanf, vswscanf—scan and format argument list from wide character inputviprintf, vfiprintf, vsiprintf, vsniprintf, vasiprintf, vasniprintf—format argument list (integer only)viscanf, vfiscanf, vsiscanf—format argument listNext: diprintf, vdiprintf—print to a file descriptor (integer only), Up: Input and Output (stdio.h)   [Contents][Index]
clearerr, clearerr_unlocked—clear file or stream error indicatorSynopsis
#include <stdio.h>void clearerr(FILE *fp);#define _BSD_SOURCE#include <stdio.h>void clearerr_unlocked(FILE *fp);
Description
The stdio functions maintain an error indicator with each filepointer fp, to record whether any read or write errors haveoccurred on the associated file or stream. Similarly, it maintains anend-of-file indicator to record whether there is no more data in thefile.
Use clearerr to reset both of these indicators.
See ferror and feof to query the two indicators.
clearerr_unlocked is a non-thread-safe version of clearerr.clearerr_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenclearerr_unlocked is equivalent to clearerr.
Returnsclearerr does not return a result.
Portability
ANSI C requires clearerr.
clearerr_unlocked is a BSD extension also provided by GNU libc.
No supporting OS subroutines are required.
Next: dprintf, vdprintf—print to a file descriptor, Previous: clearerr, clearerr_unlocked—clear file or stream error indicator, Up: Input and Output (stdio.h)   [Contents][Index]
diprintf, vdiprintf—print to a file descriptor (integer only)Synopsis
#include <stdio.h>#include <stdarg.h>int diprintf(int fd, const char *format, ...);int vdiprintf(int fd, const char *format, va_list ap);int _diprintf_r(struct _reent *ptr, int fd, const char *format, ...);int _vdiprintf_r(struct _reent *ptr, int fd, const char *format, va_list ap);
Descriptiondiprintf and vdiprintf are similar to dprintf and vdprintf,except that only integer format specifiers are processed.
The functions _diprintf_r and _vdiprintf_r are simplyreentrant versions of the functions above.
Returns
Similar to dprintf and vdprintf.
Portability
This set of functions is an integer-only extension, and is not portable.
Supporting OS subroutines required: sbrk, write.
Next: fclose—close a file, Previous: diprintf, vdiprintf—print to a file descriptor (integer only), Up: Input and Output (stdio.h)   [Contents][Index]
dprintf, vdprintf—print to a file descriptorSynopsis
#include <stdio.h>#include <stdarg.h>int dprintf(int fd, const char *restrict format, ...);int vdprintf(int fd, const char *restrict format, va_list ap);int _dprintf_r(struct _reent *ptr, int fd, const char *restrict format, ...);int _vdprintf_r(struct _reent *ptr, int fd, const char *restrict format, va_list ap);
Descriptiondprintf and vdprintf allow printing a format, similarly toprintf, but write to a file descriptor instead of to a FILEstream.
The functions _dprintf_r and _vdprintf_r are simplyreentrant versions of the functions above.
Returns
The return value and errors are exactly as for write, except thaterrno may also be set to ENOMEM if the heap is exhausted.
Portability
This function is originally a GNU extension in glibc and is not portable.
Supporting OS subroutines required: sbrk, write.
Next: fcloseall—close all files, Previous: dprintf, vdprintf—print to a file descriptor, Up: Input and Output (stdio.h)   [Contents][Index]
fclose—close a fileSynopsis
#include <stdio.h>int fclose(FILE *fp);int _fclose_r(struct _reent *reent, FILE *fp);
Description
If the file or stream identified by fp is open, fclose closesit, after first ensuring that any pending data is written (by callingfflush(fp)).
The alternate function _fclose_r is a reentrant version.The extra argument reent is a pointer to a reentrancy structure.
Returnsfclose returns 0 if successful (including when fp isNULL or not an open file); otherwise, it returns EOF.
Portabilityfclose is required by ANSI C.
Required OS subroutines: close, fstat, isatty, lseek,read, sbrk, write.
Next: fdopen—turn open file into a stream, Previous: fclose—close a file, Up: Input and Output (stdio.h)   [Contents][Index]
fcloseall—close all filesSynopsis
#include <stdio.h>int fcloseall(void);int _fcloseall_r (struct _reent *ptr);
Descriptionfcloseall closes all files in the current reentrancy struct’s domain.The function _fcloseall_r is the same function, except the reentrancystruct is passed in as the ptr argument.
This function is not recommended as it closes all streams, includingthe std streams.
Returnsfclose returns 0 if all closes are successful. Otherwise,EOF is returned.
Portabilityfcloseall is a glibc extension.
Required OS subroutines: close, fstat, isatty, lseek,read, sbrk, write.
Next: feof, feof_unlocked—test for end of file, Previous: fcloseall—close all files, Up: Input and Output (stdio.h)   [Contents][Index]
fdopen—turn open file into a streamSynopsis
#include <stdio.h>FILE *fdopen(int fd, const char *mode);FILE *_fdopen_r(struct _reent *reent, int fd, const char *mode);
Descriptionfdopen produces a file descriptor of type FILE *, from adescriptor for an already-open file (returned, for example, by thesystem subroutine open rather than by fopen).The mode argument has the same meanings as in fopen.
Returns
File pointer or NULL, as for fopen.
Portabilityfdopen is ANSI.
Next: ferror, ferror_unlocked—test whether read/write error has occurred, Previous: fdopen—turn open file into a stream, Up: Input and Output (stdio.h)   [Contents][Index]
feof, feof_unlocked—test for end of fileSynopsis
#include <stdio.h>int feof(FILE *fp);#define _BSD_SOURCE#include <stdio.h>int feof_unlocked(FILE *fp);
Descriptionfeof tests whether or not the end of the file identified by fphas been reached.
feof_unlocked is a non-thread-safe version of feof.feof_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfeof_unlocked is equivalent to feof.
Returnsfeof returns 0 if the end of file has not yet been reached; ifat end of file, the result is nonzero.
Portabilityfeof is required by ANSI C.
feof_unlocked is a BSD extension also provided by GNU libc.
No supporting OS subroutines are required.
Next: fflush, fflush_unlocked—flush buffered file output, Previous: feof, feof_unlocked—test for end of file, Up: Input and Output (stdio.h)   [Contents][Index]
ferror, ferror_unlocked—test whether read/write error has occurredSynopsis
#include <stdio.h>int ferror(FILE *fp);#define _BSD_SOURCE#include <stdio.h>int ferror_unlocked(FILE *fp);
Description
The stdio functions maintain an error indicator with each filepointer fp, to record whether any read or write errors haveoccurred on the associated file or stream.Use ferror to query this indicator.
See clearerr to reset the error indicator.
ferror_unlocked is a non-thread-safe version of ferror.ferror_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenferror_unlocked is equivalent to ferror.
Returnsferror returns 0 if no errors have occurred; it returns anonzero value otherwise.
Portability
ANSI C requires ferror.
ferror_unlocked is a BSD extension also provided by GNU libc.
No supporting OS subroutines are required.
Next: fgetc, fgetc_unlocked—get a character from a file or stream, Previous: ferror, ferror_unlocked—test whether read/write error has occurred, Up: Input and Output (stdio.h)   [Contents][Index]
fflush, fflush_unlocked—flush buffered file outputSynopsis
#include <stdio.h>int fflush(FILE *fp);#define _BSD_SOURCE#include <stdio.h>int fflush_unlocked(FILE *fp);#include <stdio.h>int _fflush_r(struct _reent *reent, FILE *fp);#define _BSD_SOURCE#include <stdio.h>int _fflush_unlocked_r(struct _reent *reent, FILE *fp);
Description
The stdio output functions can buffer output before delivering itto the host system, in order to minimize the overhead of system calls.
Use fflush to deliver any such pending output (for the fileor stream identified by fp) to the host system.
If fp is NULL, fflush delivers pending output from allopen files.
Additionally, if fp is a seekable input stream visiting a filedescriptor, set the position of the file descriptor to match nextunread byte, useful for obeying POSIX semantics when ending a processwithout consuming all input from the stream.
fflush_unlocked is a non-thread-safe version of fflush.fflush_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfflush_unlocked is equivalent to fflush.
The alternate functions _fflush_r and _fflush_unlocked_r arereentrant versions, where the extra argument reent is a pointer toa reentrancy structure, and fp must not be NULL.
Returnsfflush returns 0 unless it encounters a write error; in thatsituation, it returns EOF.
Portability
ANSI C requires fflush. The behavior on input streams is onlyspecified by POSIX, and not all implementations follow POSIX rules.
fflush_unlocked is a BSD extension also provided by GNU libc.
No supporting OS subroutines are required.
Next: fgetpos—record position in a stream or file, Previous: fflush, fflush_unlocked—flush buffered file output, Up: Input and Output (stdio.h)   [Contents][Index]
fgetc, fgetc_unlocked—get a character from a file or streamSynopsis
#include <stdio.h>int fgetc(FILE *fp);#define _BSD_SOURCE#include <stdio.h>int fgetc_unlocked(FILE *fp);#include <stdio.h>int _fgetc_r(struct _reent *ptr, FILE *fp);#define _BSD_SOURCE#include <stdio.h>int _fgetc_unlocked_r(struct _reent *ptr, FILE *fp);
Description
Use fgetc to get the next single character from the file or streamidentified by fp. As a side effect, fgetc advances the file’scurrent position indicator.
For a macro version of this function, see getc.
fgetc_unlocked is a non-thread-safe version of fgetc.fgetc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfgetc_unlocked is equivalent to fgetc.
The functions _fgetc_r and _fgetc_unlocked_r are simply reentrantversions that are passed the additional reentrant structure pointerargument: ptr.
Returns
The next character (read as an unsigned char, and cast toint), unless there is no more data, or the host system reports aread error; in either of these situations, fgetc returns EOF.
You can distinguish the two situations that cause an EOF result byusing the ferror and feof functions.
Portability
ANSI C requires fgetc.
fgetc_unlocked is a BSD extension also provided by GNU libc.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fgets, fgets_unlocked—get character string from a file or stream, Previous: fgetc, fgetc_unlocked—get a character from a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fgetpos—record position in a stream or fileSynopsis
#include <stdio.h>int fgetpos(FILE *restrict fp, fpos_t *restrict pos);int _fgetpos_r(struct _reent *ptr, FILE *restrict fp, fpos_t *restrict pos);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fgetpos to report on the current position for a fileidentified by fp; fgetpos will write a valuerepresenting that position at *pos. Later, you canuse this value with fsetpos to return the file to thisposition.
In the current implementation, fgetpos simply uses a charactercount to represent the file position; this is the same number thatwould be returned by ftell.
Returnsfgetpos returns 0 when successful. If fgetpos fails, theresult is 1. Failure occurs on streams that do not supportpositioning; the global errno indicates this condition with thevalue ESPIPE.
Portabilityfgetpos is required by the ANSI C standard, but the meaning of thevalue it records is not specified beyond requiring that it beacceptable as an argument to fsetpos. In particular, otherconforming C implementations may return a different result fromftell than what fgetpos writes at *pos.
No supporting OS subroutines are required.
Next: fgetwc, getwc, fgetwc_unlocked, getwc_unlocked—get a wide character from a file or stream, Previous: fgetpos—record position in a stream or file, Up: Input and Output (stdio.h)   [Contents][Index]
fgets, fgets_unlocked—get character string from a file or streamSynopsis
#include <stdio.h>char *fgets(char *restrict buf, int n, FILE *restrict fp);#define _GNU_SOURCE#include <stdio.h>char *fgets_unlocked(char *restrict buf, int n, FILE *restrict fp);#include <stdio.h>char *_fgets_r(struct _reent *ptr, char *restrict buf, int n, FILE *restrict fp);#include <stdio.h>char *_fgets_unlocked_r(struct _reent *ptr, char *restrict buf, int n, FILE *restrict fp);
Description
Reads at most n-1 characters from fp until a newlineis found. The characters including to the newline are storedin buf. The buffer is terminated with a 0.
fgets_unlocked is a non-thread-safe version of fgets.fgets_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfgets_unlocked is equivalent to fgets.
The functions _fgets_r and _fgets_unlocked_r are simplyreentrant versions that are passed the additional reentrant structurepointer argument: ptr.
Returnsfgets returns the buffer passed to it, with the datafilled in. If end of file occurs with some data alreadyaccumulated, the data is returned with no other indication. Ifno data are read, NULL is returned instead.
Portabilityfgets should replace all uses of gets. Note howeverthat fgets returns all of the data, while gets removesthe trailing newline (with no indication that it has done so.)
fgets_unlocked is a GNU extension.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fgetws, fgetws_unlocked—get wide character string from a file or stream, Previous: fgets, fgets_unlocked—get character string from a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fgetwc, getwc, fgetwc_unlocked, getwc_unlocked—get a wide character from a file or streamSynopsis
#include <stdio.h>#include <wchar.h>wint_t fgetwc(FILE *fp);#define _GNU_SOURCE#include <stdio.h>#include <wchar.h>wint_t fgetwc_unlocked(FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _fgetwc_r(struct _reent *ptr, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _fgetwc_unlocked_r(struct _reent *ptr, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t getwc(FILE *fp);#define _GNU_SOURCE#include <stdio.h>#include <wchar.h>wint_t getwc_unlocked(FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _getwc_r(struct _reent *ptr, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _getwc_unlocked_r(struct _reent *ptr, FILE *fp);
Description
Use fgetwc to get the next wide character from the file or streamidentified by fp. As a side effect, fgetwc advances the file’scurrent position indicator.
fgetwc_unlocked is a non-thread-safe version of fgetwc.fgetwc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfgetwc_unlocked is equivalent to fgetwc.
The getwc and getwc_unlocked functions or macros functions identicallyto fgetwc and fgetwc_unlocked. It may be implemented as a macro, andmay evaluate its argument more than once. There is no reason ever to use it.
_fgetwc_r, _getwc_r, _fgetwc_unlocked_r, and _getwc_unlocked_rare simply reentrant versions of the above functions that are passed theadditional reentrant structure pointer argument: ptr.
Returns
The next wide character cast to wint_t, unless there is no more data,or the host system reports a read error; in either of these situations,fgetwc and getwc return WEOF.
You can distinguish the two situations that cause an EOF result byusing the ferror and feof functions.
Portabilityfgetwc and getwc are required by C99 and POSIX.1-2001.
fgetwc_unlocked and getwc_unlocked are GNU extensions.
Next: fileno, fileno_unlocked—return file descriptor associated with stream, Previous: fgetwc, getwc, fgetwc_unlocked, getwc_unlocked—get a wide character from a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fgetws, fgetws_unlocked—get wide character string from a file or streamSynopsis
#include <wchar.h>wchar_t *fgetws(wchar_t *__restrict ws, int n, FILE *__restrict fp);#define _GNU_SOURCE#include <wchar.h>wchar_t *fgetws_unlocked(wchar_t *__restrict ws, int n, FILE *__restrict fp);#include <wchar.h>wchar_t *_fgetws_r(struct _reent *ptr, wchar_t *ws, int n, FILE *fp);#include <wchar.h>wchar_t *_fgetws_unlocked_r(struct _reent *ptr, wchar_t *ws, int n, FILE *fp);
Description
Reads at most n-1 wide characters from fp until a newlineis found. The wide characters including to the newline are storedin ws. The buffer is terminated with a 0.
fgetws_unlocked is a non-thread-safe version of fgetws.fgetws_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfgetws_unlocked is equivalent to fgetws.
The _fgetws_r and _fgetws_unlocked_r functions are simply reentrantversion of the above and are passed an additional reentrancy structurepointer: ptr.
Returnsfgetws returns the buffer passed to it, with the datafilled in. If end of file occurs with some data alreadyaccumulated, the data is returned with no other indication. Ifno data are read, NULL is returned instead.
Portabilityfgetws is required by C99 and POSIX.1-2001.
fgetws_unlocked is a GNU extension.
Next: fmemopen—open a stream around a fixed-length string, Previous: fgetws, fgetws_unlocked—get wide character string from a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fileno, fileno_unlocked—return file descriptor associated with streamSynopsis
#include <stdio.h>int fileno(FILE *fp);#define _BSD_SOURCE#include <stdio.h>int fileno_unlocked(FILE *fp);
Description
You can use fileno to return the file descriptor identified by fp.
fileno_unlocked is a non-thread-safe version of fileno.fileno_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfileno_unlocked is equivalent to fileno.
Returnsfileno returns a non-negative integer when successful.If fp is not an open stream, fileno returns -1.
Portabilityfileno is not part of ANSI C.POSIX requires fileno.
fileno_unlocked is a BSD extension also provided by GNU libc.
Supporting OS subroutines required: none.
Next: fopen—open a file, Previous: fileno, fileno_unlocked—return file descriptor associated with stream, Up: Input and Output (stdio.h)   [Contents][Index]
fmemopen—open a stream around a fixed-length stringSynopsis
#include <stdio.h>FILE *fmemopen(void *restrict buf, size_t size, const char *restrict mode);
Descriptionfmemopen creates a seekable FILE stream that wraps afixed-length buffer of size bytes starting at buf. The streamis opened with mode treated as in fopen, where append modestarts writing at the first NUL byte. If buf is NULL, thensize bytes are automatically provided as if by malloc, withthe initial size of 0, and mode must contain + so that datacan be read after it is written.
The stream maintains a current position, which moves according tobytes read or written, and which can be one past the end of the array.The stream also maintains a current file size, which is never greaterthan size. If mode starts with r, the position starts at0, and file size starts at size if buf was provided. Ifmode starts with w, the position and file size start at 0,and if buf was provided, the first byte is set to NUL. Ifmode starts with a, the position and file size start at thelocation of the first NUL byte, or else size if buf wasprovided.
When reading, NUL bytes have no significance, and reads cannot exceedthe current file size. When writing, the file size can increase up tosize as needed, and NUL bytes may be embedded in the stream (seeopen_memstream for an alternative that automatically enlarges thebuffer). When the stream is flushed or closed after a write thatchanged the file size, a NUL byte is written at the current positionif there is still room; if the stream is not also open for reading, aNUL byte is additionally written at the last byte of buf when thestream has exceeded size, so that a write-only buf is alwaysNUL-terminated when the stream is flushed or closed (and the initialsize should take this into account). It is not possible to seekoutside the bounds of size. A NUL byte written during a flush isrestored to its previous value when seeking elsewhere in the string.
Returns
The return value is an open FILE pointer on success. On error,NULL is returned, and errno will be set to EINVAL if sizeis zero or mode is invalid, ENOMEM if buf was NULL and memorycould not be allocated, or EMFILE if too many streams are alreadyopen.
Portability
This function is being added to POSIX 200x, but is not in POSIX 2001.
Supporting OS subroutines required: sbrk.
Next: fopencookie—open a stream with custom callbacks, Previous: fmemopen—open a stream around a fixed-length string, Up: Input and Output (stdio.h)   [Contents][Index]
fopen—open a fileSynopsis
#include <stdio.h>FILE *fopen(const char *file, const char *mode);FILE *_fopen_r(struct _reent *reent, const char *file, const char *mode);
Descriptionfopen initializes the data structures needed to read or write afile. Specify the file’s name as the string at file, and the kindof access you need to the file with the string at mode.
The alternate function _fopen_r is a reentrant version.The extra argument reent is a pointer to a reentrancy structure.
Three fundamental kinds of access are available: read, write, and append.*mode must begin with one of the three characters ‘r’,‘w’, or ‘a’, to select one of these:
rOpen the file for reading; the operation will fail if the file doesnot exist, or if the host system does not permit you to read it.
wOpen the file for writing from the beginning of the file:effectively, this always creates a new file. If the file whose name youspecified already existed, its old contents are discarded.
aOpen the file for appending data, that is writing from the end offile. When you open a file this way, all data always goes to thecurrent end of file; you cannot change this using fseek.
Some host systems distinguish between “binary” and “text” files.Such systems may perform data transformations on data written to, orread from, files opened as “text”.If your system is one of these, then you can append a ‘b’ to anyof the three modes above, to specify that you are opening the file asa binary file (the default is to open the file as a text file).
‘rb’, then, means “read binary”; ‘wb’, “write binary”; and‘ab’, “append binary”.
To make C programs more portable, the ‘b’ is accepted on allsystems, whether or not it makes a difference.
Finally, you might need to both read and write from the same file.You can also append a ‘+’ to any of the three modes, to permitthis. (If you want to append both ‘b’ and ‘+’, you can do itin either order: for example, "rb+" means the same thing as"r+b" when used as a mode string.)
Use "r+" (or "rb+") to permit reading and writing anywhere inan existing file, without discarding any data; "w+" (or "wb+")to create a new file (or begin by discarding all data from an old one)that permits reading and writing anywhere in it; and "a+" (or"ab+") to permit reading anywhere in an existing file, but writingonly at the end.
Returnsfopen returns a file pointer which you can use for other fileoperations, unless the file you requested could not be opened; in thatsituation, the result is NULL. If the reason for failure was aninvalid string at mode, errno is set to EINVAL.
Portabilityfopen is required by ANSI C.
Supporting OS subroutines required: close, fstat, isatty,lseek, open, read, sbrk, write.
Next: fpurge—discard pending file I/O, Previous: fopen—open a file, Up: Input and Output (stdio.h)   [Contents][Index]
fopencookie—open a stream with custom callbacksSynopsis
#include <stdio.h>FILE *fopencookie(const void *cookie, const char *mode, cookie_io_functions_t functions);
Descriptionfopencookie creates a FILE stream where I/O is performed usingcustom callbacks. The callbacks are registered via the structure:
typedef ssize_t (*cookie_read_function_t)(void *_cookie, char *_buf,size_t _n);typedef ssize_t (*cookie_write_function_t)(void *_cookie,const char *_buf, size_t _n);typedef int (*cookie_seek_function_t)(void *_cookie, off_t *_off,int _whence);typedef int (*cookie_close_function_t)(void *_cookie);
typedef struct	{	cookie_read_function_t	*read;	cookie_write_function_t *write;	cookie_seek_function_t	*seek;	cookie_close_function_t *close;	} cookie_io_functions_t;The stream is opened with mode treated as in fopen. Thecallbacks functions.read and functions.write may only be NULLwhen mode does not require them.
functions.read should return -1 on failure, or else the number ofbytes read (0 on EOF). It is similar to read, except thatcookie will be passed as the first argument.
functions.write should return -1 on failure, or else the number ofbytes written. It is similar to write, except that cookiewill be passed as the first argument.
functions.seek should return -1 on failure, and 0 on success, with_off set to the current file position. It is a cross betweenlseek and fseek, with the _whence argument interpreted inthe same manner. A NULL functions.seek makes the stream behavesimilarly to a pipe in relation to stdio functions that requirepositioning.
functions.close should return -1 on failure, or 0 on success. Itis similar to close, except that cookie will be passed as thefirst argument. A NULL functions.close merely flushes all datathen lets fclose succeed. A failed close will still invalidatethe stream.
Read and write I/O functions are allowed to change the underlyingbuffer on fully buffered or line buffered streams by callingsetvbuf. They are also not required to completely fill or emptythe buffer. They are not, however, allowed to change streams fromunbuffered to buffered or to change the state of the line bufferingflag. They must also be prepared to have read or write calls occur onbuffers other than the one most recently specified.
Returns
The return value is an open FILE pointer on success. On error,NULL is returned, and errno will be set to EINVAL if afunction pointer is missing or mode is invalid, ENOMEM if thestream cannot be created, or EMFILE if too many streams are alreadyopen.
Portability
This function is a newlib extension, copying the prototype from Linux.It is not portable. See also the funopen interface from BSD.
Supporting OS subroutines required: sbrk.
Next: fputc, fputc_unlocked—write a character on a stream or file, Previous: fopencookie—open a stream with custom callbacks, Up: Input and Output (stdio.h)   [Contents][Index]
fpurge—discard pending file I/OSynopsis
#include <stdio.h>int fpurge(FILE *fp);int _fpurge_r(struct _reent *reent, FILE *fp);#include <stdio.h>#include <stdio_ext.h>void __fpurge(FILE *fp);
Description
Use fpurge to clear all buffers of the given stream. For outputstreams, this discards data not yet written to disk. For input streams,this discards any data from ungetc and any data retrieved from diskbut not yet read via getc. This is more severe than fflush,and generally is only needed when manually altering the underlying filedescriptor of a stream.
__fpurge behaves exactly like fpurge but does not return a value.
The alternate function _fpurge_r is a reentrant version, where theextra argument reent is a pointer to a reentrancy structure, andfp must not be NULL.
Returnsfpurge returns 0 unless fp is not valid, in which case itreturns EOF and sets errno.
Portability
These functions are not portable to any standard.
No supporting OS subroutines are required.
Next: fputs, fputs_unlocked—write a character string in a file or stream, Previous: fpurge—discard pending file I/O, Up: Input and Output (stdio.h)   [Contents][Index]
fputc, fputc_unlocked—write a character on a stream or fileSynopsis
#include <stdio.h>int fputc(int ch, FILE *fp);#define _BSD_SOURCE#include <stdio.h>int fputc_unlocked(int ch, FILE *fp);#include <stdio.h>int _fputc_r(struct _rent *ptr, int ch, FILE *fp);#include <stdio.h>int _fputc_unlocked_r(struct _rent *ptr, int ch, FILE *fp);
Descriptionfputc converts the argument ch from an int to anunsigned char, then writes it to the file or stream identified byfp.
If the file was opened with append mode (or if the stream cannotsupport positioning), then the new character goes at the end of thefile or stream. Otherwise, the new character is written at thecurrent value of the position indicator, and the position indicatoroadvances by one.
For a macro version of this function, see putc.
fputc_unlocked is a non-thread-safe version of fputc.fputc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfputc_unlocked is equivalent to fputc.
The _fputc_r and _fputc_unlocked_r functions are simply reentrantversions of the above that take an additional reentrant structureargument: ptr.
Returns
If successful, fputc returns its argument ch. If an errorintervenes, the result is EOF. You can use ‘ferror(fp)’ toquery for errors.
Portabilityfputc is required by ANSI C.
fputc_unlocked is a BSD extension also provided by GNU libc.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fputwc, putwc, fputwc_unlocked, putwc_unlocked—write a wide character on a stream or file, Previous: fputc, fputc_unlocked—write a character on a stream or file, Up: Input and Output (stdio.h)   [Contents][Index]
fputs, fputs_unlocked—write a character string in a file or streamSynopsis
#include <stdio.h>int fputs(const char *restrict s, FILE *restrict fp);#define _GNU_SOURCE#include <stdio.h>int fputs_unlocked(const char *restrict s, FILE *restrict fp);#include <stdio.h>int _fputs_r(struct _reent *ptr, const char *restrict s, FILE *restrict fp);#include <stdio.h>int _fputs_unlocked_r(struct _reent *ptr, const char *restrict s, FILE *restrict fp);
Descriptionfputs writes the string at s (but without the trailing null)to the file or stream identified by fp.
fputs_unlocked is a non-thread-safe version of fputs.fputs_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfputs_unlocked is equivalent to fputs.
_fputs_r and _fputs_unlocked_r are simply reentrant versions of theabove that take an additional reentrant struct pointer argument: ptr.
Returns
If successful, the result is 0; otherwise, the result is EOF.
Portability
ANSI C requires fputs, but does not specify that the result onsuccess must be 0; any non-negative value is permitted.
fputs_unlocked is a GNU extension.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fputws, fputws_unlocked—write a wide character string in a file or stream, Previous: fputs, fputs_unlocked—write a character string in a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fputwc, putwc, fputwc_unlocked, putwc_unlocked—write a wide character on a stream or fileSynopsis
#include <stdio.h>#include <wchar.h>wint_t fputwc(wchar_t wc, FILE *fp);#define _GNU_SOURCE#include <stdio.h>#include <wchar.h>wint_t fputwc_unlocked(wchar_t wc, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _fputwc_r(struct _reent *ptr, wchar_t wc, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _fputwc_unlocked_r(struct _reent *ptr, wchar_t wc, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t putwc(wchar_t wc, FILE *fp);#define _GNU_SOURCE#include <stdio.h>#include <wchar.h>wint_t putwc_unlocked(wchar_t wc, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _putwc_r(struct _reent *ptr, wchar_t wc, FILE *fp);#include <stdio.h>#include <wchar.h>wint_t _putwc_unlocked_r(struct _reent *ptr, wchar_t wc, FILE *fp);
Descriptionfputwc writes the wide character argument wc to the file orstream identified by fp.
If the file was opened with append mode (or if the stream cannotsupport positioning), then the new wide character goes at the end of thefile or stream. Otherwise, the new wide character is written at thecurrent value of the position indicator, and the position indicatoroadvances by one.
fputwc_unlocked is a non-thread-safe version of fputwc.fputwc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfputwc_unlocked is equivalent to fputwc.
The putwc and putwc_unlocked functions or macros function identicallyto fputwc and fputwc_unlocked. They may be implemented as a macro, andmay evaluate its argument more than once. There is no reason ever to use them.
The _fputwc_r, _putwc_r, _fputwc_unlocked_r, and_putwc_unlocked_r functions are simply reentrant versions of the abovethat take an additional reentrant structure argument: ptr.
Returns
If successful, fputwc and putwc return their argument wc.If an error intervenes, the result is EOF. You can use‘ferror(fp)’ to query for errors.
Portabilityfputwc and putwc are required by C99 and POSIX.1-2001.
fputwc_unlocked and putwc_unlocked are GNU extensions.
Next: fread, fread_unlocked—read array elements from a file, Previous: fputwc, putwc, fputwc_unlocked, putwc_unlocked—write a wide character on a stream or file, Up: Input and Output (stdio.h)   [Contents][Index]
fputws, fputws_unlocked—write a wide character string in a file or streamSynopsis
#include <wchar.h>int fputws(const wchar_t *__restrict ws, FILE *__restrict fp);#define _GNU_SOURCE#include <wchar.h>int fputws_unlocked(const wchar_t *__restrict ws, FILE *__restrict fp);#include <wchar.h>int _fputws_r(struct _reent *ptr, const wchar_t *ws, FILE *fp);#include <wchar.h>int _fputws_unlocked_r(struct _reent *ptr, const wchar_t *ws, FILE *fp);
Descriptionfputws writes the wide character string at ws (but without thetrailing null) to the file or stream identified by fp.
fputws_unlocked is a non-thread-safe version of fputws.fputws_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfputws_unlocked is equivalent to fputws.
_fputws_r and _fputws_unlocked_r are simply reentrant versions of theabove that take an additional reentrant struct pointer argument: ptr.
Returns
If successful, the result is a non-negative integer; otherwise, the resultis -1 to indicate an error.
Portabilityfputws is required by C99 and POSIX.1-2001.
fputws_unlocked is a GNU extension.
Next: freopen—open a file using an existing file descriptor, Previous: fputws, fputws_unlocked—write a wide character string in a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
fread, fread_unlocked—read array elements from a fileSynopsis
#include <stdio.h>size_t fread(void *restrict buf, size_t size, size_t count, FILE *restrict fp);#define _BSD_SOURCE#include <stdio.h>size_t fread_unlocked(void *restrict buf, size_t size, size_t count, FILE *restrict fp);#include <stdio.h>size_t _fread_r(struct _reent *ptr, void *restrict buf, size_t size, size_t count, FILE *restrict fp);#include <stdio.h>size_t _fread_unlocked_r(struct _reent *ptr, void *restrict buf, size_t size, size_t count, FILE *restrict fp);
Descriptionfread attempts to copy, from the file or stream identified byfp, count elements (each of size size) into memory,starting at buf. fread may copy fewer elements thancount if an error, or end of file, intervenes.
fread also advances the file position indicator (if any) forfp by the number of characters actually read.
fread_unlocked is a non-thread-safe version of fread.fread_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfread_unlocked is equivalent to fread.
_fread_r and _fread_unlocked_r are simply reentrant versions of theabove that take an additional reentrant structure pointer argument: ptr.
Returns
The result of fread is the number of elements it succeeded inreading.
Portability
ANSI C requires fread.
fread_unlocked is a BSD extension also provided by GNU libc.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fseek, fseeko—set file position, Previous: fread, fread_unlocked—read array elements from a file, Up: Input and Output (stdio.h)   [Contents][Index]
freopen—open a file using an existing file descriptorSynopsis
#include <stdio.h>FILE *freopen(const char *restrict file, const char *restrict mode, FILE *restrict fp);FILE *_freopen_r(struct _reent *ptr, const char *restrict file, const char *restrict mode, FILE *restrict fp);
Description
Use this variant of fopen if you wish to specify a particular filedescriptor fp (notably stdin, stdout, or stderr) forthe file.
If fp was associated with another file or stream, freopencloses that other file or stream (but ignores any errors while closingit).
file and mode are used just as in fopen.
If file is NULL, the underlying stream is modified rather thanclosed. The file cannot be given a more permissive access mode (forexample, a mode of "w" will fail on a read-only file descriptor),but can change status such as append or binary mode. If modificationis not possible, failure occurs.
Returns
If successful, the result is the same as the argument fp. If thefile cannot be opened as specified, the result is NULL.
Portability
ANSI C requires freopen.
Supporting OS subroutines required: close, fstat, isatty,lseek, open, read, sbrk, write.
Next: __fsetlocking—set or query locking mode on FILE stream, Previous: freopen—open a file using an existing file descriptor, Up: Input and Output (stdio.h)   [Contents][Index]
fseek, fseeko—set file positionSynopsis
#include <stdio.h>int fseek(FILE *fp, long offset, int whence);int fseeko(FILE *fp, off_t offset, int whence);int _fseek_r(struct _reent *ptr, FILE *fp, long offset, int whence);int _fseeko_r(struct _reent *ptr, FILE *fp, off_t offset, int whence);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fseek/fseeko to set the position for the file identified byfp. The value of offset determines the new position, in oneof three ways selected by the value of whence (defined as macrosin ‘stdio.h’):
SEEK_SET—offset is the absolute file position (an offsetfrom the beginning of the file) desired. offset must be positive.
SEEK_CUR—offset is relative to the current file position.offset can meaningfully be either positive or negative.
SEEK_END—offset is relative to the current end of file.offset can meaningfully be either positive (to increase the sizeof the file) or negative.
See ftell/ftello to determine the current file position.
Returnsfseek/fseeko return 0 when successful. On failure, theresult is EOF. The reason for failure is indicated in errno:either ESPIPE (the stream identified by fp doesn’t supportrepositioning) or EINVAL (invalid file position).
Portability
ANSI C requires fseek.
fseeko is defined by the Single Unix specification.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: fsetpos—restore position of a stream or file, Previous: fseek, fseeko—set file position, Up: Input and Output (stdio.h)   [Contents][Index]
__fsetlocking—set or query locking mode on FILE streamSynopsis
#include <stdio.h>#include <stdio_ext.h>int __fsetlocking(FILE *fp, int type);
Description
This function sets how the stdio functions handle locking of FILE fp.The following values describe type:
FSETLOCKING_INTERNAL is the default state, where stdio functionsautomatically lock and unlock the stream.
FSETLOCKING_BYCALLER means that automatic locking in stdio functionsis disabled. Applications which set this take all responsibility for filelocking themselves.
FSETLOCKING_QUERY returns the current locking mode without changing it.
Returns__fsetlocking returns the current locking mode of fp.
Portability
This function originates from Solaris and is also provided by GNU libc.
No supporting OS subroutines are required.
Next: ftell, ftello—return position in a stream or file, Previous: __fsetlocking—set or query locking mode on FILE stream, Up: Input and Output (stdio.h)   [Contents][Index]
fsetpos—restore position of a stream or fileSynopsis
#include <stdio.h>int fsetpos(FILE *fp, const fpos_t *pos);int _fsetpos_r(struct _reent *ptr, FILE *fp, const fpos_t *pos);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fsetpos to return the file identified by fp to a previousposition *pos (after first recording it with fgetpos).
See fseek for a similar facility.
Returnsfgetpos returns 0 when successful. If fgetpos fails, theresult is 1. The reason for failure is indicated in errno:either ESPIPE (the stream identified by fp doesn’t supportrepositioning) or EINVAL (invalid file position).
Portability
ANSI C requires fsetpos, but does not specify the nature of*pos beyond identifying it as written by fgetpos.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: funopen, fropen, fwopen—open a stream with custom callbacks, Previous: fsetpos—restore position of a stream or file, Up: Input and Output (stdio.h)   [Contents][Index]
ftell, ftello—return position in a stream or fileSynopsis
#include <stdio.h>long ftell(FILE *fp);off_t ftello(FILE *fp);long _ftell_r(struct _reent *ptr, FILE *fp);off_t _ftello_r(struct _reent *ptr, FILE *fp);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
The result of ftell/ftello is the current position for a fileidentified by fp. If you record this result, you can lateruse it with fseek/fseeko to return the file to thisposition. The difference between ftell and ftello is thatftell returns long and ftello returns off_t.
In the current implementation, ftell/ftello simply uses a charactercount to represent the file position; this is the same number thatwould be recorded by fgetpos.
Returnsftell/ftello return the file position, if possible. If they cannot dothis, they return -1L. Failure occurs on streams that do not supportpositioning; the global errno indicates this condition with thevalue ESPIPE.
Portabilityftell is required by the ANSI C standard, but the meaning of itsresult (when successful) is not specified beyond requiring that it beacceptable as an argument to fseek. In particular, otherconforming C implementations may return a different result fromftell than what fgetpos records.
ftello is defined by the Single Unix specification.
No supporting OS subroutines are required.
Next: fwide—set and determine the orientation of a FILE stream, Previous: ftell, ftello—return position in a stream or file, Up: Input and Output (stdio.h)   [Contents][Index]
funopen, fropen, fwopen—open a stream with custom callbacksSynopsis
#include <stdio.h>FILE *funopen(const void *cookie, int (*readfn) (void *cookie, char *buf, int n), int (*writefn) (void *cookie, const char *buf, int n), fpos_t (*seekfn) (void *cookie, fpos_t off, int whence), int (*closefn) (void *cookie));FILE *fropen(const void *cookie, int (*readfn) (void *cookie, char *buf, int n));FILE *fwopen(const void *cookie, int (*writefn) (void *cookie, const char *buf, int n));
Descriptionfunopen creates a FILE stream where I/O is performed usingcustom callbacks. At least one of readfn and writefn must beprovided, which determines whether the stream behaves with mode <"r">,<"w">, or <"r+">.
readfn should return -1 on failure, or else the number of bytesread (0 on EOF). It is similar to read, except that <int> ratherthan <size_t> bounds a transaction size, and cookie will be passedas the first argument. A NULL readfn makes attempts to read thestream fail.
writefn should return -1 on failure, or else the number of byteswritten. It is similar to write, except that <int> rather than<size_t> bounds a transaction size, and cookie will be passed asthe first argument. A NULL writefn makes attempts to write thestream fail.
seekfn should return (fpos_t)-1 on failure, or else the currentfile position. It is similar to lseek, except that cookiewill be passed as the first argument. A NULL seekfn makes thestream behave similarly to a pipe in relation to stdio functions thatrequire positioning. This implementation assumes fpos_t and off_t arethe same type.
closefn should return -1 on failure, or 0 on success. It issimilar to close, except that cookie will be passed as thefirst argument. A NULL closefn merely flushes all data then letsfclose succeed. A failed close will still invalidate the stream.
Read and write I/O functions are allowed to change the underlyingbuffer on fully buffered or line buffered streams by callingsetvbuf. They are also not required to completely fill or emptythe buffer. They are not, however, allowed to change streams fromunbuffered to buffered or to change the state of the line bufferingflag. They must also be prepared to have read or write calls occur onbuffers other than the one most recently specified.
The functions fropen and fwopen are convenience macros aroundfunopen that only use the specified callback.
Returns
The return value is an open FILE pointer on success. On error,NULL is returned, and errno will be set to EINVAL if afunction pointer is missing, ENOMEM if the stream cannot be created,or EMFILE if too many streams are already open.
Portability
This function is a newlib extension, copying the prototype from BSD.It is not portable. See also the fopencookie interface from Linux.
Supporting OS subroutines required: sbrk.
Next: fwrite, fwrite_unlocked—write array elements, Previous: funopen, fropen, fwopen—open a stream with custom callbacks, Up: Input and Output (stdio.h)   [Contents][Index]
fwide—set and determine the orientation of a FILE streamSynopsis
#include <wchar.h>int fwide(FILE *fp, int mode);int _fwide_r(struct _reent *ptr, FILE *fp, int mode);
Description
When mode is zero, the fwide function determines the currentorientation of fp. It returns a value > 0 if fp iswide-character oriented, i.e. if wide character I/O is permitted butchar I/O is disallowed. It returns a value < 0 if fp is byteoriented, i.e. if char I/O is permitted but wide character I/O isdisallowed. It returns zero if fp has no orientation yet; inthis case the next I/O operation might change the orientation (to byteoriented if it is a char I/O operation, or to wide-character orientedif it is a wide character I/O operation).
Once a stream has an orientation, it cannot be changed and persistsuntil the stream is closed, unless the stream is re-opened with freopen,which removes the orientation of the stream.
When mode is non-zero, the fwide function first attempts to setfp’s orientation (to wide-character oriented if mode > 0, or tobyte oriented if mode < 0). It then returns a value denoting thecurrent orientation, as above.
Returns
The fwide function returns fp’s orientation, after possiblychanging it. A return value > 0 means wide-character oriented. A returnvalue < 0 means byte oriented. A return value of zero means undecided.
Portability
C99, POSIX.1-2001.
Next: getc—read a character (macro), Previous: fwide—set and determine the orientation of a FILE stream, Up: Input and Output (stdio.h)   [Contents][Index]
fwrite, fwrite_unlocked—write array elementsSynopsis
#include <stdio.h>size_t fwrite(const void *restrict buf, size_t size, size_t count, FILE *restrict fp);#define _BSD_SOURCE#include <stdio.h>size_t fwrite_unlocked(const void *restrict buf, size_t size, size_t count, FILE *restrict fp);#include <stdio.h>size_t _fwrite_r(struct _reent *ptr, const void *restrict buf, size_t size, size_t count, FILE *restrict fp);#include <stdio.h>size_t _fwrite_unlocked_r(struct _reent *ptr, const void *restrict buf, size_t size, size_t count, FILE *restrict fp);
Descriptionfwrite attempts to copy, starting from the memory locationbuf, count elements (each of size size) into the file orstream identified by fp. fwrite may copy fewer elements thancount if an error intervenes.
fwrite also advances the file position indicator (if any) forfp by the number of characters actually written.
fwrite_unlocked is a non-thread-safe version of fwrite.fwrite_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenfwrite_unlocked is equivalent to fwrite.
_fwrite_r and _fwrite_unlocked_r are simply reentrant versions of theabove that take an additional reentrant structure argument: ptr.
Returns
If fwrite succeeds in writing all the elements you specify, theresult is the same as the argument count. In any event, theresult is the number of complete elements that fwrite copied tothe file.
Portability
ANSI C requires fwrite.
fwrite_unlocked is a BSD extension also provided by GNU libc.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: getc_unlocked—non-thread-safe version of getc (macro), Previous: fwrite, fwrite_unlocked—write array elements, Up: Input and Output (stdio.h)   [Contents][Index]
getc—read a character (macro)Synopsis
#include <stdio.h>int getc(FILE *fp);#include <stdio.h>int _getc_r(struct _reent *ptr, FILE *fp);
Descriptiongetc is a macro, defined in stdio.h. You can use getcto get the next single character from the file or streamidentified by fp. As a side effect, getc advances the file’scurrent position indicator.
For a subroutine version of this macro, see fgetc.
The _getc_r function is simply the reentrant version of getcwhich passes an additional reentrancy structure pointer argument: ptr.
Returns
The next character (read as an unsigned char, and cast toint), unless there is no more data, or the host system reports aread error; in either of these situations, getc returns EOF.
You can distinguish the two situations that cause an EOF result byusing the ferror and feof functions.
Portability
ANSI C requires getc; it suggests, but does not require, thatgetc be implemented as a macro. The standard explicitly permitsmacro implementations of getc to use the argument more than once;therefore, in a portable program, you should not use an expressionwith side effects as the getc argument.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: getchar—read a character (macro), Previous: getc—read a character (macro), Up: Input and Output (stdio.h)   [Contents][Index]
getc_unlocked—non-thread-safe version of getc (macro)Synopsis
#include <stdio.h>int getc_unlocked(FILE *fp);#include <stdio.h>int _getc_unlocked_r(FILE *fp);
Descriptiongetc_unlocked is a non-thread-safe version of getc declared instdio.h. getc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thesefunctions may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the ( FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thengetc_unlocked is equivalent to getc.
The _getc_unlocked_r function is simply the reentrant version ofget_unlocked which passes an additional reentrancy structure pointerargument: ptr.
Returns
See getc.
Portability
POSIX 1003.1 requires getc_unlocked. getc_unlocked may beimplemented as a macro, so arguments should not have side-effects.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write. 
Next: getchar_unlocked—non-thread-safe version of getchar (macro), Previous: getc_unlocked—non-thread-safe version of getc (macro), Up: Input and Output (stdio.h)   [Contents][Index]
getchar—read a character (macro)Synopsis
#include <stdio.h>int getchar(void);int _getchar_r(struct _reent *reent);
Descriptiongetchar is a macro, defined in stdio.h. You can use getcharto get the next single character from the standard input stream.As a side effect, getchar advances the standard input’scurrent position indicator.
The alternate function _getchar_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returns
The next character (read as an unsigned char, and cast toint), unless there is no more data, or the host system reports aread error; in either of these situations, getchar returns EOF.
You can distinguish the two situations that cause an EOF result byusing ‘ferror(stdin)’ and ‘feof(stdin)’.
Portability
ANSI C requires getchar; it suggests, but does not require, thatgetchar be implemented as a macro.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: getdelim—read a line up to a specified line delimiter, Previous: getchar—read a character (macro), Up: Input and Output (stdio.h)   [Contents][Index]
getchar_unlocked—non-thread-safe version of getchar (macro)Synopsis
#include <stdio.h>int getchar_unlocked(void);#include <stdio.h>int _getchar_unlocked_r(struct _reent *ptr);
Descriptiongetchar_unlocked is a non-thread-safe version of getchardeclared in stdio.h. getchar_unlocked may only safely be usedwithin a scope protected by flockfile() (or ftrylockfile()) andfunlockfile(). These functions may safely be used in a multi-threadedprogram if and only if they are called while the invoking thread ownsthe ( FILE *) object, as is the case after a successful call to theflockfile() or ftrylockfile() functions. If threads are disabled,then getchar_unlocked is equivalent to getchar.
The _getchar_unlocked_r function is simply the reentrant version ofgetchar_unlocked which passes an addtional reentrancy structure pointerargument: ptr.
Returns
See getchar.
Portability
POSIX 1003.1 requires getchar_unlocked. getchar_unlocked maybe implemented as a macro.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write. 
Next: getline—read a line from a file, Previous: getchar_unlocked—non-thread-safe version of getchar (macro), Up: Input and Output (stdio.h)   [Contents][Index]
getdelim—read a line up to a specified line delimiterSynopsis
#include <stdio.h>int getdelim(char **bufptr, size_t *n, int delim, FILE *fp);
Descriptiongetdelim reads a file fp up to and possibly including a specifieddelimiter delim. The line is read into a buffer pointed toby bufptr and designated with size *n. If the buffer isnot large enough, it will be dynamically grown by getdelim.As the buffer is grown, the pointer to the size n will beupdated.
Returnsgetdelim returns -1 if no characters were successfully read;otherwise, it returns the number of bytes successfully read.At end of file, the result is nonzero.
Portabilitygetdelim is a glibc extension.
No supporting OS subroutines are directly required.
Next: gets—get character string (obsolete, use fgets instead), Previous: getdelim—read a line up to a specified line delimiter, Up: Input and Output (stdio.h)   [Contents][Index]
getline—read a line from a fileSynopsis
#include <stdio.h>ssize_t getline(char **bufptr, size_t *n, FILE *fp);
Descriptiongetline reads a file fp up to and possibly including thenewline character. The line is read into a buffer pointed toby bufptr and designated with size *n. If the buffer isnot large enough, it will be dynamically grown by getdelim.As the buffer is grown, the pointer to the size n will beupdated.
getline is equivalent to getdelim(bufptr, n, ’\n’, fp);
Returnsgetline returns -1 if no characters were successfully read,otherwise, it returns the number of bytes successfully read.at end of file, the result is nonzero.
Portabilitygetline is a glibc extension.
No supporting OS subroutines are directly required.
Next: getw—read a word (int), Previous: getline—read a line from a file, Up: Input and Output (stdio.h)   [Contents][Index]
gets—get character string (obsolete, use fgets instead)Synopsis
#include <stdio.h>char *gets(char *buf);char *_gets_r(struct _reent *reent, char *buf);
Description
Reads characters from standard input until a newline is found.The characters up to the newline are stored in buf. Thenewline is discarded, and the buffer is terminated with a 0.
This is a dangerous function, as it has no way of checkingthe amount of space available in buf. One of the attacksused by the Internet Worm of 1988 used this to overrun abuffer allocated on the stack of the finger daemon andoverwrite the return address, causing the daemon to executecode downloaded into it over the connection.
The alternate function _gets_r is a reentrant version. The extraargument reent is a pointer to a reentrancy structure.
Returnsgets returns the buffer passed to it, with the data filledin. If end of file occurs with some data already accumulated,the data is returned with no other indication. If end of fileoccurs with no data in the buffer, NULL is returned.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: getwchar, getwchar_unlocked—read a wide character from standard input, Previous: gets—get character string (obsolete, use fgets instead), Up: Input and Output (stdio.h)   [Contents][Index]
getw—read a word (int)Synopsis
#include <stdio.h>int getw(FILE *fp);
Descriptiongetw is a function, defined in stdio.h. You can use getwto get the next word from the file or stream identified by fp. Asa side effect, getw advances the file’s current positionindicator.
Returns
The next word (read as an int), unless there is no moredata or the host system reports a read error; in either of thesesituations, getw returns EOF. Since EOF is a validint, you must use ferror or feof to distinguish thesesituations.
Portabilitygetw is a remnant of K&R C; it is not part of any ISO C Standard.fread should be used instead. In fact, this implementation ofgetw is based upon fread.
Supporting OS subroutines required: fread. 
Next: mktemp, mkstemp, mkostemp, mkstemps,, Previous: getw—read a word (int), Up: Input and Output (stdio.h)   [Contents][Index]
getwchar, getwchar_unlocked—read a wide character from standard inputSynopsis
#include <wchar.h>wint_t getwchar(void);#define _GNU_SOURCE#include <wchar.h>wint_t getwchar_unlocked(void);#include <wchar.h>wint_t _getwchar_r(struct _reent *reent);#include <wchar.h>wint_t _getwchar_unlocked_r(struct _reent *reent);
Descriptiongetwchar function or macro is the wide character equivalent ofthe getchar function. You can use getwchar to get the nextwide character from the standard input stream. As a side effect,getwchar advances the standard input’s current position indicator.
getwchar_unlocked is a non-thread-safe version of getwchar.getwchar_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thengetwchar_unlocked is equivalent to getwchar.
The alternate functions _getwchar_r and _getwchar_unlocked_r arereentrant versions of the above. The extra argument reent is a pointer toa reentrancy structure.
Returns
The next wide character cast to wint_t, unless there is no moredata, or the host system reports a read error; in either of thesesituations, getwchar returns WEOF.
You can distinguish the two situations that cause an WEOF result byusing ‘ferror(stdin)’ and ‘feof(stdin)’.
Portabilitygetwchar is required by C99.
getwchar_unlocked is a GNU extension.
Next: open_memstream, open_wmemstream—open a write stream around an arbitrary-length string, Previous: getwchar, getwchar_unlocked—read a wide character from standard input, Up: Input and Output (stdio.h)   [Contents][Index]
mktemp, mkstemp, mkostemp, mkstemps,Synopsis
#include <stdlib.h>char *mktemp(char *path);char *mkdtemp(char *path);int mkstemp(char *path);int mkstemps(char *path, int suffixlen);int mkostemp(char *path, int flags);int mkostemps(char *path, int suffixlen, int flags);char *_mktemp_r(struct _reent *reent, char *path);char *_mkdtemp_r(struct _reent *reent, char *path);int *_mkstemp_r(struct _reent *reent, char *path);int *_mkstemps_r(struct _reent *reent, char *path, int len);int *_mkostemp_r(struct _reent *reent, char *path, int flags);int *_mkostemps_r(struct _reent *reent, char *path, int len, int flags);
Descriptionmktemp, mkstemp, and mkstemps attempt to generate a file namethat is not yet in use for any existing file. mkstemp and mkstempscreate the file and open it for reading and writing; mktemp simplygenerates the file name (making mktemp a security risk). mkostempand mkostemps allow the addition of other open flags, suchas O_CLOEXEC, O_APPEND, or O_SYNC. On platforms with aseparate text mode, mkstemp forces O_BINARY, while mkostempallows the choice between O_BINARY, O_TEXT, or 0 for default.mkdtemp attempts to create a directory instead of a file, with apermissions mask of 0700.
You supply a simple pattern for the generated file name, as the stringat path. The pattern should be a valid filename (including pathinformation if you wish) ending with at least six ‘X’characters. The generated filename will match the leading part of thename you supply, with the trailing ‘X’ characters replaced by somecombination of digits and letters. With mkstemps, the ‘X’characters end suffixlen bytes before the end of the string.
The alternate functions _mktemp_r, _mkdtemp_r, _mkstemp_r,_mkostemp_r, _mkostemps_r, and _mkstemps_r are reentrantversions. The extra argument reent is a pointer to a reentrancystructure.
Returnsmktemp returns the pointer path to the modified stringrepresenting an unused filename, unless it could not generate one, orthe pattern you provided is not suitable for a filename; in that case,it returns NULL. Be aware that there is an inherent race betweengenerating the name and attempting to create a file by that name;you are advised to use O_EXCL|O_CREAT.
mkdtemp returns the pointer path to the modified string if thedirectory was created, otherwise it returns NULL.
mkstemp, mkstemps, mkostemp, and mkostemps return a filedescriptor to the newly created file, unless it could not generate anunused filename, or the pattern you provided is not suitable for afilename; in that case, it returns -1.
Notes
Never use mktemp. The generated filenames are easy to guess andthere’s a race between the test if the file exists and the creationof the file. In combination this makes mktemp prone to attacksand using it is a security risk. Whenever possible use mkstempinstead. It doesn’t suffer the race condition.
Portability
ANSI C does not require either mktemp or mkstemp; the SystemV Interface Definition requires mktemp as of Issue 2. POSIX 2001requires mkstemp, and POSIX 2008 requires mkdtemp whiledeprecating mktemp. mkstemps, mkostemp, and mkostempsare not standardized.
Supporting OS subroutines required: getpid, mkdir, open, stat.
Next: perror—print an error message on standard error, Previous: mktemp, mkstemp, mkostemp, mkstemps,, Up: Input and Output (stdio.h)   [Contents][Index]
open_memstream, open_wmemstream—open a write stream around an arbitrary-length stringSynopsis
#include <stdio.h>FILE *open_memstream(char **restrict buf, size_t *restrict size);#include <wchar.h>FILE *open_wmemstream(wchar_t **restrict buf, size_t *restrict size);
Descriptionopen_memstream creates a seekable, byte-oriented FILE stream thatwraps an arbitrary-length buffer, created as if by malloc. The currentcontents of *buf are ignored; this implementation uses *sizeas a hint of the maximum size expected, but does not fail if the hintwas wrong. The parameters buf and size are later storedthrough following any call to fflush or fclose, set to thecurrent address and usable size of the allocated string; althoughafter fflush, the pointer is only valid until another stream operationthat results in a write. Behavior is undefined if the user alterseither *buf or *size prior to fclose.
open_wmemstream is like open_memstream just with the associatedstream being wide-oriented. The size set in size in subsequentoperations is the number of wide characters.
The stream is write-only, since the user can directly read *bufafter a flush; see fmemopen for a way to wrap a string with areadable stream. The user is responsible for calling free onthe final *buf after fclose.
Any time the stream is flushed, a NUL byte is written at the currentposition (but is not counted in the buffer length), so that the stringis always NUL-terminated after at most *size bytes (or wide charactersin case of open_wmemstream). However, data previously written beyondthe current stream offset is not lost, and the NUL value written during aflush is restored to its previous value when seeking elsewhere in the string.
Returns
The return value is an open FILE pointer on success. On error,NULL is returned, and errno will be set to EINVAL if bufor size is NULL, ENOMEM if memory could not be allocated, orEMFILE if too many streams are already open.
Portability
POSIX.1-2008
Supporting OS subroutines required: sbrk.
Next: putc—write a character (macro), Previous: open_memstream, open_wmemstream—open a write stream around an arbitrary-length string, Up: Input and Output (stdio.h)   [Contents][Index]
perror—print an error message on standard errorSynopsis
#include <stdio.h>void perror(char *prefix);void _perror_r(struct _reent *reent, char *prefix);
Description
Use perror to print (on standard error) an error messagecorresponding to the current value of the global variable errno.Unless you use NULL as the value of the argument prefix, theerror message will begin with the string at prefix, followed by acolon and a space (: ). The remainder of the error message is oneof the strings described for strerror.
The alternate function _perror_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsperror returns no result.
Portability
ANSI C requires perror, but the strings issued vary from oneimplementation to another.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: putc_unlocked—non-thread-safe version of putc (macro), Previous: perror—print an error message on standard error, Up: Input and Output (stdio.h)   [Contents][Index]
putc—write a character (macro)Synopsis
#include <stdio.h>int putc(int ch, FILE *fp);#include <stdio.h>int _putc_r(struct _reent *ptr, int ch, FILE *fp);
Descriptionputc is a macro, defined in stdio.h. putcwrites the argument ch to the file or stream identified byfp, after converting it from an int to an unsigned char.
If the file was opened with append mode (or if the stream cannotsupport positioning), then the new character goes at the end of thefile or stream. Otherwise, the new character is written at thecurrent value of the position indicator, and the position indicatoradvances by one.
For a subroutine version of this macro, see fputc.
The _putc_r function is simply the reentrant version ofputc that takes an additional reentrant structure argument: ptr.
Returns
If successful, putc returns its argument ch. If an errorintervenes, the result is EOF. You can use ‘ferror(fp)’ toquery for errors.
Portability
ANSI C requires putc; it suggests, but does not require, thatputc be implemented as a macro. The standard explicitly permitsmacro implementations of putc to use the fp argument more than once;therefore, in a portable program, you should not use an expressionwith side effects as this argument.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: putchar—write a character (macro), Previous: putc—write a character (macro), Up: Input and Output (stdio.h)   [Contents][Index]
putc_unlocked—non-thread-safe version of putc (macro)Synopsis
#include <stdio.h>int putc_unlocked(int ch, FILE *fp);#include <stdio.h>int _putc_unlocked_r(struct _reent *ptr, int ch, FILE *fp);
Descriptionputc_unlocked is a non-thread-safe version of putc declared instdio.h. putc_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thesefunctions may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the ( FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenputc_unlocked is equivalent to putc.
The function _putc_unlocked_r is simply the reentrant version ofputc_unlocked that takes an additional reentrant structure pointerargument: ptr.
Returns
See putc.
Portability
POSIX 1003.1 requires putc_unlocked. putc_unlocked may beimplemented as a macro, so arguments should not have side-effects.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: putchar_unlocked—non-thread-safe version of putchar (macro), Previous: putc_unlocked—non-thread-safe version of putc (macro), Up: Input and Output (stdio.h)   [Contents][Index]
putchar—write a character (macro)Synopsis
#include <stdio.h>int putchar(int ch);int _putchar_r(struct _reent *reent, int ch);
Descriptionputchar is a macro, defined in stdio.h. putcharwrites its argument to the standard output stream,after converting it from an int to an unsigned char.
The alternate function _putchar_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returns
If successful, putchar returns its argument ch. If an errorintervenes, the result is EOF. You can use ‘ferror(stdin)’ toquery for errors.
Portability
ANSI C requires putchar; it suggests, but does not require, thatputchar be implemented as a macro.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: puts—write a character string, Previous: putchar—write a character (macro), Up: Input and Output (stdio.h)   [Contents][Index]
putchar_unlocked—non-thread-safe version of putchar (macro)Synopsis
#include <stdio.h>int putchar_unlocked(int ch);
Descriptionputchar_unlocked is a non-thread-safe version of putchardeclared in stdio.h. putchar_unlocked may only safely be usedwithin a scope protected by flockfile() (or ftrylockfile()) andfunlockfile(). These functions may safely be used in a multi-threadedprogram if and only if they are called while the invoking thread ownsthe ( FILE *) object, as is the case after a successful call to theflockfile() or ftrylockfile() functions. If threads are disabled,then putchar_unlocked is equivalent to putchar.
Returns
See putchar.
Portability
POSIX 1003.1 requires putchar_unlocked. putchar_unlocked maybe implemented as a macro.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write. 
Next: putw—write a word (int), Previous: putchar_unlocked—non-thread-safe version of putchar (macro), Up: Input and Output (stdio.h)   [Contents][Index]
puts—write a character stringSynopsis
#include <stdio.h>int puts(const char *s);int _puts_r(struct _reent *reent, const char *s);
Descriptionputs writes the string at s (followed by a newline, instead ofthe trailing null) to the standard output stream.
The alternate function _puts_r is a reentrant version. The extraargument reent is a pointer to a reentrancy structure.
Returns
If successful, the result is a nonnegative integer; otherwise, theresult is EOF.
Portability
ANSI C requires puts, but does not specify that the result onsuccess must be 0; any non-negative value is permitted.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: putwchar, putwchar_unlocked—write a wide character to standard output, Previous: puts—write a character string, Up: Input and Output (stdio.h)   [Contents][Index]
putw—write a word (int)Synopsis
#include <stdio.h>int putw(int w, FILE *fp);
Descriptionputw is a function, defined in stdio.h. You can use putwto write a word to the file or stream identified by fp. As a sideeffect, putw advances the file’s current position indicator.
Returns
Zero on success, EOF on failure.
Portabilityputw is a remnant of K&R C; it is not part of any ISO C Standard.fwrite should be used instead. In fact, this implementation ofputw is based upon fwrite.
Supporting OS subroutines required: fwrite.
Next: remove—delete a file’s name, Previous: putw—write a word (int), Up: Input and Output (stdio.h)   [Contents][Index]
putwchar, putwchar_unlocked—write a wide character to standard outputSynopsis
#include <wchar.h>wint_t putwchar(wchar_t wc);#include <wchar.h>wint_t putwchar_unlocked(wchar_t wc);#include <wchar.h>wint_t _putwchar_r(struct _reent *reent, wchar_t wc);#include <wchar.h>wint_t _putwchar_unlocked_r(struct _reent *reent, wchar_t wc);
Description
The putwchar function or macro is the wide-character equivalent ofthe putchar function. It writes the wide character wc to stdout.
putwchar_unlocked is a non-thread-safe version of putwchar.putwchar_unlocked may only safely be used within a scopeprotected by flockfile() (or ftrylockfile()) and funlockfile(). Thisfunction may safely be used in a multi-threaded program if and onlyif they are called while the invoking thread owns the (FILE *)object, as is the case after a successful call to the flockfile() orftrylockfile() functions. If threads are disabled, thenputwchar_unlocked is equivalent to putwchar.
The alternate functions _putwchar_r and _putwchar_unlocked_r arereentrant versions of the above. The extra argument reent is a pointerto a reentrancy structure.
Returns
If successful, putwchar returns its argument wc. If an errorintervenes, the result is EOF. You can use ‘ferror(stdin)’ toquery for errors.
Portabilityputwchar is required by C99.
putwchar_unlocked is a GNU extension.
Next: rename—rename a file, Previous: putwchar, putwchar_unlocked—write a wide character to standard output, Up: Input and Output (stdio.h)   [Contents][Index]
remove—delete a file’s nameSynopsis
#include <stdio.h>int remove(char *filename);int _remove_r(struct _reent *reent, char *filename);
Description
Use remove to dissolve the association between a particularfilename (the string at filename) and the file it represents.After calling remove with a particular filename, you will nolonger be able to open the file by that name.
In this implementation, you may use remove on an open file withouterror; existing file descriptors for the file will continue to accessthe file’s data until the program using them closes the file.
The alternate function _remove_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returnsremove returns 0 if it succeeds, -1 if it fails.
Portability
ANSI C requires remove, but only specifies that the result onfailure be nonzero. The behavior of remove when you call it on anopen file may vary among implementations.
Supporting OS subroutine required: unlink.
Next: rewind—reinitialize a file or stream, Previous: remove—delete a file’s name, Up: Input and Output (stdio.h)   [Contents][Index]
rename—rename a fileSynopsis
#include <stdio.h>int rename(const char *old, const char *new);
Description
Use rename to establish a new name (the string at new) for afile now known by the string at old. After a successfulrename, the file is no longer accessible by the string at old.
If rename fails, the file named *old is unaffected. Theconditions for failure depend on the host operating system.
Returns
The result is either 0 (when successful) or -1 (when the filecould not be renamed).
Portability
ANSI C requires rename, but only specifies that the result onfailure be nonzero. The effects of using the name of an existing fileas *new may vary from one implementation to another.
Supporting OS subroutines required: link, unlink, or rename.
Next: setbuf—specify full buffering for a file or stream, Previous: rename—rename a file, Up: Input and Output (stdio.h)   [Contents][Index]
rewind—reinitialize a file or streamSynopsis
#include <stdio.h>void rewind(FILE *fp);void _rewind_r(struct _reent *ptr, FILE *fp);
Descriptionrewind returns the file position indicator (if any) for the fileor stream identified by fp to the beginning of the file. It alsoclears any error indicator and flushes any pending output.
Returnsrewind does not return a result.
Portability
ANSI C requires rewind.
No supporting OS subroutines are required.
Next: setbuffer—specify full buffering for a file or stream with size, Previous: rewind—reinitialize a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
setbuf—specify full buffering for a file or streamSynopsis
#include <stdio.h>void setbuf(FILE *fp, char *buf);
Descriptionsetbuf specifies that output to the file or stream identified by fpshould be fully buffered. All output for this file will go to abuffer (of size BUFSIZ, specified in ‘stdio.h’). Output willbe passed on to the host system only when the buffer is full, or whenan input operation intervenes.
You may, if you wish, supply your own buffer by passing a pointer toit as the argument buf. It must have size BUFSIZ. You canalso use NULL as the value of buf, to signal that thesetbuf function is to allocate the buffer.
Warnings
You may only use setbuf before performing any file operation otherthan opening the file.
If you supply a non-null buf, you must ensure that the associatedstorage continues to be available until you close the streamidentified by fp.
Returnssetbuf does not return a result.
Portability
Both ANSI C and the System V Interface Definition (Issue 2) requiresetbuf. However, they differ on the meaning of a NULL bufferpointer: the SVID issue 2 specification says that a NULL bufferpointer requests unbuffered output. For maximum portability, avoidNULL buffer pointers.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: setlinebuf—specify line buffering for a file or stream, Previous: setbuf—specify full buffering for a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
setbuffer—specify full buffering for a file or stream with sizeSynopsis
#include <stdio.h>void setbuffer(FILE *fp, char *buf, int size);
Descriptionsetbuffer specifies that output to the file or stream identified byfp should be fully buffered. All output for this file will go to abuffer (of size size). Output will be passed on to the host systemonly when the buffer is full, or when an input operation intervenes.
You may, if you wish, supply your own buffer by passing a pointer toit as the argument buf. It must have size size. You canalso use NULL as the value of buf, to signal that thesetbuffer function is to allocate the buffer.
Warnings
You may only use setbuffer before performing any file operationother than opening the file.
If you supply a non-null buf, you must ensure that the associatedstorage continues to be available until you close the streamidentified by fp.
Returnssetbuffer does not return a result.
Portability
This function comes from BSD not ANSI or POSIX.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: setvbuf—specify file or stream buffering, Previous: setbuffer—specify full buffering for a file or stream with size, Up: Input and Output (stdio.h)   [Contents][Index]
setlinebuf—specify line buffering for a file or streamSynopsis
#include <stdio.h>void setlinebuf(FILE *fp);
Descriptionsetlinebuf specifies that output to the file or stream identified byfp should be line buffered. This causes the file or stream to passon output to the host system at every newline, as well as when thebuffer is full, or when an input operation intervenes.
Warnings
You may only use setlinebuf before performing any file operationother than opening the file.
Returnssetlinebuf returns as per setvbuf.
Portability
This function comes from BSD not ANSI or POSIX.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: siprintf, fiprintf, iprintf, sniprintf, asiprintf, asniprintf—format output (integer only), Previous: setlinebuf—specify line buffering for a file or stream, Up: Input and Output (stdio.h)   [Contents][Index]
setvbuf—specify file or stream bufferingSynopsis
#include <stdio.h>int setvbuf(FILE *fp, char *buf, int mode, size_t size);
Description
Use setvbuf to specify what kind of buffering you want for thefile or stream identified by fp, by using one of the followingvalues (from stdio.h) as the mode argument:
_IONBFDo not use a buffer: send output directly to the host system for thefile or stream identified by fp.
_IOFBFUse full output buffering: output will be passed on to the host systemonly when the buffer is full, or when an input operation intervenes.
_IOLBFUse line buffering: pass on output to the host system at everynewline, as well as when the buffer is full, or when an inputoperation intervenes.
Use the size argument to specify how large a buffer you wish. Youcan supply the buffer itself, if you wish, by passing a pointer to asuitable area of memory as buf. Otherwise, you may pass NULLas the buf argument, and setvbuf will allocate the buffer.
Warnings
You may only use setvbuf before performing any file operation otherthan opening the file.
If you supply a non-null buf, you must ensure that the associatedstorage continues to be available until you close the streamidentified by fp.
Returns
A 0 result indicates success, EOF failure (invalid mode orsize can cause failure).
Portability
Both ANSI C and the System V Interface Definition (Issue 2) requiresetvbuf. However, they differ on the meaning of a NULL bufferpointer: the SVID issue 2 specification says that a NULL bufferpointer requests unbuffered output. For maximum portability, avoidNULL buffer pointers.
Both specifications describe the result on failure only as anonzero value.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: siscanf, fiscanf, iscanf—scan and format non-floating input, Previous: setvbuf—specify file or stream buffering, Up: Input and Output (stdio.h)   [Contents][Index]
siprintf, fiprintf, iprintf, sniprintf, asiprintf, asniprintf—format output (integer only)Synopsis
#include <stdio.h>int iprintf(const char *format, ...);int fiprintf(FILE *fd, const char *format , ...);int siprintf(char *str, const char *format, ...);int sniprintf(char *str, size_t size, const char *format, ...);int asiprintf(char **strp, const char *format, ...);char *asniprintf(char *str, size_t *size, const char *format, ...);int _iprintf_r(struct _reent *ptr, const char *format, ...);int _fiprintf_r(struct _reent *ptr, FILE *fd, const char *format, ...);int _siprintf_r(struct _reent *ptr, char *str, const char *format, ...);int _sniprintf_r(struct _reent *ptr, char *str, size_t size, const char *format, ...);int _asiprintf_r(struct _reent *ptr, char **strp, const char *format, ...);char *_asniprintf_r(struct _reent *ptr, char *str, size_t *size, const char *format, ...);
Descriptioniprintf, fiprintf, siprintf, sniprintf,asiprintf, and asniprintf are the same as printf,fprintf, sprintf, snprintf, asprintf, andasnprintf, respectively, except that they restrict usageto non-floating-point format specifiers.
_iprintf_r, _fiprintf_r, _asiprintf_r,_siprintf_r, _sniprintf_r, _asniprintf_r aresimply reentrant versions of the functions above.
Returns
Similar to printf, fprintf, sprintf, snprintf, asprintf,and asnprintf.
Portabilityiprintf, fiprintf, siprintf, sniprintf, asiprintf,and asniprintf are newlib extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: sprintf, fprintf, printf, snprintf, asprintf, asnprintf—format output, Previous: siprintf, fiprintf, iprintf, sniprintf, asiprintf, asniprintf—format output (integer only), Up: Input and Output (stdio.h)   [Contents][Index]
siscanf, fiscanf, iscanf—scan and format non-floating inputSynopsis
#include <stdio.h>int iscanf(const char *format, ...);int fiscanf(FILE *fd, const char *format, ...);int siscanf(const char *str, const char *format, ...);int _iscanf_r(struct _reent *ptr, const char *format, ...);int _fiscanf_r(struct _reent *ptr, FILE *fd, const char *format, ...);int _siscanf_r(struct _reent *ptr, const char *str, const char *format, ...);
Descriptioniscanf, fiscanf, and siscanf are the same asscanf, fscanf, and sscanf respectively, only thatthey restrict the available formats to non-floating-pointformat specifiers.
The routines _iscanf_r, _fiscanf_r, and _siscanf_r are reentrantversions of iscanf, fiscanf, and siscanf that take an additionalfirst argument pointing to a reentrancy structure.
Returnsiscanf returns the number of input fields successfullyscanned, converted and stored; the return value doesnot include scanned fields which were not stored.
If iscanf attempts to read at end-of-file, the returnvalue is EOF.
If no fields were stored, the return value is 0.
Portabilityiscanf, fiscanf, and siscanf are newlib extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: sscanf, fscanf, scanf—scan and format input, Previous: siscanf, fiscanf, iscanf—scan and format non-floating input, Up: Input and Output (stdio.h)   [Contents][Index]
sprintf, fprintf, printf, snprintf, asprintf, asnprintf—format outputSynopsis
#include <stdio.h>int printf(const char *restrict format, ...);int fprintf(FILE *restrict fd, const char *restrict format, ...);int sprintf(char *restrict str, const char *restrict format, ...);int snprintf(char *restrict str, size_t size, const char *restrict format, ...);int asprintf(char **restrict strp, const char *restrict format, ...);char *asnprintf(char *restrict str, size_t *restrict size, const char *restrict format, ...);int _printf_r(struct _reent *ptr, const char *restrict format, ...);int _fprintf_r(struct _reent *ptr, FILE *restrict fd, const char *restrict format, ...);int _sprintf_r(struct _reent *ptr, char *restrict str, const char *restrict format, ...);int _snprintf_r(struct _reent *ptr, char *restrict str, size_t size, const char *restrict format, ...);int _asprintf_r(struct _reent *ptr, char **restrict strp, const char *restrict format, ...);char *_asnprintf_r(struct _reent *ptr, char *restrict str, size_t *restrict size, const char *restrict format, ...);
Descriptionprintf accepts a series of arguments, applies to each aformat specifier from *format, and writes theformatted data to stdout, without a terminating NULcharacter. The behavior of printf is undefined if thereare not enough arguments for the format. printf returnswhen it reaches the end of the format string. If there aremore arguments than the format requires, excess arguments areignored.
fprintf is like printf, except that output is directedto the stream fd rather than stdout.
sprintf is like printf, except that output is directedto the buffer str, and a terminating NUL is output.Behavior is undefined if more output is generated than thebuffer can hold.
snprintf is like sprintf, except that output islimited to at most size bytes, including the terminatingNUL. As a special case, if size is 0, str can beNULL, and snprintf merely calculates how many bytes wouldbe printed.
asprintf is like sprintf, except that the output isstored in a dynamically allocated buffer, pstr, whichshould be freed later with free.
asnprintf is like sprintf, except that the return typeis either the original str if it was large enough, or adynamically allocated string if the output exceeds *size;the length of the result is returned in *size. Whendynamic allocation occurs, the contents of the originalstr may have been modified.
For sprintf, snprintf, and asnprintf, the behavioris undefined if the output *str overlaps with one ofthe arguments. Behavior is also undefined if the argument for%n within *format overlaps another argument.
format is a pointer to a character string containing twotypes of objects: ordinary characters (other than %),which are copied unchanged to the output, and conversionspecifications, each of which is introduced by %. (Toinclude % in the output, use %% in the format string.)A conversion specification has the following form:
%[pos][flags][width][.prec][size]type
The fields of the conversion specification have the followingmeanings:
Conversions normally consume arguments in the order that theyare presented. However, it is possible to consume argumentsout of order, and reuse an argument for more than oneconversion specification (although the behavior is undefinedif the same argument is requested with different types), byspecifying pos, which is a decimal integer followed by’$’. The integer must be between 1 and <NL_ARGMAX> fromlimits.h, and if argument %n$ is requested, all earlierarguments must be requested somewhere within format. Ifpositional parameters are used, then all conversionspecifications except for %% must specify a position.This positional parameters method is a POSIX extension to the Cstandard definition for the functions.
flags is an optional sequence of characters which controloutput justification, numeric signs, decimal points, trailingzeros, and octal and hex prefixes. The flag characters areminus (-), plus (+), space ( ), zero (0), sharp(#), and quote ('). They can appear in anycombination, although not all flags can be used for allconversion specification types.
'A POSIX extension to the C standard. However, thisimplementation presently treats it as a no-op, whichis the default behavior for the C locale, anyway. (Ifit did what it is supposed to, when type were i,d, u, f, F, g, or G, theinteger portion of the conversion would be formattedwith thousands’ grouping wide characters.)
-The result of the conversion is leftjustified, and the right is padded withblanks. If you do not use this flag, theresult is right justified, and padded on theleft.
+The result of a signed conversion (asdetermined by type of d, i, a,A, e, E, f, F, g, orG) will always begin with a plus or minussign. (If you do not use this flag, positivevalues do not begin with a plus sign.)
" " (space)If the first character of a signed conversionspecification is not a sign, or if a signedconversion results in no characters, theresult will begin with a space. If the space( ) flag and the plus (+) flag bothappear, the space flag is ignored.
0If the type character is d, i,o, u, x, X, a, A,e, E, f, F, g, or G: leadingzeros are used to pad the field width(following any indication of sign or base); nospaces are used for padding. If the zero(0) and minus (-) flags both appear,the zero (0) flag will be ignored. Ford, i, o, u, x, and Xconversions, if a precision prec isspecified, the zero (0) flag is ignored.
Note that 0 is interpreted as a flag, notas the beginning of a field width.
#The result is to be converted to analternative form, according to the typecharacter.
The alternative form output with the # flag depends on the typecharacter:
oIncreases precision to force the firstdigit of the result to be a zero.
xA non-zero result will have a 0xprefix.
XA non-zero result will have a 0Xprefix.
a, A, e, E, f, or FThe result will always contain adecimal point even if no digits followthe point. (Normally, a decimal pointappears only if a digit follows it.)Trailing zeros are removed.
g or GThe result will always contain adecimal point even if no digits followthe point. Trailing zeros are notremoved.
all othersUndefined.
width is an optional minimum field width. You caneither specify it directly as a decimal integer, orindirectly by using instead an asterisk (*), inwhich case an int argument is used as the fieldwidth. If positional arguments are used, then thewidth must also be specified positionally as *m$,with m as a decimal integer. Negative field widthsare treated as specifying the minus (-) flag forleft justfication, along with a positive field width.The resulting format may be wider than the specifiedwidth.
prec is an optional field; if present, it isintroduced with ‘.’ (a period). You can specifythe precision either directly as a decimal integer orindirectly by using an asterisk (*), in which casean int argument is used as the precision. Ifpositional arguments are used, then the precision mustalso be specified positionally as *m$, with m as adecimal integer. Supplying a negative precision isequivalent to omitting the precision. If only aperiod is specified the precision is zero. The effectdepends on the conversion type.
d, i, o, u, x, or XMinimum number of digits to appear. If noprecision is given, defaults to 1.
a or ANumber of digits to appear after the decimalpoint. If no precision is given, theprecision defaults to the minimum needed foran exact representation.
e, E, f or FNumber of digits to appear after the decimalpoint. If no precision is given, theprecision defaults to 6.
g or GMaximum number of significant digits. Aprecision of 0 is treated the same as aprecision of 1. If no precision is given, theprecision defaults to 6.
s or SMaximum number of characters to print from thestring. If no precision is given, the entirestring is printed.
all othersundefined.
size is an optional modifier that changes the datatype that the corresponding argument has. Behavior isunspecified if a size is given that does not match thetype.
hhWith d, i, o, u, x, orX, specifies that the argument should beconverted to a signed char or unsignedchar before printing.
With n, specifies that the argument is apointer to a signed char.
hWith d, i, o, u, x, orX, specifies that the argument should beconverted to a short or unsigned shortbefore printing.
With n, specifies that the argument is apointer to a short.
lWith d, i, o, u, x, orX, specifies that the argument is along or unsigned long.
With c, specifies that the argument hastype wint_t.
With s, specifies that the argument is apointer to wchar_t.
With n, specifies that the argument is apointer to a long.
With a, A, e, E, f, F,g, or G, has no effect (because ofvararg promotion rules, there is no need todistinguish between float and double).
llWith d, i, o, u, x, orX, specifies that the argument is along long or unsigned long long.
With n, specifies that the argument is apointer to a long long.
jWith d, i, o, u, x, orX, specifies that the argument is anintmax_t or uintmax_t.
With n, specifies that the argument is apointer to an intmax_t.
zWith d, i, o, u, x, orX, specifies that the argument is a size_t.
With n, specifies that the argument is apointer to a size_t.
tWith d, i, o, u, x, orX, specifies that the argument is aptrdiff_t.
With n, specifies that the argument is apointer to a ptrdiff_t.
LWith a, A, e, E, f, F,g, or G, specifies that the argumentis a long double.
type specifies what kind of conversion printfperforms. Here is a table of these:
%Prints the percent character (%).
cPrints arg as single character. If thel size specifier is in effect, a multibytecharacter is printed.
CShort for %lc. A POSIX extension to the C standard.
sPrints the elements of a pointer to charuntil the precision or a null character isreached. If the l size specifier is ineffect, the pointer is to an array ofwchar_t, and the string is converted tomultibyte characters before printing.
SShort for %ls. A POSIX extension to the C standard.
d or iPrints a signed decimal integer; takes anint. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
DNewlib extension, short for %ld.
oPrints an unsigned octal integer; takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
ONewlib extension, short for %lo.
uPrints an unsigned decimal integer; takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
UNewlib extension, short for %lu.
xPrints an unsigned hexadecimal integer (usingabcdef as digits beyond 9); takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
XLike x, but uses ABCDEF as digitsbeyond 9.
fPrints a signed value of the form[-]9999.9999, with the precisiondetermining how many digits follow the decimalpoint; takes a double (remember thatfloat promotes to double as a vararg).The low order digit is rounded to even. Ifthe precision results in at most DECIMAL_DIGdigits, the result is rounded correctly; ifmore than DECIMAL_DIG digits are printed, theresult is only guaranteed to round back to theoriginal value.
If the value is infinite, the result isinf, and no zero padding is performed. Ifthe value is not a number, the result isnan, and no zero padding is performed.
FLike f, but uses INF and NAN fornon-finite numbers.
ePrints a signed value of the form[-]9.9999e[+|-]999; takes a double.The digit before the decimal point is non-zeroif the value is non-zero. The precisiondetermines how many digits appear between. and e, and the exponent alwayscontains at least two digits. The value zerohas an exponent of zero. If the value is notfinite, it is printed like f.
ELike e, but using E to introduce theexponent, and like F for non-finitevalues.
gPrints a signed value in either f or eform, based on the given value andprecision—an exponent less than -4 orgreater than the precision selects the eform. Trailing zeros and the decimal pointare printed only if necessary; takes adouble.
GLike g, except use F or E form.
aPrints a signed value of the form[-]0x1.ffffp[+|-]9; takes a double.The letters abcdef are used for digitsbeyond 9. The precision determines howmany digits appear after the decimal point.The exponent contains at least one digit, andis a decimal value representing the power of2; a value of 0 has an exponent of 0.Non-finite values are printed like f.
ALike a, except uses X, P, andABCDEF instead of lower case.
nTakes a pointer to int, and stores a countof the number of bytes written so far. Nooutput is created.
pTakes a pointer to void, and prints it inan implementation-defined format. Thisimplementation is similar to %#tx), exceptthat 0x appears even for the NULL pointer.
mPrints the output of strerror(errno); noargument is required. A GNU extension.
_printf_r, _fprintf_r, _asprintf_r,_sprintf_r, _snprintf_r, _asnprintf_r are simplyreentrant versions of the functions above.
Returns
On success, sprintf and asprintf return the number of bytes inthe output string, except the concluding NUL is not counted.snprintf returns the number of bytes that would be in the outputstring, except the concluding NUL is not counted. printf andfprintf return the number of characters transmitted.asnprintf returns the original str if there was enough room,otherwise it returns an allocated string.
If an error occurs, the result of printf, fprintf,snprintf, and asprintf is a negative value, and the result ofasnprintf is NULL. No error returns occur for sprintf. Forprintf and fprintf, errno may be set according tofputc. For asprintf and asnprintf, errno may be setto ENOMEM if allocation fails, and for snprintf, errno may beset to EOVERFLOW if size or the output length exceeds INT_MAX.
Bugs
The “”’ (quote) flag does not work when locale’s thousands_sep is not empty.
Portability
ANSI C requires printf, fprintf, sprintf, andsnprintf. asprintf and asnprintf are newlib extensions.
The ANSI C standard specifies that implementations must support atleast formatted output of up to 509 characters. This implementationhas no inherent limit.
Depending on how newlib was configured, not all format specifiers aresupported.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: stdio_ext,__fbufsize,__fpending,__flbf,__freadable,__fwritable,__freading,__fwriting—access internals of FILE structure, Previous: sprintf, fprintf, printf, snprintf, asprintf, asnprintf—format output, Up: Input and Output (stdio.h)   [Contents][Index]
sscanf, fscanf, scanf—scan and format inputSynopsis
#include <stdio.h>int scanf(const char *restrict format, ...);int fscanf(FILE *restrict fd, const char *restrict format, ...);int sscanf(const char *restrict str, const char *restrict format, ...);int _scanf_r(struct _reent *ptr, const char *restrict format, ...);int _fscanf_r(struct _reent *ptr, FILE *restrict fd, const char *restrict format, ...);int _sscanf_r(struct _reent *ptr, const char *restrict str, const char *restrict format, ...);
Descriptionscanf scans a series of input fields from standard input,one character at a time. Each field is interpreted according toa format specifier passed to scanf in the format string at*format. scanf stores the interpreted input fromeach field at the address passed to it as the corresponding argumentfollowing format. You must supply the same number offormat specifiers and address arguments as there are input fields.
There must be sufficient address arguments for the given formatspecifiers; if not the results are unpredictable and likelydisasterous. Excess address arguments are merely ignored.
scanf often produces unexpected results if the input diverges froman expected pattern. Since the combination of gets or fgetsfollowed by sscanf is safe and easy, that is the preferred wayto be certain that a program is synchronized with input at the endof a line.
fscanf and sscanf are identical to scanf, other than thesource of input: fscanf reads from a file, and sscanffrom a string.
The routines _scanf_r, _fscanf_r, and _sscanf_r are reentrantversions of scanf, fscanf, and sscanf that take an additionalfirst argument pointing to a reentrancy structure.
The string at *format is a character sequence composedof zero or more directives. Directives are composed ofone or more whitespace characters, non-whitespace characters,and format specifications.
Whitespace characters are blank ( ), tab (\t), ornewline (\n).When scanf encounters a whitespace character in the format stringit will read (but not store) all consecutive whitespace charactersup to the next non-whitespace character in the input.
Non-whitespace characters are all other ASCII characters except thepercent sign (%). When scanf encounters a non-whitespacecharacter in the format string it will read, but not storea matching non-whitespace character.
Format specifications tell scanf to read and convert charactersfrom the input field into specific types of values, and store thenin the locations specified by the address arguments.
Trailing whitespace is left unread unless explicitlymatched in the format string.
The format specifiers must begin with a percent sign (%)and have the following form:
%[*][width][size]type
Each format specification begins with the percent character (%).The other fields are:
an optional marker; if present, it suppresses interpretation andassignment of this input field.
an optional maximum field width: a decimal integer,which controls the maximum number of characters thatwill be read before converting the current input field. If theinput field has fewer than width characters, scanfreads all the characters in the field, and thenproceeds with the next field and its format specification.
If a whitespace or a non-convertable character occursbefore width character are read, the characters upto that character are read, converted, and stored.Then scanf proceeds to the next format specification.
h, j, l, L, t, and z are optional sizecharacters which override the default way that scanfinterprets the data type of the corresponding argument.
| Modifier | Type(s) | |
|---|---|---|
| hh | d, i, o, u, x, n | convert input to char, store in char object | 
| h | d, i, o, u, x, n | convert input to short, store in short object | 
| h | D, I, O, U, X, e, f, c, s, p | no effect | 
| j | d, i, o, u, x, n | convert input to intmax_t, store in intmax_t object | 
| j | all others | no effect | 
| l | d, i, o, u, x, n | convert input to long, store in long object | 
| l | e, f, g | convert input to double, store in a double object | 
| l | D, I, O, U, X, c, s, p | no effect | 
| ll | d, i, o, u, x, n | convert to long long, store in long long object | 
| L | d, i, o, u, x, n | convert to long long, store in long long object | 
| L | e, f, g, E, G | convert to long double, store in long double object | 
| L | all others | no effect | 
| t | d, i, o, u, x, n | convert input to ptrdiff_t, store in ptrdiff_t object | 
| t | all others | no effect | 
| z | d, i, o, u, x, n | convert input to size_t, store in size_t object | 
| z | all others | no effect | 
A character to specify what kind of conversionscanf performs. Here is a table of the conversioncharacters:
%No conversion is done; the percent character (%) is stored.
cScans one character. Corresponding arg: (char *arg).
sReads a character string into the array supplied.Corresponding arg: (char arg[]).
[pattern]Reads a non-empty character string into memorystarting at arg. This area must be largeenough to accept the sequence and aterminating null character which will be addedautomatically. (pattern is discussed in the paragraph followingthis table). Corresponding arg: (char *arg).
dReads a decimal integer into the corresponding arg: (int *arg).
DReads a decimal integer into the correspondingarg: (long *arg).
oReads an octal integer into the corresponding arg: (int *arg).
OReads an octal integer into the corresponding arg: (long *arg).
uReads an unsigned decimal integer into the correspondingarg: (unsigned int *arg).
UReads an unsigned decimal integer into the corresponding arg:(unsigned long *arg).
x,XRead a hexadecimal integer into the corresponding arg:(int *arg).
e, f, gRead a floating-point number into the corresponding arg:(float *arg).
E, F, GRead a floating-point number into the corresponding arg:(double *arg).
iReads a decimal, octal or hexadecimal integer into thecorresponding arg: (int *arg).
IReads a decimal, octal or hexadecimal integer into thecorresponding arg: (long *arg).
nStores the number of characters read in the correspondingarg: (int *arg).
pStores a scanned pointer. ANSI C leaves the detailsto each implementation; this implementation treats%p exactly the same as %U. Correspondingarg: (void **arg). 
A pattern of characters surrounded by square brackets can be usedinstead of the s type character. pattern is a set ofcharacters which define a search set of possible characters making upthe scanf input field. If the first character in the brackets is acaret (^), the search set is inverted to include all ASCII charactersexcept those between the brackets. There is also a range facilitywhich you can use as a shortcut. %[0-9]  matches all decimal digits.The hyphen must not be the first or last character in the set.The character prior to the hyphen must be lexically less than thecharacter after it.
Here are some pattern examples:
%[abcd]matches strings containing only a, b, c, and d.
%[^abcd]matches strings containing any characters except a, b,c, or d
%[A-DW-Z]matches strings containing A, B, C, D, W,X, Y, Z
%[z-a]matches the characters z, -, and a
Floating point numbers (for field types e, f, g, E,F, G) must correspond to the following general form:
[+/-] ddddd[.]ddd [E|e[+|-]ddd]
where objects inclosed in square brackets are optional, and dddrepresents decimal, octal, or hexadecimal digits.
Returnsscanf returns the number of input fields successfullyscanned, converted and stored; the return value doesnot include scanned fields which were not stored.
If scanf attempts to read at end-of-file, the returnvalue is EOF.
If no fields were stored, the return value is 0.
scanf might stop scanning a particular field beforereaching the normal field end character, or mayterminate entirely.
scanf stops scanning and storing the current fieldand moves to the next input field (if any)in any of the following situations:
*) appearsafter the % in the format specification; the currentinput field is scanned but not stored.Z is read when the format is decimal).When scanf stops scanning the current input field for one ofthese reasons, the next character is considered unread andused as the first character of the following input field, or thefirst character in a subsequent read operation on the input.
scanf will terminate under the following circumstances:
EOF.When the format string contains a character sequence that isnot part of a format specification, the same charactersequence must appear in the input; scanf willscan but not store the matched characters. If aconflict occurs, the first conflicting character remains in the inputas if it had never been read.
Portabilityscanf is ANSI C.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: swprintf, fwprintf, wprintf—wide character format output, Previous: sscanf, fscanf, scanf—scan and format input, Up: Input and Output (stdio.h)   [Contents][Index]
stdio_ext,__fbufsize,__fpending,__flbf,__freadable,__fwritable,__freading,__fwriting—access internals of FILE structureSynopsis
#include <stdio.h>#include <stdio_ext.h>size_t __fbufsize(FILE *fp);size_t __fpending(FILE *fp);int __flbf(FILE *fp);int __freadable(FILE *fp);int __fwritable(FILE *fp);int __freading(FILE *fp);int __fwriting(FILE *fp);
Description
These functions provides access to the internals of the FILE structure fp.
Returns__fbufsize returns the number of bytes in the buffer of stream fp.
__fpending returns the number of bytes in the output buffer of stream fp.
__flbf returns nonzero if stream fp is line-buffered, and 0 if not.
__freadable returns nonzero if stream fp may be read, and 0 if not.
__fwritable returns nonzero if stream fp may be written, and 0 if not.
__freading returns nonzero if stream fp if the last operation onit was a read, or if it read-only, and 0 if not.
__fwriting returns nonzero if stream fp if the last operation onit was a write, or if it write-only, and 0 if not.
Portability
These functions originate from Solaris and are also provided by GNU libc.
No supporting OS subroutines are required.
Next: swscanf, fwscanf, wscanf—scan and format wide character input, Previous: stdio_ext,__fbufsize,__fpending,__flbf,__freadable,__fwritable,__freading,__fwriting—access internals of FILE structure, Up: Input and Output (stdio.h)   [Contents][Index]
swprintf, fwprintf, wprintf—wide character format outputSynopsis
#include <wchar.h>int wprintf(const wchar_t *format, ...);int fwprintf(FILE *__restrict fd, const wchar_t *__restrict format, ...);int swprintf(wchar_t *__restrict str, size_t size, const wchar_t *__restrict format, ...);int _wprintf_r(struct _reent *ptr, const wchar_t *format, ...);int _fwprintf_r(struct _reent *ptr, FILE *fd, const wchar_t *format, ...);int _swprintf_r(struct _reent *ptr, wchar_t *str, size_t size, const wchar_t *format, ...);
Descriptionwprintf accepts a series of arguments, applies to each aformat specifier from *format, and writes theformatted data to stdout, without a terminating NULwide character. The behavior of wprintf is undefined if thereare not enough arguments for the format or if any argument is not theright type for the corresponding conversion specifier. wprintfreturns when it reaches the end of the format string. If there aremore arguments than the format requires, excess arguments areignored.
fwprintf is like wprintf, except that output is directedto the stream fd rather than stdout.
swprintf is like wprintf, except that output is directedto the buffer str with a terminating wide NUL, and theresulting string length is limited to at most size wide characters,including the terminating NUL. It is considered an error if theoutput (including the terminating wide-NULL) does not fit intosize wide characters. (This error behavior is not the same as forsnprintf, which swprintf is otherwise completely analogous to.While snprintf allows the needed size to be known simply by givingsize=0, swprintf does not, giving an error instead.)
For swprintf the behavior is undefined if the output*str overlaps with one of the arguments. Behavior is alsoundefined if the argument for %n within *formatoverlaps another argument.
format is a pointer to a wide character string containing twotypes of objects: ordinary characters (other than %),which are copied unchanged to the output, and conversionspecifications, each of which is introduced by %. (Toinclude % in the output, use %% in the format string.)A conversion specification has the following form:
%[pos][flags][width][.prec][size]type
The fields of the conversion specification have the followingmeanings:
Conversions normally consume arguments in the order that theyare presented. However, it is possible to consume argumentsout of order, and reuse an argument for more than oneconversion specification (although the behavior is undefinedif the same argument is requested with different types), byspecifying pos, which is a decimal integer followed by’$’. The integer must be between 1 and <NL_ARGMAX> fromlimits.h, and if argument %n$ is requested, all earlierarguments must be requested somewhere within format. Ifpositional parameters are used, then all conversionspecifications except for %% must specify a position.This positional parameters method is a POSIX extension to the Cstandard definition for the functions.
flags is an optional sequence of characters which controloutput justification, numeric signs, decimal points, trailingzeros, and octal and hex prefixes. The flag characters areminus (-), plus (+), space ( ), zero (0), sharp(#), and quote ('). They can appear in anycombination, although not all flags can be used for allconversion specification types.
'A POSIX extension to the C standard. However, thisimplementation presently treats it as a no-op, whichis the default behavior for the C locale, anyway. (Ifit did what it is supposed to, when type were i,d, u, f, F, g, or G, theinteger portion of the conversion would be formattedwith thousands’ grouping wide characters.)
-The result of the conversion is leftjustified, and the right is padded withblanks. If you do not use this flag, theresult is right justified, and padded on theleft.
+The result of a signed conversion (asdetermined by type of d, i, a,A, e, E, f, F, g, orG) will always begin with a plus or minussign. (If you do not use this flag, positivevalues do not begin with a plus sign.)
" " (space)If the first character of a signed conversionspecification is not a sign, or if a signedconversion results in no characters, theresult will begin with a space. If the space( ) flag and the plus (+) flag bothappear, the space flag is ignored.
0If the type character is d, i,o, u, x, X, a, A,e, E, f, F, g, or G: leadingzeros are used to pad the field width(following any indication of sign or base); nospaces are used for padding. If the zero(0) and minus (-) flags both appear,the zero (0) flag will be ignored. Ford, i, o, u, x, and Xconversions, if a precision prec isspecified, the zero (0) flag is ignored.
Note that 0 is interpreted as a flag, notas the beginning of a field width.
#The result is to be converted to analternative form, according to the typecharacter.
The alternative form output with the # flag depends on the typecharacter:
oIncreases precision to force the firstdigit of the result to be a zero.
xA non-zero result will have a 0xprefix.
XA non-zero result will have a 0Xprefix.
a, A, e, E, f, or FThe result will always contain adecimal point even if no digits followthe point. (Normally, a decimal pointappears only if a digit follows it.)Trailing zeros are removed.
g or GThe result will always contain adecimal point even if no digits followthe point. Trailing zeros are notremoved.
all othersUndefined.
width is an optional minimum field width. You caneither specify it directly as a decimal integer, orindirectly by using instead an asterisk (*), inwhich case an int argument is used as the fieldwidth. If positional arguments are used, then thewidth must also be specified positionally as *m$,with m as a decimal integer. Negative field widthsare treated as specifying the minus (-) flag forleft justfication, along with a positive field width.The resulting format may be wider than the specifiedwidth.
prec is an optional field; if present, it isintroduced with ‘.’ (a period). You can specifythe precision either directly as a decimal integer orindirectly by using an asterisk (*), in which casean int argument is used as the precision. Ifpositional arguments are used, then the precision mustalso be specified positionally as *m$, with m as adecimal integer. Supplying a negative precision isequivalent to omitting the precision. If only aperiod is specified the precision is zero. The effectdepends on the conversion type.
d, i, o, u, x, or XMinimum number of digits to appear. If noprecision is given, defaults to 1.
a or ANumber of digits to appear after the decimalpoint. If no precision is given, theprecision defaults to the minimum needed foran exact representation.
e, E, f or FNumber of digits to appear after the decimalpoint. If no precision is given, theprecision defaults to 6.
g or GMaximum number of significant digits. Aprecision of 0 is treated the same as aprecision of 1. If no precision is given, theprecision defaults to 6.
s or SMaximum number of characters to print from thestring. If no precision is given, the entirestring is printed.
all othersundefined.
size is an optional modifier that changes the datatype that the corresponding argument has. Behavior isunspecified if a size is given that does not match thetype.
hhWith d, i, o, u, x, orX, specifies that the argument should beconverted to a signed char or unsignedchar before printing.
With n, specifies that the argument is apointer to a signed char.
hWith d, i, o, u, x, orX, specifies that the argument should beconverted to a short or unsigned shortbefore printing.
With n, specifies that the argument is apointer to a short.
lWith d, i, o, u, x, orX, specifies that the argument is along or unsigned long.
With c, specifies that the argument hastype wint_t.
With s, specifies that the argument is apointer to wchar_t.
With n, specifies that the argument is apointer to a long.
With a, A, e, E, f, F,g, or G, has no effect (because ofvararg promotion rules, there is no need todistinguish between float and double).
llWith d, i, o, u, x, orX, specifies that the argument is along long or unsigned long long.
With n, specifies that the argument is apointer to a long long.
jWith d, i, o, u, x, orX, specifies that the argument is anintmax_t or uintmax_t.
With n, specifies that the argument is apointer to an intmax_t.
zWith d, i, o, u, x, orX, specifies that the argument is a size_t.
With n, specifies that the argument is apointer to a size_t.
tWith d, i, o, u, x, orX, specifies that the argument is aptrdiff_t.
With n, specifies that the argument is apointer to a ptrdiff_t.
LWith a, A, e, E, f, F,g, or G, specifies that the argumentis a long double.
type specifies what kind of conversion wprintfperforms. Here is a table of these:
%Prints the percent character (%).
cIf no l qualifier is present, the int argument shallbe converted to a wide character as if by callingthe btowc() function and the resulting wide charactershall be written. Otherwise, the wint_t argumentshall be converted to wchar_t, and written.
CShort for %lc. A POSIX extension to the C standard.
sIf no l qualifier is present, the applicationshall ensure that the argument is a pointer to acharacter array containing a character sequencebeginning in the initial shift state. Charactersfrom the array shall be converted as if by repeatedcalls to the mbrtowc() function, with the conversionstate described by an mbstate_t object initialized tozero before the first character is converted, andwritten up to (but not including) the terminatingnull wide character. If the precision is specified,no more than that many wide characters shall bewritten. If the precision is not specified, or isgreater than the size of the array, the applicationshall ensure that the array contains a null widecharacter.
If an l qualifier is present, the applicationshall ensure that the argument is a pointer to anarray of type wchar_t. Wide characters from the arrayshall be written up to (but not including) aterminating null wide character. If no precision isspecified, or is greater than the size of the array,the application shall ensure that the array containsa null wide character. If a precision is specified,no more than that many wide characters shall bewritten.
SShort for %ls. A POSIX extension to the C standard.
d or iPrints a signed decimal integer; takes anint. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
oPrints an unsigned octal integer; takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
uPrints an unsigned decimal integer; takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
xPrints an unsigned hexadecimal integer (usingabcdef as digits beyond 9); takes anunsigned. Leading zeros are inserted asnecessary to reach the precision. A value of 0 witha precision of 0 produces an empty string.
XLike x, but uses ABCDEF as digitsbeyond 9.
fPrints a signed value of the form[-]9999.9999, with the precisiondetermining how many digits follow the decimalpoint; takes a double (remember thatfloat promotes to double as a vararg).The low order digit is rounded to even. Ifthe precision results in at most DECIMAL_DIGdigits, the result is rounded correctly; ifmore than DECIMAL_DIG digits are printed, theresult is only guaranteed to round back to theoriginal value.
If the value is infinite, the result isinf, and no zero padding is performed. Ifthe value is not a number, the result isnan, and no zero padding is performed.
FLike f, but uses INF and NAN fornon-finite numbers.
ePrints a signed value of the form[-]9.9999e[+|-]999; takes a double.The digit before the decimal point is non-zeroif the value is non-zero. The precisiondetermines how many digits appear between. and e, and the exponent alwayscontains at least two digits. The value zerohas an exponent of zero. If the value is notfinite, it is printed like f.
ELike e, but using E to introduce theexponent, and like F for non-finitevalues.
gPrints a signed value in either f or eform, based on the given value andprecision—an exponent less than -4 orgreater than the precision selects the eform. Trailing zeros and the decimal pointare printed only if necessary; takes adouble.
GLike g, except use F or E form.
aPrints a signed value of the form[-]0x1.ffffp[+|-]9; takes a double.The letters abcdef are used for digitsbeyond 9. The precision determines howmany digits appear after the decimal point.The exponent contains at least one digit, andis a decimal value representing the power of2; a value of 0 has an exponent of 0.Non-finite values are printed like f.
ALike a, except uses X, P, andABCDEF instead of lower case.
nTakes a pointer to int, and stores a countof the number of bytes written so far. Nooutput is created.
pTakes a pointer to void, and prints it inan implementation-defined format. Thisimplementation is similar to %#tx), exceptthat 0x appears even for the NULL pointer.
mPrints the output of strerror(errno); noargument is required. A GNU extension.
_wprintf_r, _fwprintf_r, _swprintf_r, are simplyreentrant versions of the functions above.
Returns
On success, swprintf return the number of wide characters inthe output string, except the concluding NUL is not counted.wprintf and fwprintf return the number of characters transmitted.
If an error occurs, the result of wprintf, fwprintf, andswprintf is a negative value. For wprintf and fwprintf,errno may be set according to fputwc. For swprintf, errnomay be set to EOVERFLOW if size is greater than INT_MAX / sizeof (wchar_t),or when the output does not fit into size wide characters (including theterminating wide NULL).
Bugs
The “”’ (quote) flag does not work when locale’s thousands_sep is not empty.
Portability
POSIX-1.2008 with extensions; C99 (compliant except for POSIX extensions).
Depending on how newlib was configured, not all format specifiers aresupported.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: tmpfile—create a temporary file, Previous: swprintf, fwprintf, wprintf—wide character format output, Up: Input and Output (stdio.h)   [Contents][Index]
swscanf, fwscanf, wscanf—scan and format wide character inputSynopsis
#include <stdio.h>int wscanf(const wchar_t *__restrict format, ...);int fwscanf(FILE *__restrict fd, const wchar_t *__restrict format, ...);int swscanf(const wchar_t *__restrict str, const wchar_t *__restrict format, ...);int _wscanf_r(struct _reent *ptr, const wchar_t *format, ...);int _fwscanf_r(struct _reent *ptr, FILE *fd, const wchar_t *format, ...);int _swscanf_r(struct _reent *ptr, const wchar_t *str, const wchar_t *format, ...);
Descriptionwscanf scans a series of input fields from standard input,one wide character at a time. Each field is interpreted according toa format specifier passed to wscanf in the format string at*format. wscanf stores the interpreted input fromeach field at the address passed to it as the corresponding argumentfollowing format. You must supply the same number offormat specifiers and address arguments as there are input fields.
There must be sufficient address arguments for the given formatspecifiers; if not the results are unpredictable and likelydisasterous. Excess address arguments are merely ignored.
wscanf often produces unexpected results if the input diverges froman expected pattern. Since the combination of gets or fgetsfollowed by swscanf is safe and easy, that is the preferred wayto be certain that a program is synchronized with input at the endof a line.
fwscanf and swscanf are identical to wscanf, other than thesource of input: fwscanf reads from a file, and swscanffrom a string.
The routines _wscanf_r, _fwscanf_r, and _swscanf_r are reentrantversions of wscanf, fwscanf, and swscanf that take an additionalfirst argument pointing to a reentrancy structure.
The string at *format is a wide character sequence composedof zero or more directives. Directives are composed ofone or more whitespace characters, non-whitespace characters,and format specifications.
Whitespace characters are blank ( ), tab (\t), ornewline (\n).When wscanf encounters a whitespace character in the format stringit will read (but not store) all consecutive whitespace charactersup to the next non-whitespace character in the input.
Non-whitespace characters are all other ASCII characters except thepercent sign (%). When wscanf encounters a non-whitespacecharacter in the format string it will read, but not storea matching non-whitespace character.
Format specifications tell wscanf to read and convert charactersfrom the input field into specific types of values, and store thenin the locations specified by the address arguments.
Trailing whitespace is left unread unless explicitlymatched in the format string.
The format specifiers must begin with a percent sign (%)and have the following form:
%[*][width][size]type
Each format specification begins with the percent character (%).The other fields are:
an optional marker; if present, it suppresses interpretation andassignment of this input field.
an optional maximum field width: a decimal integer,which controls the maximum number of characters thatwill be read before converting the current input field. If theinput field has fewer than width characters, wscanfreads all the characters in the field, and thenproceeds with the next field and its format specification.
If a whitespace or a non-convertable wide character occursbefore width character are read, the characters upto that character are read, converted, and stored.Then wscanf proceeds to the next format specification.
h, j, l, L, t, and z are optional sizecharacters which override the default way that wscanfinterprets the data type of the corresponding argument.
| Modifier | Type(s) | |
|---|---|---|
| hh | d, i, o, u, x, n | convert input to char, store in char object | 
| h | d, i, o, u, x, n | convert input to short, store in short object | 
| h | e, f, c, s, p | no effect | 
| j | d, i, o, u, x, n | convert input to intmax_t, store in intmax_t object | 
| j | all others | no effect | 
| l | d, i, o, u, x, n | convert input to long, store in long object | 
| l | e, f, g | convert input to double, store in a double object | 
| l | c, s, [ | the input is stored in a wchar_t object | 
| l | p | no effect | 
| ll | d, i, o, u, x, n | convert to long long, store in long long object | 
| L | d, i, o, u, x, n | convert to long long, store in long long object | 
| L | e, f, g, E, G | convert to long double, store in long double object | 
| L | all others | no effect | 
| t | d, i, o, u, x, n | convert input to ptrdiff_t, store in ptrdiff_t object | 
| t | all others | no effect | 
| z | d, i, o, u, x, n | convert input to size_t, store in size_t object | 
| z | all others | no effect | 
A character to specify what kind of conversionwscanf performs. Here is a table of the conversioncharacters:
%No conversion is done; the percent character (%) is stored.
cScans one wide character. Corresponding arg: (char *arg).Otherwise, if an l specifier is present, the correspondingarg is a (wchar_t *arg).
sReads a character string into the array supplied.Corresponding arg: (char arg[]).If an l specifier is present, the corresponding arg is a (wchar_t *arg).
[pattern]Reads a non-empty character string into memorystarting at arg. This area must be largeenough to accept the sequence and aterminating null character which will be addedautomatically. (pattern is discussed in the paragraph followingthis table). Corresponding arg: (char *arg).If an l specifier is present, the corresponding arg isa (wchar_t *arg).
dReads a decimal integer into the corresponding arg: (int *arg).
oReads an octal integer into the corresponding arg: (int *arg).
uReads an unsigned decimal integer into the correspondingarg: (unsigned int *arg).
x,XRead a hexadecimal integer into the corresponding arg:(int *arg).
e, f, gRead a floating-point number into the corresponding arg:(float *arg).
E, F, GRead a floating-point number into the corresponding arg:(double *arg).
iReads a decimal, octal or hexadecimal integer into thecorresponding arg: (int *arg).
nStores the number of characters read in the correspondingarg: (int *arg).
pStores a scanned pointer. ANSI C leaves the detailsto each implementation; this implementation treats%p exactly the same as %U. Correspondingarg: (void **arg).
A pattern of characters surrounded by square brackets can be usedinstead of the s type character. pattern is a set ofcharacters which define a search set of possible characters making upthe wscanf input field. If the first character in the brackets is acaret (^), the search set is inverted to include all ASCII charactersexcept those between the brackets. There is no range facility as isdefined in the corresponding non-wide character scanf functions.Ranges are not part of the POSIX standard.
Here are some pattern examples:
%[abcd]matches wide character strings containing onlya, b, c, and d.
%[^abcd]matches wide character strings containing any characters excepta, b, c, or d.
%[A-DW-Z]Note: No wide character ranges, so this expression matches widecharacter strings containing A, -, D, W, Z.
Floating point numbers (for field types e, f, g, E,F, G) must correspond to the following general form:
[+/-] ddddd[.]ddd [E|e[+|-]ddd]
where objects inclosed in square brackets are optional, and dddrepresents decimal, octal, or hexadecimal digits.
Returnswscanf returns the number of input fields successfullyscanned, converted and stored; the return value doesnot include scanned fields which were not stored.
If wscanf attempts to read at end-of-file, the returnvalue is EOF.
If no fields were stored, the return value is 0.
wscanf might stop scanning a particular field beforereaching the normal field end character, or mayterminate entirely.
wscanf stops scanning and storing the current fieldand moves to the next input field (if any)in any of the following situations:
*) appearsafter the % in the format specification; the currentinput field is scanned but not stored.Z is read when the format is decimal).When wscanf stops scanning the current input field for one ofthese reasons, the next character is considered unread andused as the first character of the following input field, or thefirst character in a subsequent read operation on the input.
wscanf will terminate under the following circumstances:
WEOF.When the format string contains a wide character sequence that isnot part of a format specification, the same wide charactersequence must appear in the input; wscanf willscan but not store the matched characters. If aconflict occurs, the first conflicting wide character remains in theinput as if it had never been read.
Portabilitywscanf is C99, POSIX-1.2008.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: tmpnam, tempnam—name for a temporary file, Previous: swscanf, fwscanf, wscanf—scan and format wide character input, Up: Input and Output (stdio.h)   [Contents][Index]
tmpfile—create a temporary fileSynopsis
#include <stdio.h>FILE *tmpfile(void);FILE *_tmpfile_r(struct _reent *reent);
Description
Create a temporary file (a file which will be deleted automatically),using a name generated by tmpnam. The temporary file is opened withthe mode "wb+", permitting you to read and write anywhere in itas a binary file (without any data transformations the host system mayperform for text files).
The alternate function _tmpfile_r is a reentrant version. Theargument reent is a pointer to a reentrancy structure.
Returnstmpfile normally returns a pointer to the temporary file. If notemporary file could be created, the result is NULL, and errnorecords the reason for failure.
Portability
Both ANSI C and the System V Interface Definition (Issue 2) requiretmpfile.
Supporting OS subroutines required: close, fstat, getpid,isatty, lseek, open, read, sbrk, write.
tmpfile also requires the global pointer environ.
Next: ungetc—push data back into a stream, Previous: tmpfile—create a temporary file, Up: Input and Output (stdio.h)   [Contents][Index]
tmpnam, tempnam—name for a temporary fileSynopsis
#include <stdio.h>char *tmpnam(char *s);char *tempnam(char *dir, char *pfx);char *_tmpnam_r(struct _reent *reent, char *s);char *_tempnam_r(struct _reent *reent, char *dir, char *pfx);
Description
Use either of these functions to generate a name for a temporary file.The generated name is guaranteed to avoid collision with other files(for up to TMP_MAX calls of either function).
tmpnam generates file names with the value of P_tmpdir(defined in ‘stdio.h’) as the leading directory component of the path.
You can use the tmpnam argument s to specify a suitable areaof memory for the generated filename; otherwise, you can calltmpnam(NULL) to use an internal static buffer.
tempnam allows you more control over the generated filename: youcan use the argument dir to specify the path to a directory fortemporary files, and you can use the argument pfx to specify aprefix for the base filename.
If dir is NULL, tempnam will attempt to use the value ofenvironment variable TMPDIR instead; if there is no such value,tempnam uses the value of P_tmpdir (defined in ‘stdio.h’).
If you don’t need any particular prefix to the basename of temporaryfiles, you can pass NULL as the pfx argument to tempnam.
_tmpnam_r and _tempnam_r are reentrant versions of tmpnamand tempnam respectively. The extra argument reent is apointer to a reentrancy structure.
Warnings
The generated filenames are suitable for temporary files, but do notin themselves make files temporary. Files with these names must stillbe explicitly removed when you no longer want them.
If you supply your own data area s for tmpnam, you must ensurethat it has room for at least L_tmpnam elements of type char.
Returns
Both tmpnam and tempnam return a pointer to the newlygenerated filename.
Portability
ANSI C requires tmpnam, but does not specify the use ofP_tmpdir. The System V Interface Definition (Issue 2) requiresboth tmpnam and tempnam.
Supporting OS subroutines required: close, fstat, getpid,isatty, lseek, open, read, sbrk, write.
The global pointer environ is also required.
Next: ungetwc—push wide character data back into a stream, Previous: tmpnam, tempnam—name for a temporary file, Up: Input and Output (stdio.h)   [Contents][Index]
ungetc—push data back into a streamSynopsis
#include <stdio.h>int ungetc(int c, FILE *stream);int _ungetc_r(struct _reent *reent, int c, FILE *stream);
Descriptionungetc is used to return bytes back to stream to be read again.If c is EOF, the stream is unchanged. Otherwise, the unsignedchar c is put back on the stream, and subsequent reads will seethe bytes pushed back in reverse order. Pushed byes are lost if thestream is repositioned, such as by fseek, fsetpos, orrewind.
The underlying file is not changed, but it is possible to push backsomething different than what was originally read. Ungetting acharacter will clear the end-of-stream marker, and decrement the fileposition indicator. Pushing back beyond the beginning of a file givesunspecified behavior.
The alternate function _ungetc_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returns
The character pushed back, or EOF on error.
Portability
ANSI C requires ungetc, but only requires a pushback buffer of onebyte; although this implementation can handle multiple bytes, not allcan. Pushing back a signed char is a common application bug.
Supporting OS subroutines required: sbrk.
Next: vfprintf, vprintf, vsprintf, vsnprintf, vasprintf, vasnprintf—format argument list, Previous: ungetc—push data back into a stream, Up: Input and Output (stdio.h)   [Contents][Index]
ungetwc—push wide character data back into a streamSynopsis
#include <stdio.h>#include <wchar.h>wint_t ungetwc(wint_t wc, FILE *stream);wint_t _ungetwc_r(struct _reent *reent, wint_t wc, FILE *stream);
Descriptionungetwc is used to return wide characters back to stream to beread again. If wc is WEOF, the stream is unchanged. Otherwise, thewide character wc is put back on the stream, and subsequent reads will seethe wide chars pushed back in reverse order. Pushed wide chars are lost if thestream is repositioned, such as by fseek, fsetpos, orrewind.
The underlying file is not changed, but it is possible to push backsomething different than what was originally read. Ungetting acharacter will clear the end-of-stream marker, and decrement the fileposition indicator. Pushing back beyond the beginning of a file givesunspecified behavior.
The alternate function _ungetwc_r is a reentrant version. Theextra argument reent is a pointer to a reentrancy structure.
Returns
The wide character pushed back, or WEOF on error.
Portability
C99
Next: vfscanf, vscanf, vsscanf—format argument list, Previous: ungetwc—push wide character data back into a stream, Up: Input and Output (stdio.h)   [Contents][Index]
vfprintf, vprintf, vsprintf, vsnprintf, vasprintf, vasnprintf—format argument listSynopsis
#include <stdio.h>#include <stdarg.h>int vprintf(const char *fmt, va_list list);int vfprintf(FILE *fp, const char *fmt, va_list list);int vsprintf(char *str, const char *fmt, va_list list);int vsnprintf(char *str, size_t size, const char *fmt, va_list list);int vasprintf(char **strp, const char *fmt, va_list list);char *vasnprintf(char *str, size_t *size, const char *fmt, va_list list);int _vprintf_r(struct _reent *reent, const char *fmt, va_list list);int _vfprintf_r(struct _reent *reent, FILE *fp, const char *fmt, va_list list);int _vsprintf_r(struct _reent *reent, char *str, const char *fmt, va_list list);int _vasprintf_r(struct _reent *reent, char **str, const char *fmt, va_list list);int _vsnprintf_r(struct _reent *reent, char *str, size_t size, const char *fmt, va_list list);char *_vasnprintf_r(struct _reent *reent, char *str, size_t *size, const char *fmt, va_list list);
Descriptionvprintf, vfprintf, vasprintf, vsprintf, vsnprintf,and vasnprintf are (respectively) variants of printf,fprintf, asprintf, sprintf, snprintf, andasnprintf. They differ only in allowing their caller to pass thevariable argument list as a va_list object (initialized byva_start) rather than directly accepting a variable number ofarguments. The caller is responsible for calling va_end.
_vprintf_r, _vfprintf_r, _vasprintf_r, _vsprintf_r,_vsnprintf_r, and _vasnprintf_r are reentrant versions of theabove.
Returns
The return values are consistent with the corresponding functions.
Portability
ANSI C requires vprintf, vfprintf, vsprintf, andvsnprintf. The remaining functions are newlib extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: vfwprintf, vwprintf, vswprintf—wide character format argument list, Previous: vfprintf, vprintf, vsprintf, vsnprintf, vasprintf, vasnprintf—format argument list, Up: Input and Output (stdio.h)   [Contents][Index]
vfscanf, vscanf, vsscanf—format argument listSynopsis
#include <stdio.h>#include <stdarg.h>int vscanf(const char *fmt, va_list list);int vfscanf(FILE *fp, const char *fmt, va_list list);int vsscanf(const char *str, const char *fmt, va_list list);int _vscanf_r(struct _reent *reent, const char *fmt, va_list list);int _vfscanf_r(struct _reent *reent, FILE *fp, const char *fmt, va_list list);int _vsscanf_r(struct _reent *reent, const char *str, const char *fmt, va_list list);
Descriptionvscanf, vfscanf, and vsscanf are (respectively) variantsof scanf, fscanf, and sscanf. They differ only inallowing their caller to pass the variable argument list as ava_list object (initialized by va_start) rather thandirectly accepting a variable number of arguments.
Returns
The return values are consistent with the corresponding functions:vscanf returns the number of input fields successfully scanned,converted, and stored; the return value does not include scannedfields which were not stored.
If vscanf attempts to read at end-of-file, the return valueis EOF.
If no fields were stored, the return value is 0.
The routines _vscanf_r, _vfscanf_f, and _vsscanf_r arereentrant versions which take an additional first parameter which points to thereentrancy structure.
Portability
These are GNU extensions.
Supporting OS subroutines required:
Next: vfwscanf, vwscanf, vswscanf—scan and format argument list from wide character input, Previous: vfscanf, vscanf, vsscanf—format argument list, Up: Input and Output (stdio.h)   [Contents][Index]
vfwprintf, vwprintf, vswprintf—wide character format argument listSynopsis
#include <stdio.h>#include <stdarg.h>#include <wchar.h>int vwprintf(const wchar_t *__restrict fmt, va_list list);int vfwprintf(FILE *__restrict fp, const wchar_t *__restrict fmt, va_list list);int vswprintf(wchar_t * __restrict str, size_t size, const wchar_t *__ restrict fmt, va_list list);int _vwprintf_r(struct _reent *reent, const wchar_t *fmt, va_list list);int _vfwprintf_r(struct _reent *reent, FILE *fp, const wchar_t *fmt, va_list list);int _vswprintf_r(struct _reent *reent, wchar_t *str, size_t size, const wchar_t *fmt, va_list list);
Descriptionvwprintf, vfwprintf and vswprintf are (respectively) variantsof wprintf, fwprintf and swprintf. They differ only in allowingtheir caller to pass the variable argument list as a va_list object(initialized by va_start) rather than directly accepting a variablenumber of arguments. The caller is responsible for calling va_end.
_vwprintf_r, _vfwprintf_r and _vswprintf_r are reentrantversions of the above.
Returns
The return values are consistent with the corresponding functions.
Portability
POSIX-1.2008 with extensions; C99 (compliant except for POSIX extensions).
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
See Alsowprintf, fwprintf and swprintf.
Next: viprintf, vfiprintf, vsiprintf, vsniprintf, vasiprintf, vasniprintf—format argument list (integer only), Previous: vfwprintf, vwprintf, vswprintf—wide character format argument list, Up: Input and Output (stdio.h)   [Contents][Index]
vfwscanf, vwscanf, vswscanf—scan and format argument list from wide character inputSynopsis
#include <stdio.h>#include <stdarg.h>int vwscanf(const wchar_t *__restrict fmt, va_list list);int vfwscanf(FILE *__restrict fp, const wchar_t *__restrict fmt, va_list list);int vswscanf(const wchar_t *__restrict str, const wchar_t *__restrict fmt, va_list list);int _vwscanf(struct _reent *reent, const wchar_t *fmt, va_list list);int _vfwscanf(struct _reent *reent, FILE *fp, const wchar_t *fmt, va_list list);int _vswscanf(struct _reent *reent, const wchar_t *str, const wchar_t *fmt, va_list list);
Descriptionvwscanf, vfwscanf, and vswscanf are (respectively) variantsof wscanf, fwscanf, and swscanf. They differ only inallowing their caller to pass the variable argument list as ava_list object (initialized by va_start) rather thandirectly accepting a variable number of arguments.
Returns
The return values are consistent with the corresponding functions:vwscanf returns the number of input fields successfully scanned,converted, and stored; the return value does not include scannedfields which were not stored.
If vwscanf attempts to read at end-of-file, the return valueis EOF.
If no fields were stored, the return value is 0.
The routines _vwscanf, _vfwscanf, and _vswscanf arereentrant versions which take an additional first parameter which pointsto the reentrancy structure.
Portability
C99, POSIX-1.2008
Next: viscanf, vfiscanf, vsiscanf—format argument list, Previous: vfwscanf, vwscanf, vswscanf—scan and format argument list from wide character input, Up: Input and Output (stdio.h)   [Contents][Index]
viprintf, vfiprintf, vsiprintf, vsniprintf, vasiprintf, vasniprintf—format argument list (integer only)Synopsis
#include <stdio.h>#include <stdarg.h>int viprintf(const char *fmt, va_list list);int vfiprintf(FILE *fp, const char *fmt, va_list list);int vsiprintf(char *str, const char *fmt, va_list list);int vsniprintf(char *str, size_t size, const char *fmt, va_list list);int vasiprintf(char **strp, const char *fmt, va_list list);char *vasniprintf(char *str, size_t *size, const char *fmt, va_list list);int _viprintf_r(struct _reent *reent, const char *fmt, va_list list);int _vfiprintf_r(struct _reent *reent, FILE *fp, const char *fmt, va_list list);int _vsiprintf_r(struct _reent *reent, char *str, const char *fmt, va_list list);int _vsniprintf_r(struct _reent *reent, char *str, size_t size, const char *fmt, va_list list);int _vasiprintf_r(struct _reent *reent, char **str, const char *fmt, va_list list);char *_vasniprintf_r(struct _reent *reent, char *str, size_t *size, const char *fmt, va_list list);
Descriptionviprintf, vfiprintf, vasiprintf, vsiprintf,vsniprintf, and vasniprintf are (respectively) variants ofiprintf, fiprintf, asiprintf, siprintf, sniprintf,and asniprintf. They differ only in allowing their caller to passthe variable argument list as a va_list object (initialized byva_start) rather than directly accepting a variable number ofarguments. The caller is responsible for calling va_end.
_viprintf_r, _vfiprintf_r, _vasiprintf_r,_vsiprintf_r, _vsniprintf_r, and _vasniprintf_r arereentrant versions of the above.
Returns
The return values are consistent with the corresponding functions:
Portability
All of these functions are newlib extensions.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Previous: viprintf, vfiprintf, vsiprintf, vsniprintf, vasiprintf, vasniprintf—format argument list (integer only), Up: Input and Output (stdio.h)   [Contents][Index]
viscanf, vfiscanf, vsiscanf—format argument listSynopsis
#include <stdio.h>#include <stdarg.h>int viscanf(const char *fmt, va_list list);int vfiscanf(FILE *fp, const char *fmt, va_list list);int vsiscanf(const char *str, const char *fmt, va_list list);int _viscanf_r(struct _reent *reent, const char *fmt, va_list list);int _vfiscanf_r(struct _reent *reent, FILE *fp, const char *fmt, va_list list);int _vsiscanf_r(struct _reent *reent, const char *str, const char *fmt, va_list list);
Descriptionviscanf, vfiscanf, and vsiscanf are (respectively) variantsof iscanf, fiscanf, and siscanf. They differ only inallowing their caller to pass the variable argument list as a va_list object (initialized by va_start) rather thandirectly accepting a variable number of arguments.
Returns
The return values are consistent with the corresponding functions:viscanf returns the number of input fields successfully scanned,converted, and stored; the return value does not include scannedfields which were not stored. 
If viscanf attempts to read at end-of-file, the return valueis EOF.
If no fields were stored, the return value is 0.
The routines _viscanf_r, _vfiscanf_f, and _vsiscanf_r arereentrant versions which take an additional first parameter which points to thereentrancy structure.
Portability
These are newlib extensions.
Supporting OS subroutines required:
Next: Strings and Memory (string.h), Previous: Input and Output (stdio.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter comprises additional functions to manage large files whichare potentially larger than 2GB.
The underlying facilities for input and output depend on the hostsystem, but these functions provide a uniform interface.
The corresponding declarations are in stdio.h.
fdopen64—turn open large file into a streamfopen64—open a large filefreopen64—open a large file using an existing file descriptorftello64—return position in a stream or filefseeko64—set file position for large filefgetpos64—record position in a large stream or filefsetpos64—restore position of a large stream or filetmpfile64—create a large temporary filefdopen64—turn open large file into a streamSynopsis
#include <stdio.h>FILE *fdopen64(int fd, const char *mode);FILE *_fdopen64_r(void *reent, int fd, const char *mode);
Descriptionfdopen64 produces a file descriptor of type FILE *, from adescriptor for an already-open file (returned, for example, by thesystem subroutine open rather than by fopen).The mode argument has the same meanings as in fopen.
Returns
File pointer or NULL, as for fopen.
Next: freopen64—open a large file using an existing file descriptor, Previous: fdopen64—turn open large file into a stream, Up: Large File Input and Output (stdio.h)   [Contents][Index]
fopen64—open a large fileSynopsis
#include <stdio.h>FILE *fopen64(const char *file, const char *mode);FILE *_fopen64_r(void *reent, const char *file, const char *mode);
Descriptionfopen64 is identical to fopen except it opens a large file thatis potentially >2GB in size. See fopen for further details.
Returnsfopen64 return a file pointer which you can use for other fileoperations, unless the file you requested could not be opened; in thatsituation, the result is NULL. If the reason for failure was aninvalid string at mode, errno is set to EINVAL.
Portabilityfopen64 is a glibc extension.
Supporting OS subroutines required: close, fstat64, isatty,lseek64, open64, read, sbrk, write.
Next: ftello64—return position in a stream or file, Previous: fopen64—open a large file, Up: Large File Input and Output (stdio.h)   [Contents][Index]
freopen64—open a large file using an existing file descriptorSynopsis
#include <stdio.h>FILE *freopen64(const char *file, const char *mode, FILE *fp);FILE *_freopen64_r(struct _reent *ptr, const char *file, const char *mode, FILE *fp);
Description
Use this variant of fopen64 if you wish to specify a particular filedescriptor fp (notably stdin, stdout, or stderr) forthe file.
If fp was associated with another file or stream, freopen64closes that other file or stream (but ignores any errors while closingit).
file and mode are used just as in fopen.
If file is NULL, the underlying stream is modified rather thanclosed. The file cannot be given a more permissive access mode (forexample, a mode of "w" will fail on a read-only file descriptor),but can change status such as append or binary mode. If modificationis not possible, failure occurs.
Returns
If successful, the result is the same as the argument fp. If thefile cannot be opened as specified, the result is NULL.
Portabilityfreopen is a glibc extension.
Supporting OS subroutines required: close, fstat, isatty,lseek64, open64, read, sbrk, write.
Next: fseeko64—set file position for large file, Previous: freopen64—open a large file using an existing file descriptor, Up: Large File Input and Output (stdio.h)   [Contents][Index]
ftello64—return position in a stream or fileSynopsis
#include <stdio.h>_off64_t ftello64(FILE *fp);_off64_t _ftello64_r(struct _reent *ptr, FILE *fp);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
The result of ftello64 is the current position for a large fileidentified by fp. If you record this result, you can lateruse it with fseeko64 to return the file to thisposition. The difference between ftello and ftello64 is thatftello returns off_t and ftello64 is designed to workfor large files (>2GB) and returns _off64_t.
In the current implementation, ftello64 simply uses a charactercount to represent the file position; this is the same number thatwould be recorded by fgetpos64.
The function exists only if the __LARGE64_FILES flag is defined.An error occurs if the fp was not opened via fopen64.
Returnsftello64 returns the file position, if possible. If it cannot dothis, it returns -1. Failure occurs on streams that do not supportpositioning or not opened via fopen64; the global errno indicatesthis condition with the value ESPIPE.
Portabilityftello64 is a glibc extension.
No supporting OS subroutines are required.
Next: fgetpos64—record position in a large stream or file, Previous: ftello64—return position in a stream or file, Up: Large File Input and Output (stdio.h)   [Contents][Index]
fseeko64—set file position for large fileSynopsis
#include <stdio.h>int fseeko64(FILE *fp, _off64_t offset, int whence);int _fseeko64_r (struct _reent *ptr, FILE *fp, _off64_t offset, int whence);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fseeko64 to set the position for the file identified byfp that was opened via fopen64. The value of offset determinesthe new position, in one of three ways selected by the value of whence(defined as macros in ‘stdio.h’):
SEEK_SET—offset is the absolute file position (an offsetfrom the beginning of the file) desired. offset must be positive.
SEEK_CUR—offset is relative to the current file position.offset can meaningfully be either positive or negative.
SEEK_END—offset is relative to the current end of file.offset can meaningfully be either positive (to increase the sizeof the file) or negative.
See ftello64 to determine the current file position.
Returnsfseeko64 returns 0 when successful. On failure, theresult is EOF. The reason for failure is indicated in errno:either ESPIPE (the stream identified by fp doesn’t supportrepositioning or wasn’t opened via fopen64) or EINVAL(invalid file position).
Portabilityfseeko64 is a glibc extension.
Supporting OS subroutines required: close, fstat64, isatty,lseek64, read, sbrk, write.
Next: fsetpos64—restore position of a large stream or file, Previous: fseeko64—set file position for large file, Up: Large File Input and Output (stdio.h)   [Contents][Index]
fgetpos64—record position in a large stream or fileSynopsis
#include <stdio.h>int fgetpos64(FILE *fp, _fpos64_t *pos);int _fgetpos64_r(struct _reent *ptr, FILE *fp, _fpos64_t *pos);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fgetpos64 to report on the current position for a fileidentified by fp that was opened by fopen64; fgetpos will writea value representing that position at *pos. Later, you canuse this value with fsetpos64 to return the file to thisposition.
In the current implementation, fgetpos64 simply uses a charactercount to represent the file position; this is the same number thatwould be returned by ftello64.
Returnsfgetpos64 returns 0 when successful. If fgetpos64 fails, theresult is 1. Failure occurs on streams that do not supportpositioning or streams not opened via fopen64; the global errnoindicates these conditions with the value ESPIPE.
Portabilityfgetpos64 is a glibc extension.
No supporting OS subroutines are required.
Next: tmpfile64—create a large temporary file, Previous: fgetpos64—record position in a large stream or file, Up: Large File Input and Output (stdio.h)   [Contents][Index]
fsetpos64—restore position of a large stream or fileSynopsis
#include <stdio.h>int fsetpos64(FILE *fp, const _fpos64_t *pos);int _fsetpos64_r(struct _reent *ptr, FILE *fp, const _fpos64_t *pos);
Description
Objects of type FILE can have a “position” that records how muchof the file your program has already read. Many of the stdio functionsdepend on this position, and many change it as a side effect.
You can use fsetpos64 to return the large file identified by fp to aprevious position *pos (after first recording it with fgetpos64).
See fseeko64 for a similar facility.
Returnsfgetpos64 returns 0 when successful. If fgetpos64 fails, theresult is 1. The reason for failure is indicated in errno:either ESPIPE (the stream identified by fp doesn’t support64-bit repositioning) or EINVAL (invalid file position).
Portabilityfsetpos64 is a glibc extension.
Supporting OS subroutines required: close, fstat, isatty,lseek64, read, sbrk, write.
Previous: fsetpos64—restore position of a large stream or file, Up: Large File Input and Output (stdio.h)   [Contents][Index]
tmpfile64—create a large temporary fileSynopsis
#include <stdio.h>FILE *tmpfile64(void);FILE *_tmpfile64_r(void *reent);
Description
Create a large temporary file (a file which will be deleted automatically),using a name generated by tmpnam. The temporary file is opened withthe mode "wb+", permitting you to read and write anywhere in itas a binary file (without any data transformations the host system mayperform for text files). The file may be larger than 2GB.
The alternate function _tmpfile64_r is a reentrant version. Theargument reent is a pointer to a reentrancy structure.
Both tmpfile64 and _tmpfile64_r are only defined if __LARGE64_FILESis defined.
Returnstmpfile64 normally returns a pointer to the temporary file. If notemporary file could be created, the result is NULL, and errnorecords the reason for failure.
Portabilitytmpfile64 is a glibc extension.
Supporting OS subroutines required: close, fstat, getpid,isatty, lseek64, open64, read, sbrk, write.
tmpfile64 also requires the global pointer environ.
Next: Wide Character Strings (wchar.h), Previous: Large File Input and Output (stdio.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter describes string-handling functions and functions formanaging areas of memory. The corresponding declarations are instring.h.
bcmp—compare two memory areasbcopy—copy memory regionsbzero—initialize memory to zeroindex—search for character in stringmemccpy—copy memory regions with end-token checkmemchr—find character in memorymemcmp—compare two memory areasmemcpy—copy memory regionsmemmem—find memory segmentmemmove—move possibly overlapping memorymempcpy—copy memory regions and return end pointermemrchr—reverse search for character in memorymemset—set an area of memoryrawmemchr—find character in memoryrindex—reverse search for character in stringstpcpy—copy string returning a pointer to its endstpncpy—counted copy string returning a pointer to its endstrcasecmp—case-insensitive character string comparestrcasestr—case-insensitive character string searchstrcat—concatenate stringsstrchr—search for character in stringstrchrnul—search for character in stringstrcmp—character string comparestrcoll—locale-specific character string comparestrcpy—copy stringstrcspn—count characters not in stringstrerror, strerror_l—convert error number to stringstrerror_r—convert error number to string and copy to bufferstrlen—character string lengthstrlwr—force string to lowercasestrncasecmp—case-insensitive character string comparestrncat—concatenate stringsstrncmp—character string comparestrncpy—counted copy stringstrnstr—find string segmentstrnlen—character string lengthstrpbrk—find characters in stringstrrchr—reverse search for character in stringstrsignal—convert signal number to stringstrspn—find initial matchstrstr—find string segmentstrtok, strtok_r, strsep—get next token from a stringstrupr—force string to uppercasestrverscmp—version string comparestrxfrm—transform stringswab—swap adjacent byteswcscasecmp—case-insensitive wide character string comparewcsdup—wide character string duplicatewcsncasecmp—case-insensitive wide character string compareNext: bcopy—copy memory regions, Up: Strings and Memory (string.h)   [Contents][Index]
bcmp—compare two memory areasSynopsis
#include <strings.h>int bcmp(const void *s1, const void *s2, size_t n);
Description
This function compares not more than n bytes of theobject pointed to by s1 with the object pointed to by s2.
This function is identical to memcmp.
Returns
The function returns an integer greater than, equal to orless than zero	according to whether the object pointed to bys1 is greater than, equal to or less than the objectpointed to by s2.
Portabilitybcmp requires no supporting OS subroutines.
Next: bzero—initialize memory to zero, Previous: bcmp—compare two memory areas, Up: Strings and Memory (string.h)   [Contents][Index]
bcopy—copy memory regionsSynopsis
#include <strings.h>void bcopy(const void *in, void *out, size_t n);
Description
This function copies n bytes from the memory regionpointed to by in to the memory region pointed to byout.
This function is implemented in term of memmove.
Portabilitybcopy requires no supporting OS subroutines.
Next: index—search for character in string, Previous: bcopy—copy memory regions, Up: Strings and Memory (string.h)   [Contents][Index]
bzero—initialize memory to zeroSynopsis
#include <strings.h>void bzero(void *b, size_t length);
Descriptionbzero initializes length bytes of memory, starting at addressb, to zero.
Returnsbzero does not return a result.
Portabilitybzero is in the Berkeley Software Distribution.Neither ANSI C nor the System V Interface Definition (Issue 2) requirebzero.
bzero requires no supporting OS subroutines.
Next: memccpy—copy memory regions with end-token check, Previous: bzero—initialize memory to zero, Up: Strings and Memory (string.h)   [Contents][Index]
index—search for character in stringSynopsis
#include <strings.h>char * index(const char *string, int c);
Description
This function finds the first occurence of c (converted toa char) in the string pointed to by string (including theterminating null character).
This function is identical to strchr.
Returns
Returns a pointer to the located character, or a null pointerif c does not occur in string.
Portabilityindex requires no supporting OS subroutines.
Next: memchr—find character in memory, Previous: index—search for character in string, Up: Strings and Memory (string.h)   [Contents][Index]
memccpy—copy memory regions with end-token checkSynopsis
#include <string.h>void* memccpy(void *restrict out, const void *restrict in, int endchar, size_t n);
Description
This function copies up to n bytes from the memory regionpointed to by in to the memory region pointed to byout. If a byte matching the endchar is encountered,the byte is copied and copying stops.
If the regions overlap, the behavior is undefined.
Returnsmemccpy returns a pointer to the first byte following theendchar in the out region. If no byte matchingendchar was copied, then NULL is returned.
Portabilitymemccpy is a GNU extension.
memccpy requires no supporting OS subroutines.
Next: memcmp—compare two memory areas, Previous: memccpy—copy memory regions with end-token check, Up: Strings and Memory (string.h)   [Contents][Index]
memchr—find character in memorySynopsis
#include <string.h>void *memchr(const void *src, int c, size_t length);
Description
This function searches memory starting at *src for thecharacter c. The search only ends with the firstoccurrence of c, or after length characters; inparticular, NUL does not terminate the search.
Returns
If the character c is found within length charactersof *src, a pointer to the character is returned. Ifc is not found, then NULL is returned.
Portabilitymemchr is ANSI C.
memchr requires no supporting OS subroutines.
Next: memcpy—copy memory regions, Previous: memchr—find character in memory, Up: Strings and Memory (string.h)   [Contents][Index]
memcmp—compare two memory areasSynopsis
#include <string.h>int memcmp(const void *s1, const void *s2, size_t n);
Description
This function compares not more than n characters of theobject pointed to by s1 with the object pointed to by s2.
Returns
The function returns an integer greater than, equal to orless than zero	according to whether the object pointed to bys1 is greater than, equal to or less than the objectpointed to by s2.
Portabilitymemcmp is ANSI C.
memcmp requires no supporting OS subroutines.
Next: memmem—find memory segment, Previous: memcmp—compare two memory areas, Up: Strings and Memory (string.h)   [Contents][Index]
memcpy—copy memory regionsSynopsis
#include <string.h>void* memcpy(void *restrict out, const void *restrict in, size_t n);
Description
This function copies n bytes from the memory regionpointed to by in to the memory region pointed to byout.
If the regions overlap, the behavior is undefined.
Returnsmemcpy returns a pointer to the first byte of the outregion.
Portabilitymemcpy is ANSI C.
memcpy requires no supporting OS subroutines.
Next: memmove—move possibly overlapping memory, Previous: memcpy—copy memory regions, Up: Strings and Memory (string.h)   [Contents][Index]
memmem—find memory segmentSynopsis
#include <string.h>void *memmem(const void *s1, size_t l1, const void *s2, size_t l2);
Description
Locates the first occurrence in the memory region pointed toby s1 with length l1 of the sequence of bytes pointedto by s2 of length l2. If you already know thelengths of your haystack and needle, memmem is much fasterthan strstr.
Returns
Returns a pointer to the located segment, or a null pointer ifs2 is not found. If l2 is 0, s1 is returned.
Portabilitymemmem is a newlib extension.
memmem requires no supporting OS subroutines.
Next: mempcpy—copy memory regions and return end pointer, Previous: memmem—find memory segment, Up: Strings and Memory (string.h)   [Contents][Index]
memmove—move possibly overlapping memorySynopsis
#include <string.h>void *memmove(void *dst, const void *src, size_t length);
Description
This function moves length characters from the block ofmemory starting at *src to the memory starting at*dst. memmove reproduces the characters correctlyat *dst even if the two areas overlap.
Returns
The function returns dst as passed.
Portabilitymemmove is ANSI C.
memmove requires no supporting OS subroutines.
Next: memrchr—reverse search for character in memory, Previous: memmove—move possibly overlapping memory, Up: Strings and Memory (string.h)   [Contents][Index]
mempcpy—copy memory regions and return end pointerSynopsis
#include <string.h>void* mempcpy(void *out, const void *in, size_t n);
Description
This function copies n bytes from the memory regionpointed to by in to the memory region pointed to byout.
If the regions overlap, the behavior is undefined.
Returnsmempcpy returns a pointer to the byte following thelast byte copied to the out region.
Portabilitymempcpy is a GNU extension.
mempcpy requires no supporting OS subroutines.
Next: memset—set an area of memory, Previous: mempcpy—copy memory regions and return end pointer, Up: Strings and Memory (string.h)   [Contents][Index]
memrchr—reverse search for character in memorySynopsis
#include <string.h>void *memrchr(const void *src, int c, size_t length);
Description
This function searches memory starting at length bytesbeyond *src backwards for the character c.The search only ends with the first occurrence of c; inparticular, NUL does not terminate the search.
Returns
If the character c is found within length charactersof *src, a pointer to the character is returned. Ifc is not found, then NULL is returned.
Portabilitymemrchr is a GNU extension.
memrchr requires no supporting OS subroutines.
Next: rawmemchr—find character in memory, Previous: memrchr—reverse search for character in memory, Up: Strings and Memory (string.h)   [Contents][Index]
memset—set an area of memorySynopsis
#include <string.h>void *memset(void *dst, int c, size_t length);
Description
This function converts the argument c into an unsignedchar and fills the first length characters of the arraypointed to by dst to the value.
Returnsmemset returns the value of dst.
Portabilitymemset is ANSI C.
memset requires no supporting OS subroutines.
Next: rindex—reverse search for character in string, Previous: memset—set an area of memory, Up: Strings and Memory (string.h)   [Contents][Index]
rawmemchr—find character in memorySynopsis
#include <string.h>void *rawmemchr(const void *src, int c);
Description
This function searches memory starting at *src for thecharacter c. The search only ends with the first occurrenceof c; in particular, NUL does not terminate the search.No bounds checking is performed, so this function should onlybe used when it is certain that the character c will be found.
Returns
A pointer to the first occurance of character c.
Portabilityrawmemchr is a GNU extension.
rawmemchr requires no supporting OS subroutines.
Next: stpcpy—copy string returning a pointer to its end, Previous: rawmemchr—find character in memory, Up: Strings and Memory (string.h)   [Contents][Index]
rindex—reverse search for character in stringSynopsis
#include <string.h>char * rindex(const char *string, int c);
Description
This function finds the last occurence of c (converted toa char) in the string pointed to by string (including theterminating null character).
This function is identical to strrchr.
Returns
Returns a pointer to the located character, or a null pointerif c does not occur in string.
Portabilityrindex requires no supporting OS subroutines.
Next: stpncpy—counted copy string returning a pointer to its end, Previous: rindex—reverse search for character in string, Up: Strings and Memory (string.h)   [Contents][Index]
stpcpy—copy string returning a pointer to its endSynopsis
#include <string.h>char *stpcpy(char *restrict dst, const char *restrict src);
Descriptionstpcpy copies the string pointed to by src(including the terminating null character) to the arraypointed to by dst.
Returns
This function returns a pointer to the end of the destination string,thus pointing to the trailing ’\0’.
Portabilitystpcpy is a GNU extension, candidate for inclusion into POSIX/SUSv4.
stpcpy requires no supporting OS subroutines.
Next: strcasecmp—case-insensitive character string compare, Previous: stpcpy—copy string returning a pointer to its end, Up: Strings and Memory (string.h)   [Contents][Index]
stpncpy—counted copy string returning a pointer to its endSynopsis
#include <string.h>char *stpncpy(char *restrict dst, const char *restrict src, size_t length);
Descriptionstpncpy copies not more than length characters from thethe string pointed to by src (including the terminatingnull character) to the array pointed to by dst. If thestring pointed to by src is shorter than lengthcharacters, null characters are appended to the destinationarray until a total of length characters have beenwritten.
Returns
This function returns a pointer to the end of the destination string,thus pointing to the trailing ’\0’, or, if the destination string isnot null-terminated, pointing to dst + n.
Portabilitystpncpy is a GNU extension, candidate for inclusion into POSIX/SUSv4.
stpncpy requires no supporting OS subroutines.
Next: strcasestr—case-insensitive character string search, Previous: stpncpy—counted copy string returning a pointer to its end, Up: Strings and Memory (string.h)   [Contents][Index]
strcasecmp—case-insensitive character string compareSynopsis
#include <strings.h>int strcasecmp(const char *a, const char *b);
Descriptionstrcasecmp compares the string at a tothe string at b in a case-insensitive manner.
Returns
If *a sorts lexicographically after *b (afterboth are converted to lowercase), strcasecmp returns anumber greater than zero. If the two strings match,strcasecmp returns zero. If *a sortslexicographically before *b, strcasecmp returns anumber less than zero.
Portabilitystrcasecmp is in the Berkeley Software Distribution.
strcasecmp requires no supporting OS subroutines. It usestolower() from elsewhere in this library.
Next: strcat—concatenate strings, Previous: strcasecmp—case-insensitive character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strcasestr—case-insensitive character string searchSynopsis
#include <string.h>char *strcasestr(const char *s, const char *find);
Descriptionstrcasestr searchs the string s forthe first occurrence of the sequence find. strcasestris identical to strstr except the search iscase-insensitive.
Returns
A pointer to the first case-insensitive occurrence of the sequencefind or NULL if no match was found.
Portabilitystrcasestr is in the Berkeley Software Distribution.
strcasestr requires no supporting OS subroutines. It usestolower() from elsewhere in this library.
Next: strchr—search for character in string, Previous: strcasestr—case-insensitive character string search, Up: Strings and Memory (string.h)   [Contents][Index]
strcat—concatenate stringsSynopsis
#include <string.h>char *strcat(char *restrict dst, const char *restrict src);
Descriptionstrcat appends a copy of the string pointed to by src(including the terminating null character) to the end of thestring pointed to by dst. The initial character ofsrc overwrites the null character at the end of dst.
Returns
This function returns the initial value of dst
Portabilitystrcat is ANSI C.
strcat requires no supporting OS subroutines.
Next: strchrnul—search for character in string, Previous: strcat—concatenate strings, Up: Strings and Memory (string.h)   [Contents][Index]
strchr—search for character in stringSynopsis
#include <string.h>char * strchr(const char *string, int c);
Description
This function finds the first occurence of c (converted toa char) in the string pointed to by string (including theterminating null character).
Returns
Returns a pointer to the located character, or a null pointerif c does not occur in string.
Portabilitystrchr is ANSI C.
strchr requires no supporting OS subroutines.
Next: strcmp—character string compare, Previous: strchr—search for character in string, Up: Strings and Memory (string.h)   [Contents][Index]
strchrnul—search for character in stringSynopsis
#include <string.h>char * strchrnul(const char *string, int c);
Description
This function finds the first occurence of c (converted toa char) in the string pointed to by string (including theterminating null character).
Returns
Returns a pointer to the located character, or a pointerto the concluding null byte if c does not occur in string.
Portabilitystrchrnul is a GNU extension.
strchrnul requires no supporting OS subroutines. It usesstrchr() and strlen() from elsewhere in this library.
Next: strcoll—locale-specific character string compare, Previous: strchrnul—search for character in string, Up: Strings and Memory (string.h)   [Contents][Index]
strcmp—character string compareSynopsis
#include <string.h>int strcmp(const char *a, const char *b);
Descriptionstrcmp compares the string at a tothe string at b.
Returns
If *a sorts lexicographically after *b,strcmp returns a number greater than zero. If the twostrings match, strcmp returns zero. If *asorts lexicographically before *b, strcmp returns anumber less than zero.
Portabilitystrcmp is ANSI C.
strcmp requires no supporting OS subroutines.
Next: strcpy—copy string, Previous: strcmp—character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strcoll—locale-specific character string compareSynopsis
#include <string.h>int strcoll(const char *stra, const char * strb);
Descriptionstrcoll compares the string pointed to by stra tothe string pointed to by strb, using an interpretationappropriate to the current LC_COLLATE state.
(NOT Cygwin:) The current implementation of strcoll simplyuses strcmp and does not support any language-specific sorting.
Returns
If the first string is greater than the second string,strcoll returns a number greater than zero. If the twostrings are equivalent, strcoll returns zero. If the firststring is less than the second string, strcoll returns anumber less than zero.
Portabilitystrcoll is ANSI C.
strcoll requires no supporting OS subroutines.
Next: strcspn—count characters not in string, Previous: strcoll—locale-specific character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strcpy—copy stringSynopsis
#include <string.h>char *strcpy(char *dst, const char *src);
Descriptionstrcpy copies the string pointed to by src(including the terminating null character) to the arraypointed to by dst.
Returns
This function returns the initial value of dst.
Portabilitystrcpy is ANSI C.
strcpy requires no supporting OS subroutines.
Next: strerror, strerror_l—convert error number to string, Previous: strcpy—copy string, Up: Strings and Memory (string.h)   [Contents][Index]
strcspn—count characters not in stringSynopsis
size_t strcspn(const char *s1, const char *s2);
Description
This function computes the length of the initial part ofthe string pointed to by s1 which consists entirely ofcharacters NOT from the string pointed to by s2(excluding the terminating null character).
Returnsstrcspn returns the length of the substring found.
Portabilitystrcspn is ANSI C.
strcspn requires no supporting OS subroutines.
Next: strerror_r—convert error number to string and copy to buffer, Previous: strcspn—count characters not in string, Up: Strings and Memory (string.h)   [Contents][Index]
strerror, strerror_l—convert error number to stringSynopsis
#include <string.h>char *strerror(int errnum);char *strerror_l(int errnum, locale_t locale);char *_strerror_r(struct _reent ptr, int errnum, int internal, int *error);
Descriptionstrerror converts the error number errnum into astring. The value of errnum is usually a copy of errno.If errnum is not a known error number, the result points to anempty string.
strerror_l is like strerror but creates a string in a formatas expected in locale locale. If locale is LC_GLOBAL_LOCALE ornot a valid locale object, the behaviour is undefined.
This implementation of strerror prints out the following stringsfor each of the values defined in ‘errno.h’:
0Success
E2BIGArg list too long
EACCESPermission denied
EADDRINUSEAddress already in use
EADDRNOTAVAILAddress not available
EADVAdvertise error
EAFNOSUPPORTAddress family not supported by protocol family
EAGAINNo more processes
EALREADYSocket already connected
EBADFBad file number
EBADMSGBad message
EBUSYDevice or resource busy
ECANCELEDOperation canceled
ECHILDNo children
ECOMMCommunication error
ECONNABORTEDSoftware caused connection abort
ECONNREFUSEDConnection refused
ECONNRESETConnection reset by peer
EDEADLKDeadlock
EDESTADDRREQDestination address required
EEXISTFile exists
EDOMMathematics argument out of domain of function
EFAULTBad address
EFBIGFile too large
EHOSTDOWNHost is down
EHOSTUNREACHHost is unreachable
EIDRMIdentifier removed
EILSEQIllegal byte sequence
EINPROGRESSConnection already in progress
EINTRInterrupted system call
EINVALInvalid argument
EIOI/O error
EISCONNSocket is already connected
EISDIRIs a directory
ELIBACCCannot access a needed shared library
ELIBBADAccessing a corrupted shared library
ELIBEXECCannot exec a shared library directly
ELIBMAXAttempting to link in more shared libraries than system limit
ELIBSCN.lib section in a.out corrupted
EMFILEFile descriptor value too large
EMLINKToo many links
EMSGSIZEMessage too long
EMULTIHOPMultihop attempted
ENAMETOOLONGFile or path name too long
ENETDOWNNetwork interface is not configured
ENETRESETConnection aborted by network
ENETUNREACHNetwork is unreachable
ENFILEToo many open files in system
ENOBUFSNo buffer space available
ENODATANo data
ENODEVNo such device
ENOENTNo such file or directory
ENOEXECExec format error
ENOLCKNo lock
ENOLINKVirtual circuit is gone
ENOMEMNot enough space
ENOMSGNo message of desired type
ENONETMachine is not on the network
ENOPKGNo package
ENOPROTOOPTProtocol not available
ENOSPCNo space left on device
ENOSRNo stream resources
ENOSTRNot a stream
ENOSYSFunction not implemented
ENOTBLKBlock device required
ENOTCONNSocket is not connected
ENOTDIRNot a directory
ENOTEMPTYDirectory not empty
ENOTRECOVERABLEState not recoverable
ENOTSOCKSocket operation on non-socket
ENOTSUPNot supported
ENOTTYNot a character device
ENXIONo such device or address
EOPNOTSUPPOperation not supported on socket
EOVERFLOWValue too large for defined data type
EOWNERDEADPrevious owner died
EPERMNot owner
EPIPEBroken pipe
EPROTOProtocol error
EPROTOTYPEProtocol wrong type for socket
EPROTONOSUPPORTUnknown protocol
ERANGEResult too large
EREMOTEResource is remote
EROFSRead-only file system
ESHUTDOWNCan’t send after socket shutdown
ESOCKTNOSUPPORTSocket type not supported
ESPIPEIllegal seek
ESRCHNo such process
ESRMNTSrmount error
ESTRPIPEStrings pipe error
ETIMEStream ioctl timeout
ETIMEDOUTConnection timed out
ETXTBSYText file busy
EWOULDBLOCKOperation would block (usually same as EAGAIN)
EXDEVCross-device link
_strerror_r is a reentrant version of the above.
Returns
This function returns a pointer to a string. Your application mustnot modify that string.
Portability
ANSI C requires strerror, but does not specify the strings usedfor each error number.
strerror_l is POSIX-1.2008.
Although this implementation of strerror is reentrant (dependingon _user_strerror), ANSI C declares that subsequent calls tostrerror may overwrite the result string; therefore portablecode cannot depend on the reentrancy of this subroutine.
Although this implementation of strerror guarantees a non-nullresult with a NUL-terminator, some implementations return NULLon failure. Although POSIX allows strerror to set errnoto EINVAL on failure, this implementation does not do so (unlessyou provide _user_strerror).
POSIX recommends that unknown errnum result in a messageincluding that value, however it is not a requirement and thisimplementation does not provide that information (unless youprovide _user_strerror).
This implementation of strerror provides for user-definedextensibility. errno.h defines __ELASTERROR, which can beused as a base for user-defined error values. If the user supplies aroutine named _user_strerror, and errnum passed tostrerror does not match any of the supported values,_user_strerror is called with three arguments. The first is oftype int, and is the errnum value unknown to strerror.The second is of type int, and matches the internal argumentof _strerror_r; this should be zero if called from strerrorand non-zero if called from any other function; _user_strerror canuse this information to satisfy the POSIX rule that no otherstandardized function can overwrite a static buffer reused bystrerror. The third is of type int *, and matches theerror argument of _strerror_r; if a non-zero value is storedinto that location (usually EINVAL), then strerror will seterrno to that value, and the XPG variant of strerror_r willreturn that value instead of zero or ERANGE. _user_strerrorreturns a char * value; returning NULL implies that the userfunction did not choose to handle errnum. The default_user_strerror returns NULL for all input values. Note that_user_sterror must be thread-safe, and only denote errors via thethird argument rather than modifying errno, if strerror andstrerror_r are are to comply with POSIX.
strerror requires no supporting OS subroutines.
Next: strlen—character string length, Previous: strerror, strerror_l—convert error number to string, Up: Strings and Memory (string.h)   [Contents][Index]
strerror_r—convert error number to string and copy to bufferSynopsis
#include <string.h>#ifdef _GNU_SOURCEchar *strerror_r(int errnum, char *buffer, size_t n);#elseint strerror_r(int errnum, char *buffer, size_t n);#endif
Descriptionstrerror_r converts the error number errnum into astring and copies the result into the supplied buffer fora length up to n, including the NUL terminator. The value oferrnum is usually a copy of errno. If errnum is not a knownerror number, the result is the empty string.
See strerror for how strings are mapped to errnum.
Returns
There are two variants: the GNU version always returns a NUL-terminatedstring, which is buffer if all went well, but which is anotherpointer if n was too small (leaving buffer untouched). If thereturn is not buffer, your application must not modify that string.The POSIX version returns 0 on success, EINVAL if errnum was notrecognized, and ERANGE if n was too small. The variant chosendepends on macros that you define before inclusion of string.h.
Portabilitystrerror_r with a char * result is a GNU extension.strerror_r with an int result is required by POSIX 2001.This function is compliant only if _user_strerror is not provided,or if it is thread-safe and uses separate storage according to whetherthe second argument of that function is non-zero. For more detailson _user_strerror, see the strerror documentation.
POSIX states that the contents of buf are unspecified on error,although this implementation guarantees a NUL-terminated string forall except n of 0.
POSIX recommends that unknown errnum result in a message includingthat value, however it is not a requirement and this implementationprovides only an empty string (unless you provide _user_strerror).POSIX also recommends that unknown errnum fail with EINVAL evenwhen providing such a message, however it is not a requirement andthis implementation will return success if _user_strerror provideda non-empty alternate string without assigning into its third argument.
strerror_r requires no supporting OS subroutines.
Next: strlwr—force string to lowercase, Previous: strerror_r—convert error number to string and copy to buffer, Up: Strings and Memory (string.h)   [Contents][Index]
strlen—character string lengthSynopsis
#include <string.h>size_t strlen(const char *str);
Description
The strlen function works out the length of the stringstarting at *str by counting chararacters until itreaches a NULL character.
Returnsstrlen returns the character count.
Portabilitystrlen is ANSI C.
strlen requires no supporting OS subroutines.
Next: strncasecmp—case-insensitive character string compare, Previous: strlen—character string length, Up: Strings and Memory (string.h)   [Contents][Index]
strlwr—force string to lowercaseSynopsis
#include <string.h>char *strlwr(char *a);
Descriptionstrlwr converts each character in the string at a tolowercase.
Returnsstrlwr returns its argument, a.
Portabilitystrlwr is not widely portable.
strlwr requires no supporting OS subroutines.
Next: strncat—concatenate strings, Previous: strlwr—force string to lowercase, Up: Strings and Memory (string.h)   [Contents][Index]
strncasecmp—case-insensitive character string compareSynopsis
#include <strings.h>int strncasecmp(const char *a, const char * b, size_t length);
Descriptionstrncasecmp compares up to length charactersfrom the string at a to the string at b in acase-insensitive manner.
Returns
If *a sorts lexicographically after *b (afterboth are converted to lowercase), strncasecmp returns anumber greater than zero. If the two strings are equivalent,strncasecmp returns zero. If *a sortslexicographically before *b, strncasecmp returns anumber less than zero.
Portabilitystrncasecmp is in the Berkeley Software Distribution.
strncasecmp requires no supporting OS subroutines. It usestolower() from elsewhere in this library.
Next: strncmp—character string compare, Previous: strncasecmp—case-insensitive character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strncat—concatenate stringsSynopsis
#include <string.h>char *strncat(char *restrict dst, const char *restrict src, size_t length);
Descriptionstrncat appends not more than length characters fromthe string pointed to by src (including the	terminatingnull character) to the end of the string pointed to bydst. The initial character of src overwrites the nullcharacter at the end of dst. A terminating null characteris always appended to the result
Warnings
Note that a null is always appended, so that if the copy islimited by the length argument, the number of charactersappended to dst is n + 1.
Returns
This function returns the initial value of dst
Portabilitystrncat is ANSI C.
strncat requires no supporting OS subroutines.
Next: strncpy—counted copy string, Previous: strncat—concatenate strings, Up: Strings and Memory (string.h)   [Contents][Index]
strncmp—character string compareSynopsis
#include <string.h>int strncmp(const char *a, const char * b, size_t length);
Descriptionstrncmp compares up to length charactersfrom the string at a to the string at b.
Returns
If *a sorts lexicographically after *b,strncmp returns a number greater than zero. If the twostrings are equivalent, strncmp returns zero. If *asorts lexicographically before *b, strncmp returns anumber less than zero.
Portabilitystrncmp is ANSI C.
strncmp requires no supporting OS subroutines.
Next: strnstr—find string segment, Previous: strncmp—character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strncpy—counted copy stringSynopsis
#include <string.h>char *strncpy(char *restrict dst, const char *restrict src, size_t length);
Descriptionstrncpy copies not more than length characters from thethe string pointed to by src (including the terminatingnull character) to the array pointed to by dst. If thestring pointed to by src is shorter than lengthcharacters, null characters are appended to the destinationarray until a total of length characters have beenwritten.
Returns
This function returns the initial value of dst.
Portabilitystrncpy is ANSI C.
strncpy requires no supporting OS subroutines.
Next: strnlen—character string length, Previous: strncpy—counted copy string, Up: Strings and Memory (string.h)   [Contents][Index]
strnstr—find string segmentSynopsis
#include <string.h>size_t strnstr(const char *s1, const char *s2, size_t n);
Description
Locates the first occurrence in the string pointed to by s1 ofthe sequence of limited to the n characters in the stringpointed to by s2
Returns
Returns a pointer to the located string segment, or a nullpointer if the string s2 is not found. If s2 points toa string with zero length, s1 is returned.
Portabilitystrnstr is a BSD extension.
strnstr requires no supporting OS subroutines.
Next: strpbrk—find characters in string, Previous: strnstr—find string segment, Up: Strings and Memory (string.h)   [Contents][Index]
strnlen—character string lengthSynopsis
#include <string.h>size_t strnlen(const char *str, size_t n);
Description
The strnlen function works out the length of the stringstarting at *str by counting chararacters until itreaches a NUL character or the maximum: n number ofcharacters have been inspected.
Returnsstrnlen returns the character count or n.
Portabilitystrnlen is a GNU extension.
strnlen requires no supporting OS subroutines.
Next: strrchr—reverse search for character in string, Previous: strnlen—character string length, Up: Strings and Memory (string.h)   [Contents][Index]
strpbrk—find characters in stringSynopsis
#include <string.h>char *strpbrk(const char *s1, const char *s2);
Description
This function locates the first occurence in the stringpointed to by s1 of any character in string pointed to bys2 (excluding the terminating null character).
Returnsstrpbrk returns a pointer to the character found in s1, or anull pointer if no character from s2 occurs in s1.
Portabilitystrpbrk requires no supporting OS subroutines.
Next: strsignal—convert signal number to string, Previous: strpbrk—find characters in string, Up: Strings and Memory (string.h)   [Contents][Index]
strrchr—reverse search for character in stringSynopsis
#include <string.h>char * strrchr(const char *string, int c);
Description
This function finds the last occurence of c (converted toa char) in the string pointed to by string (including theterminating null character).
Returns
Returns a pointer to the located character, or a null pointerif c does not occur in string.
Portabilitystrrchr is ANSI C.
strrchr requires no supporting OS subroutines.
Next: strspn—find initial match, Previous: strrchr—reverse search for character in string, Up: Strings and Memory (string.h)   [Contents][Index]
strsignal—convert signal number to stringSynopsis
#include <string.h>char *strsignal(int signal);
Descriptionstrsignal converts the signal number signal into astring. If signal is not a known signal number, the resultwill be of the form "Unknown signal NN" where NN is the signalis a decimal number.
Returns
This function returns a pointer to a string. Your application mustnot modify that string.
Portability
POSIX.1-2008 C requires strsignal, but does not specify the strings usedfor each signal number.
strsignal requires no supporting OS subroutines.
Next: strstr—find string segment, Previous: strsignal—convert signal number to string, Up: Strings and Memory (string.h)   [Contents][Index]
strspn—find initial matchSynopsis
#include <string.h>size_t strspn(const char *s1, const char *s2);
Description
This function computes the length of the initial segment ofthe string pointed to by s1 which consists entirely ofcharacters from the string pointed to by s2 (excluding theterminating null character).
Returnsstrspn returns the length of the segment found.
Portabilitystrspn is ANSI C.
strspn requires no supporting OS subroutines.
Next: strtok, strtok_r, strsep—get next token from a string, Previous: strspn—find initial match, Up: Strings and Memory (string.h)   [Contents][Index]
strstr—find string segmentSynopsis
#include <string.h>char *strstr(const char *s1, const char *s2);
Description
Locates the first occurrence in the string pointed to by s1 ofthe sequence of characters in the string pointed to by s2(excluding the terminating null character).
Returns
Returns a pointer to the located string segment, or a nullpointer if the string s2 is not found. If s2 points toa string with zero length, s1 is returned.
Portabilitystrstr is ANSI C.
strstr requires no supporting OS subroutines.
Next: strupr—force string to uppercase, Previous: strstr—find string segment, Up: Strings and Memory (string.h)   [Contents][Index]
strtok, strtok_r, strsep—get next token from a stringSynopsis
#include <string.h>char *strtok(char *restrict source, const char *restrict delimiters);char *strtok_r(char *restrict source, const char *restrict delimiters, char **lasts);char *strsep(char **source_ptr, const char *delimiters);
Description
The strtok function is used to isolate sequential tokens in anull-terminated string, *source. These tokens are delimitedin the string by at least one of the characters in *delimiters.The first time that strtok is called, *source should bespecified; subsequent calls, wishing to obtain further tokens fromthe same string, should pass a null pointer instead. The separatorstring, *delimiters, must be supplied each time and maychange between calls.
The strtok function returns a pointer to the beginning of eachsubsequent token in the string, after replacing the separatorcharacter itself with a null character. When no more tokens remain,a null pointer is returned.
The strtok_r function has the same behavior as strtok, excepta pointer to placeholder *lasts must be supplied by the caller.
The strsep function is similar in behavior to strtok, excepta pointer to the string pointer must be supplied source_ptr andthe function does not skip leading delimiters. When the string startswith a delimiter, the delimiter is changed to the null character andthe empty string is returned. Like strtok_r and strtok, the*source_ptr is updated to the next character following thelast delimiter found or NULL if the end of string is reached withno more delimiters.
Returnsstrtok, strtok_r, and strsep all return a pointer to thenext token, or NULL if no more tokens can be found. Forstrsep, a token may be the empty string.
Notesstrtok is unsafe for multi-threaded applications. strtok_rand strsep are thread-safe and should be used instead.
Portabilitystrtok is ANSI C.strtok_r is POSIX.strsep is a BSD extension.
strtok, strtok_r, and strsep require no supporting OS subroutines.
Next: strverscmp—version string compare, Previous: strtok, strtok_r, strsep—get next token from a string, Up: Strings and Memory (string.h)   [Contents][Index]
strupr—force string to uppercaseSynopsis
#include <string.h>char *strupr(char *a);
Descriptionstrupr converts each character in the string at a touppercase.
Returnsstrupr returns its argument, a.
Portabilitystrupr is not widely portable.
strupr requires no supporting OS subroutines.
Next: strxfrm—transform string, Previous: strupr—force string to uppercase, Up: Strings and Memory (string.h)   [Contents][Index]
strverscmp—version string compareSynopsis
#define _GNU_SOURCE#include <string.h>int strverscmp(const char *a, const char *b);
Descriptionstrverscmp compares the string at a tothe string at b in a version-logical order.
Returns
If *a version-sorts after *b, strverscmp returnsa number greater than zero. If the two strings match, strverscmpreturns zero. If *a version-sorts before *b,strverscmp returns a number less than zero.
Portabilitystrverscmp is a GNU extension.
strverscmp requires no supporting OS subroutines. It usesisdigit() from elsewhere in this library.
Next: swab—swap adjacent bytes, Previous: strverscmp—version string compare, Up: Strings and Memory (string.h)   [Contents][Index]
strxfrm—transform stringSynopsis
#include <string.h>size_t strxfrm(char *restrict s1, const char *restrict s2, size_t n);
Description
This function transforms the string pointed to by s2 andplaces the resulting string into the array pointed to bys1. The transformation is such that if the strcmpfunction is applied to the two transformed strings, it returnsa value greater than, equal to, or less than zero,correspoinding to the result of a strcoll function appliedto the same two original strings.
No more than n characters are placed into the resultingarray pointed to by s1, including the terminating nullcharacter. If n is zero, s1 may be a null pointer. Ifcopying takes place between objects that overlap, the behavioris undefined.
(NOT Cygwin:) The current implementation of strxfrm simply copiesthe input and does not support any language-specific transformations.
Returns
The strxfrm function returns the length of the transformed string(not including the terminating null character). If the value returnedis n or more, the contents of the array pointed to bys1 are indeterminate.
Portabilitystrxfrm is ANSI C.
strxfrm requires no supporting OS subroutines.
Next: wcscasecmp—case-insensitive wide character string compare, Previous: strxfrm—transform string, Up: Strings and Memory (string.h)   [Contents][Index]
swab—swap adjacent bytesSynopsis
#include <unistd.h>void swab(const void *in, void *out, ssize_t n);
Description
This function copies n bytes from the memory regionpointed to by in to the memory region pointed to byout, exchanging adjacent even and odd bytes.
Portabilityswab requires no supporting OS subroutines.
Next: wcsdup—wide character string duplicate, Previous: swab—swap adjacent bytes, Up: Strings and Memory (string.h)   [Contents][Index]
wcscasecmp—case-insensitive wide character string compareSynopsis
#include <wchar.h>int wcscasecmp(const wchar_t *a, const wchar_t *b);
Descriptionwcscasecmp compares the wide character string at a tothe wide character string at b in a case-insensitive manner.
Returns
If *a sorts lexicographically after *b (afterboth are converted to uppercase), wcscasecmp returns anumber greater than zero. If the two strings match,wcscasecmp returns zero. If *a sortslexicographically before *b, wcscasecmp returns anumber less than zero.
Portability
POSIX-1.2008
wcscasecmp requires no supporting OS subroutines. It usestolower() from elsewhere in this library.
Next: wcsncasecmp—case-insensitive wide character string compare, Previous: wcscasecmp—case-insensitive wide character string compare, Up: Strings and Memory (string.h)   [Contents][Index]
wcsdup—wide character string duplicateSynopsis
#include <wchar.h>wchar_t *wcsdup(const wchar_t *str);#include <wchar.h>wchar_t *_wcsdup_r(struct _reent *ptr, const wchar_t *str);
Descriptionwcsdup allocates a new wide character string using malloc,and copies the content of the argument str into the newlyallocated string, thus making a copy of str.
Returnswcsdup returns a pointer to the copy of str if enoughmemory for the copy was available. Otherwise it returns NULLand errno is set to ENOMEM.
Portability
POSIX-1.2008
Previous: wcsdup—wide character string duplicate, Up: Strings and Memory (string.h)   [Contents][Index]
wcsncasecmp—case-insensitive wide character string compareSynopsis
#include <wchar.h>int wcsncasecmp(const wchar_t *a, const wchar_t * b, size_t length);
Descriptionwcsncasecmp compares up to length wide charactersfrom the string at a to the string at b in acase-insensitive manner.
Returns
If *a sorts lexicographically after *b (afterboth are converted to uppercase), wcsncasecmp returns anumber greater than zero. If the two strings are equivalent,wcsncasecmp returns zero. If *a sortslexicographically before *b, wcsncasecmp returns anumber less than zero.
Portability
POSIX-1.2008
wcsncasecmp requires no supporting OS subroutines. It usestolower() from elsewhere in this library.
Next: Signal Handling (signal.h), Previous: Strings and Memory (string.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter describes wide-character string-handling functions andmanaging areas of memory containing wide characters. The correspondingdeclarations are in wchar.h.
wmemchr—find a wide character in memorywmemcmp—compare wide characters in memorywmemcpy—copy wide characters in memorywmemmove—copy wide characters in memory with overlapping areaswmempcpy—copy wide characters in memory and return end pointerwmemset—set wide characters in memorywcscat—concatenate two wide-character stringswcschr—wide-character string scanning operationwcscmp—compare two wide-character stringswcscoll—locale-specific wide-character string comparewcscpy—copy a wide-character stringwcpcpy—copy a wide-character string returning a pointer to its endwcscspn—get length of a complementary wide substringwcsftime—convert date and time to a formatted wide-character stringwcslcat—concatenate wide-character strings to specified lengthwcslcpy—copy a wide-character string to specified lengthwcslen—get wide-character string lengthwcsncat—concatenate part of two wide-character stringswcsncmp—compare part of two wide-character stringswcsncpy—copy part of a wide-character stringwcpncpy—copy part of a wide-character string returning a pointer to its endwcsnlen—get fixed-size wide-character string lengthwcspbrk—-scan wide-character string for a wide-character codewcsrchr—wide-character string scanning operationwcsspn—get length of a wide substringwcsstr—find a wide-character substringwcstok—get next token from a stringwcswidth—number of column positions of a wide-character stringwcsxfrm—locale-specific wide-character string transformationwcwidth—number of column positions of a wide-character codeNext: wmemcmp—compare wide characters in memory, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmemchr—find a wide character in memorySynopsis
#include <wchar.h>wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n);
Description
The wmemchr function locates the first occurrence of c in theinitial n wide characters of the object pointed to be s. Thisfunction is not affected by locale and all wchar_t values are treatedidentically. The null wide character and wchar_t values notcorresponding to valid characters are not treated specially.
If n is zero, s must be a valid pointer and the functionbehaves as if no valid occurrence of c is found.
Returns
The wmemchr function returns a pointer to the locatedwide character, or a null pointer if the wide character does not occurin the object. 
Portabilitywmemchr is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wmemcpy—copy wide characters in memory, Previous: wmemchr—find a wide character in memory, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmemcmp—compare wide characters in memorySynopsis
#include <wchar.h>int wmemcmp(const wchar_t *s1, const wchar_t *s2, size_t n);
Description
The wmemcmp function compares the first n wide characters of theobject pointed to by s1 to the first n wide characters of theobject pointed to by s2. This function is not affected by localeand all wchar_t values are treated identically. The null wide characterand wchar_t values not corresponding to valid characters are not treatedspecially.
If n is zero, s1 and s2 must be a valid pointers and thefunction behaves as if the two objects compare equal.
Returns
The wmemcmp function returns an integer greater than, equal to,or less than zero, accordingly as the object pointed to by s1 isgreater than, equal to, or less than the object pointed to by s2.
Portabilitywmemcmp is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wmemmove—copy wide characters in memory with overlapping areas, Previous: wmemcmp—compare wide characters in memory, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmemcpy—copy wide characters in memorySynopsis
#include <wchar.h>wchar_t *wmemcpy(wchar_t *__restrict d, const wchar_t *__restrict s, size_t n);
Description
The wmemcpy function copies n wide characters from the objectpointed to by s to the object pointed to be d. This functionis not affected by locale and all wchar_t values are treatedidentically. The null wide character and wchar_t values notcorresponding to valid characters are not treated specially.
If n is zero, d and s must be a valid pointers, and thefunction copies zero wide characters.
Returns
The wmemcpy function returns the value of d.
Portabilitywmemcpy is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wmempcpy—copy wide characters in memory and return end pointer, Previous: wmemcpy—copy wide characters in memory, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmemmove—copy wide characters in memory with overlapping areasSynopsis
#include <wchar.h>wchar_t *wmemmove(wchar_t *d, const wchar_t *s, size_t n);
Description
The wmemmove function copies n wide characters from the objectpointed to by s to the object pointed to by d. Copying takesplace as if the n wide characters from the object pointed to bys are first copied into a temporary array of n wide charactersthat does not overlap the objects pointed to by d or s, and thenthe n wide characters from the temporary array are copied into theobject pointed to by d.
This function is not affected by locale and all wchar_t values aretreated identically. The null wide character and wchar_t values notcorresponding to valid characters are not treated specially.
If n is zero, d and s must be a valid pointers, and thefunction copies zero wide characters.
Returns
The wmemmove function returns the value of d.
Portabilitywmemmove is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wmemset—set wide characters in memory, Previous: wmemmove—copy wide characters in memory with overlapping areas, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmempcpy—copy wide characters in memory and return end pointerSynopsis
#define _GNU_SOURCE#include <wchar.h>wchar_t *wmempcpy(wchar_t *d, const wchar_t *s, size_t n);
Description
The wmemcpy function copies n wide characters from the objectpointed to by s to the object pointed to be d. This functionis not affected by locale and all wchar_t values are treatedidentically. The null wide character and wchar_t values notcorresponding to valid characters are not treated specially.
If n is zero, d and s must be a valid pointers, and thefunction copies zero wide characters.
Returnswmempcpy returns a pointer to the wide character following thelast wide character copied to the out region.
Portabilitywmempcpy is a GNU extension.
No supporting OS subroutines are required.
Next: wcscat—concatenate two wide-character strings, Previous: wmempcpy—copy wide characters in memory and return end pointer, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wmemset—set wide characters in memorySynopsis
#include <wchar.h>wchar_t *wmemset(wchar_t *s, wchar_t c, size_t n);
Description
The wmemset function copies the value of c into each of thefirst n wide characters of the object pointed to by s. Thisfunction is not affected by locale and all wchar_t values are treatedidentically. The null wide character and wchar_t values notcorresponding to valid characters are not treated specially.
If n is zero, s must be a valid pointer and the functioncopies zero wide characters.
Returns
The wmemset function returns the value of s.
Portabilitywmemset is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcschr—wide-character string scanning operation, Previous: wmemset—set wide characters in memory, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcscat—concatenate two wide-character stringsSynopsis
#include <wchar.h>wchar_t *wcscat(wchar_t *__restrict s1, const wchar_t *__restrict s2);
Description
The wcscat function appends a copy of the wide-character stringpointed to by s2 (including the terminating null wide-charactercode) to the end of the wide-character string pointed to by s1.The initial wide-character code of s2 overwrites the nullwide-character code at the end of s1. If copying takes place betweenobjects that overlap, the behaviour is undefined. 
Returns
The wcscat function returns s1;no return value is reserved to indicate an error. 
Portabilitywcscat is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcscmp—compare two wide-character strings, Previous: wcscat—concatenate two wide-character strings, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcschr—wide-character string scanning operationSynopsis
#include <wchar.h>wchar_t *wcschr(const wchar_t *s, wchar_t c);
Description
The wcschr function locates the first occurrence of c in thewide-character string pointed to by s. The value of c must be acharacter representable as a type wchar_t and must be a wide-charactercode corresponding to a valid character in the current locale.The terminating null wide-character string.
Returns
Upon completion, wcschr returns a pointer to the wide-charactercode, or a null pointer if the wide-character code is not found. 
Portabilitywcschr is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcscoll—locale-specific wide-character string compare, Previous: wcschr—wide-character string scanning operation, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcscmp—compare two wide-character stringsSynopsis
#include <wchar.h>int wcscmp(const wchar_t *s1, *s2);
Description
The wcscmp function compares the wide-character string pointed toby s1 to the wide-character string pointed to by s2.
The sign of a non-zero return value is determined by the sign of thedifference between the values of the first pair of wide-character codesthat differ in the objects being compared.
Returns
Upon completion, wcscmp returns an integer greater than, equal toor less than 0, if the wide-character string pointed to by s1 isgreater than, equal to or less than the wide-character string pointedto by s2 respectively. 
Portabilitywcscmp is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcscpy—copy a wide-character string, Previous: wcscmp—compare two wide-character strings, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcscoll—locale-specific wide-character string compareSynopsis
#include <wchar.h>int wcscoll(const wchar_t *stra, const wchar_t * strb);
Descriptionwcscoll compares the wide-character string pointed to bystra to the wide-character string pointed to by strb,using an interpretation appropriate to the current LC_COLLATEstate.
(NOT Cygwin:) The current implementation of wcscoll simplyuses wcscmp and does not support any language-specific sorting.
Returns
If the first string is greater than the second string,wcscoll returns a number greater than zero. If the twostrings are equivalent, wcscoll returns zero. If the firststring is less than the second string, wcscoll returns anumber less than zero.
Portabilitywcscoll is ISO/IEC 9899/AMD1:1995 (ISO C).
Next: wcpcpy—copy a wide-character string returning a pointer to its end, Previous: wcscoll—locale-specific wide-character string compare, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcscpy—copy a wide-character stringSynopsis
#include <wchar.h>wchar_t *wcscpy(wchar_t *__restrict s1, const wchar_t *__restrict s2);
Description
The wcscpy function copies the wide-character string pointed to bys2 (including the terminating null wide-character code) into thearray pointed to by s1. If copying takes place between objects thatoverlap, the behaviour is undefined. 
Returns
The wcscpy function returns s1; no return value is reserved toindicate an error. 
Portabilitywcscpy is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcscspn—get length of a complementary wide substring, Previous: wcscpy—copy a wide-character string, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcpcpy—copy a wide-character string returning a pointer to its endSynopsis
#include <wchar.h>wchar_t *wcpcpy(wchar_t *s1, const wchar_t *s2);
Description
The wcpcpy function copies the wide-character string pointed to bys2 (including the terminating null wide-character code) into thearray pointed to by s1. If copying takes place between objects thatoverlap, the behaviour is undefined. 
Returns
This function returns a pointer to the end of the destination string,thus pointing to the trailing ’\0’.
Portabilitywcpcpy is a GNU extension.
No supporting OS subroutines are required.
Next: wcsftime—convert date and time to a formatted wide-character string, Previous: wcpcpy—copy a wide-character string returning a pointer to its end, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcscspn—get length of a complementary wide substringSynopsis
#include <wchar.h>size_t wcscspn(const wchar_t *s, wchar_t *set);
Description
The wcscspn function computes the length of the maximum initialsegment of the wide-character string pointed to by s which consistsentirely of wide-character codes not from the wide-character stringpointed to by set. 
Returns
The wcscspn function returns the length of the initial substring ofs1; no return value is reserved to indicate an error.
Portabilitywcscspn is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcslcat—concatenate wide-character strings to specified length, Previous: wcscspn—get length of a complementary wide substring, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsftime—convert date and time to a formatted wide-character stringSynopsis
#include <time.h>#include <wchar.h>size_t wcsftime(wchar_t *s, size_t maxsize, const wchar_t *format, const struct tm *timp);
Descriptionwcsftime is equivalent to strftime, except that:
(The difference in all of the above being wide characters versus regularcharacters.)See strftime for the details of the format specifiers.
Returns
When the formatted time takes up no more than maxsize wide characters,the result is the length of the formatted wide string. Otherwise, if theformatting operation was abandoned due to lack of room, the result is0, and the wide-character string starting at s corresponds to just thoseparts of *format that could be completely filled in within themaxsize limit.
Portability
C99 and POSIX require wcsftime, but do not specify the contents of*s when the formatted string would require more thanmaxsize characters. Unrecognized specifiers and fields oftimp that are out of range cause undefined results. Since someformats expand to 0 bytes, it is wise to set *s to a nonzerovalue beforehand to distinguish between failure and an empty string.This implementation does not support s being NULL, nor overlappings and format.
wcsftime requires no supporting OS subroutines.
See Alsostrftime
Next: wcslcpy—copy a wide-character string to specified length, Previous: wcsftime—convert date and time to a formatted wide-character string, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcslcat—concatenate wide-character strings to specified lengthSynopsis
#include <wchar.h>size_t wcslcat(wchar_t *dst, const wchar_t *src, size_t siz);
Description
The wcslcat function appends wide characters from src toend of the dst wide-character string so that the resultantwide-character string is not more than siz wide charactersincluding the terminating null wide-character code. A terminatingnull wide character is always added unless siz is 0. Thus,the maximum number of wide characters that can be appended fromsrc is siz - 1. If copying takes place between objectsthat overlap, the behaviour is undefined.
Returns
Wide-character string length of initial dst plus thewide-character string length of src (does not includeterminating null wide-characters). If the return value isgreater than or equal to siz, then truncation occurred andnot all wide characters from src were appended.
Portability
No supporting OS subroutines are required.
Next: wcslen—get wide-character string length, Previous: wcslcat—concatenate wide-character strings to specified length, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcslcpy—copy a wide-character string to specified lengthSynopsis
#include <wchar.h>size_t wcslcpy(wchar_t *dst, const wchar_t *src, size_t siz);
Descriptionwcslcpy copies wide characters from src to dstsuch that up to siz - 1 characters are copied. Aterminating null is appended to the result, unless sizis zero.
Returnswcslcpy returns the number of wide characters in src,not including the terminating null wide character. If thereturn value is greater than or equal to siz, thennot all wide characters were copied from src and truncationoccurred.
Portability
No supporting OS subroutines are required.
Next: wcsncat—concatenate part of two wide-character strings, Previous: wcslcpy—copy a wide-character string to specified length, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcslen—get wide-character string lengthSynopsis
#include <wchar.h>size_t wcslen(const wchar_t *s);
Description
The wcslen function computes the number of wide-character codesin the wide-character string to which s points, not including theterminating null wide-character code.
Returns
The wcslen function returns the length of s; no return value isreserved to indicate an error.
Portabilitywcslen is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcsncmp—compare part of two wide-character strings, Previous: wcslen—get wide-character string length, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsncat—concatenate part of two wide-character stringsSynopsis
#include <wchar.h>wchar_t *wcsncat(wchar_t *__restrict s1, const wchar_t *__restrict s2, size_t n);
Description
The wcsncat function appends not more than n wide-charactercodes (a null wide-character code and wide-character codes that followit are not appended) from the array pointed to by s2 to the end ofthe wide-character string pointed to by s1. The initialwide-character code of s2 overwrites the null wide-character codeat the end of s1.A terminating null wide-character code is always appended to the result.If copying takes place between objects that overlap, the behaviour isundefined.
Returns
The wcsncat function returns s1; no return value is reserved toindicate an error.
Portabilitywcsncat is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcsncpy—copy part of a wide-character string, Previous: wcsncat—concatenate part of two wide-character strings, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsncmp—compare part of two wide-character stringsSynopsis
#include <wchar.h>int wcsncmp(const wchar_t *s1, const wchar_t *s2, size_t n);
Description
The wcsncmp function compares not more than n wide-charactercodes (wide-character codes that follow a null wide-character code arenot compared) from the array pointed to by s1 to the array pointedto by s2.
The sign of a non-zero return value is determined by the sign of thedifference between the values of the first pair of wide-character codesthat differ in the objects being compared.
Returns
Upon successful completion, wcsncmp returns an integer greater than,equal to or less than 0, if the possibly null-terminated array pointedto by s1 is greater than, equal to or less than the possiblynull-terminated array pointed to by s2 respectively. 
Portabilitywcsncmp is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcpncpy—copy part of a wide-character string returning a pointer to its end, Previous: wcsncmp—compare part of two wide-character strings, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsncpy—copy part of a wide-character stringSynopsis
#include <wchar.h>wchar_t *wcsncpy(wchar_t *__restrict s1, const wchar_t *__restrict s2, size_t n);
Description
The wcsncpy function copies not more than n wide-character codes(wide-character codes that follow a null wide-character code are notcopied) from the array pointed to by s2 to the array pointed toby s1. If copying takes place between objects that overlap, thebehaviour is undefined. Note that if s1 contains more than nwide characters before its terminating null, the result is notnull-terminated.
If the array pointed to by s2 is a wide-character string that isshorter than n wide-character codes, null wide-character codes areappended to the copy in the array pointed to by s1, until nwide-character codes in all are written.
Returns
The wcsncpy function returns s1; no return value is reserved toindicate an error. 
Portability
ISO/IEC 9899; POSIX.1.
No supporting OS subroutines are required.
Next: wcsnlen—get fixed-size wide-character string length, Previous: wcsncpy—copy part of a wide-character string, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcpncpy—copy part of a wide-character string returning a pointer to its endSynopsis
#include <wchar.h>wchar_t *wcpncpy(wchar_t *__restrict s1, const wchar_t *__restrict s2, size_t n);
Description
The wcpncpy function copies not more than n wide-character codes(wide-character codes that follow a null wide-character code are notcopied) from the array pointed to by s2 to the array pointed toby s1. If copying takes place between objects that overlap, thebehaviour is undefined.
If the array pointed to by s2 is a wide-character string that isshorter than n wide-character codes, null wide-character codes areappended to the copy in the array pointed to by s1, until nwide-character codes in all are written.
Returns
The wcpncpy function returns s1; no return value is reserved toindicate an error. 
Portabilitywcpncpy is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcspbrk—-scan wide-character string for a wide-character code, Previous: wcpncpy—copy part of a wide-character string returning a pointer to its end, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsnlen—get fixed-size wide-character string lengthSynopsis
#include <wchar.h>size_t wcsnlen(const wchar_t *s, size_t maxlen);
Description
The wcsnlen function computes the number of wide-character codesin the wide-character string pointed to by s not including theterminating L’\0’ wide character but at most maxlen widecharacters.
Returnswcsnlen returns the length of s if it is less then maxlen,or maxlen if there is no L’\0’ wide character in first maxlencharacters.
Portabilitywcsnlen is a GNU extension.
wcsnlen requires no supporting OS subroutines.
Next: wcsrchr—wide-character string scanning operation, Previous: wcsnlen—get fixed-size wide-character string length, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcspbrk—-scan wide-character string for a wide-character codeSynopsis
#include <wchar.h>wchar_t *wcspbrk(const wchar_t *s, const wchar_t *set);
Description
The wcspbrk function locates the first occurrence in thewide-character string pointed to by s of any wide-character codefrom the wide-character string pointed to by set. 
Returns
Upon successful completion, wcspbrk returns a pointer to thewide-character code or a null pointer if no wide-character code fromset occurs in s.
Portabilitywcspbrk is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcsspn—get length of a wide substring, Previous: wcspbrk—-scan wide-character string for a wide-character code, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsrchr—wide-character string scanning operationSynopsis
#include <wchar.h>wchar_t *wcsrchr(const wchar_t *s, wchar_t c);
Description
The wcsrchr function locates the last occurrence of c in thewide-character string pointed to by s. The value of c must be acharacter representable as a type wchar_t and must be a wide-charactercode corresponding to a valid character in the current locale.The terminating null wide-character code is considered to be part ofthe wide-character string. 
Returns
Upon successful completion, wcsrchr returns a pointer to thewide-character code or a null pointer if c does not occur in thewide-character string.
Portabilitywcsrchr is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcsstr—find a wide-character substring, Previous: wcsrchr—wide-character string scanning operation, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsspn—get length of a wide substringSynopsis
#include <wchar.h>size_t wcsspn(const wchar_t *s, const wchar_t *set);
Description
The wcsspn function computes the length of the maximum initialsegment of the wide-character string pointed to by s which consistsentirely of wide-character codes from the wide-character stringpointed to by set.
Returns
The wcsspn() function returns the length s1; no return value isreserved to indicate an error.
Portabilitywcsspn is ISO/IEC 9899/AMD1:1995 (ISO C).
No supporting OS subroutines are required.
Next: wcstok—get next token from a string, Previous: wcsspn—get length of a wide substring, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsstr—find a wide-character substringSynopsis
#include <wchar.h>wchar_t *wcsstr(const wchar_t *__restrict big, const wchar_t *__restrict little);
Description
The wcsstr function locates the first occurrence in thewide-character string pointed to by big of the sequence ofwide characters (excluding the terminating null wide character) in thewide-character string pointed to by little.
Returns
On successful completion, wcsstr returns a pointer to the locatedwide-character string, or a null pointer if the wide-character stringis not found.
If little points to a wide-character string with zero length,the function returns big.
Portabilitywcsstr is ISO/IEC 9899/AMD1:1995 (ISO C).
Next: wcswidth—number of column positions of a wide-character string, Previous: wcsstr—find a wide-character substring, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcstok—get next token from a stringSynopsis
#include <wchar.h>wchar_t *wcstok(wchar_t *__restrict source, const wchar_t *__restrict delimiters, wchar_t **__restrict lasts);
Description
The wcstok function is the wide-character equivalent of thestrtok_r function (which in turn is the same as the strtokfunction with an added argument to make it thread-safe).
The wcstok function is used to isolate (one at a time)sequential tokens in a null-terminated wide-character string,*source. A token is defined as a substring not containingany wide-characters from *delimiters.
The first time that wcstok is called, *source shouldbe specified with the wide-character string to be searched, and*lasts–but not lasts, which must be non-NULL–may berandom; subsequent calls, wishing to obtain further tokens fromthe same string, should pass a null pointer for *sourceinstead but must supply *lasts unchanged from the lastcall. The separator wide-character string, *delimiters,must be supplied each time and may change between calls.A pointer to placeholder *lasts must be supplied bythe caller, and is set each time as needed to save the stateby wcstok.	Every call to wcstok with *source== NULL must pass the value of *lasts as last setby wcstok.
The wcstok function returns a pointer to the beginning of eachsubsequent token in the string, after replacing the separatorwide-character itself with a null wide-character. When no more tokensremain, a null pointer is returned.
Returnswcstok returns a pointer to the first wide character of a token, orNULL if there is no token.
Noteswcstok is thread-safe (unlike strtok, but like strtok_r).wcstok writes into the string being searched.
Portabilitywcstok is C99 and POSIX.1-2001.
wcstok requires no supporting OS subroutines.
Next: wcsxfrm—locale-specific wide-character string transformation, Previous: wcstok—get next token from a string, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcswidth—number of column positions of a wide-character stringSynopsis
#include <wchar.h>int wcswidth(const wchar_t *pwcs, size_t n);
Description
The wcswidth function shall determine the number of columnpositions required for n wide-character codes (or fewer than nwide-character codes if a null wide-character code is encounteredbefore n wide-character codes are exhausted) in the string pointedto by pwcs.
Returns
The wcswidth function either shall return 0 (if pwcs points to anull wide-character code), or return the number of column positionsto be occupied by the wide-character string pointed to by pwcs, orreturn -1 (if any of the first n wide-character codes in thewide-character string pointed to by pwcs is not a printablewide-character code).
Portabilitywcswidth has been introduced in the Single UNIX Specification Volume 2.wcswidth has been marked as an extension in the Single UNIX Specification Volume 3.
Next: wcwidth—number of column positions of a wide-character code, Previous: wcswidth—number of column positions of a wide-character string, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcsxfrm—locale-specific wide-character string transformationSynopsis
#include <wchar.h>int wcsxfrm(wchar_t *__restrict stra, const wchar_t *__restrict strb, size_t n);
Descriptionwcsxfrm transforms the wide-character string pointed to bystrb to the wide-character string pointed to by stra,Comparing two transformed wide strings with wcscmp should returnthe same result as comparing the original strings with wcscoll.No more than n wide characters are transformed, including thetrailing null character.
If n is 0, stra may be a NULL pointer.
(NOT Cygwin:) The current implementation of wcsxfrm simply useswcslcpy and does not support any language-specific transformations.
Returnswcsxfrm returns the length of the transformed wide characterstring. if the return value is greater or equal to n, thecontent of stra is undefined.
Portabilitywcsxfrm is ISO/IEC 9899/AMD1:1995 (ISO C).
Previous: wcsxfrm—locale-specific wide-character string transformation, Up: Wide Character Strings (wchar.h)   [Contents][Index]
wcwidth—number of column positions of a wide-character codeSynopsis
#include <wchar.h>int wcwidth(const wint_t wc);
Description
The wcwidth function shall determine the number of columnpositions required for the wide character wc. The applicationshall ensure that the value of wc is a character representableas a wint_t (combining Unicode surrogate pairs into single 21-bitUnicode code points), and is a wide-character code corresponding to avalid character in the current locale.
Returns
The wcwidth function shall either return 0 (if wc is a nullwide-character code), or return the number of column positions tobe occupied by the wide-character code wc, or return -1 (if wcdoes not correspond to a printable wide-character code).
Portabilitywcwidth has been introduced in the Single UNIX Specification Volume 2.wcwidth has been marked as an extension in the Single UNIX Specification Volume 3.
Next: Time Functions (time.h), Previous: Wide Character Strings (wchar.h), Up: The Red Hat newlib C Library [Contents][Index]
A signal is an event that interrupts the normal flow of controlin your program. Your operating environment normally defines the fullset of signals available (see sys/signal.h), as well as thedefault means of dealing with them—typically, either printing anerror message and aborting your program, or ignoring the signal.
All systems support at least the following signals:
SIGABRTAbnormal termination of a program; raised by the abort function.
SIGFPEA domain error in arithmetic, such as overflow, or division by zero.
SIGILLAttempt to execute as a function data that is not executable.
SIGINTInterrupt; an interactive attention signal.
SIGSEGVAn attempt to access a memory location that is not available.
SIGTERMA request that your program end execution.
Two functions are available for dealing with asynchronoussignals—one to allow your program to send signals to itself (this iscalled raising a signal), and one to specify subroutines (calledhandlers to handle particular signals that you anticipate mayoccur—whether raised by your own program or the operating environment.
To support these functions, signal.h defines three macros:
SIG_DFLUsed with the signal function in place of a pointer to ahandler subroutine, to select the operating environment’s defaulthandling of a signal.
SIG_IGNUsed with the signal function in place of a pointer to ahandler, to ignore a particular signal.
SIG_ERRReturned by the signal function in place of a pointer to ahandler, to indicate that your request to set up a handler could notbe honored for some reason.
signal.h also defines an integral type, sig_atomic_t.This type is not used in any function declarations; it exists only toallow your signal handlers to declare a static storage location wherethey may store a signal value. (Static storage is not otherwisereliable from signal handlers.)
psignal—print a signal message on standard errorraise—send a signalsig2str, str2sig—Translate between signal number and namesignal—specify handler subroutine for a signalNext: raise—send a signal, Up: Signal Handling (signal.h)   [Contents][Index]
psignal—print a signal message on standard errorSynopsis
#include <stdio.h>void psignal(int signal, const char *prefix);
Description
Use psignal to print (on standard error) a signal messagecorresponding to the value of the signal number signal.Unless you use NULL as the value of the argument prefix, thesignal message will begin with the string at prefix, followed by acolon and a space (: ). The remainder of the signal message is oneof the strings described for strsignal.
Returnspsignal returns no result.
Portability
POSIX.1-2008 requires psignal, but the strings issued vary from oneimplementation to another.
Supporting OS subroutines required: close, fstat, isatty,lseek, read, sbrk, write.
Next: sig2str, str2sig—Translate between signal number and name, Previous: psignal—print a signal message on standard error, Up: Signal Handling (signal.h)   [Contents][Index]
raise—send a signalSynopsis
#include <signal.h>int raise(int sig);int _raise_r(void *reent, int sig);
Description
Send the signal sig (one of the macros from ‘sys/signal.h’).This interrupts your program’s normal flow of execution, and allows a signalhandler (if you’ve defined one, using signal) to take control.
The alternate function _raise_r is a reentrant version. The extraargument reent is a pointer to a reentrancy structure.
Returns
The result is 0 if sig was successfully raised, 1otherwise. However, the return value (since it depends on the normalflow of execution) may not be visible, unless the signal handler forsig terminates with a return or unless SIG_IGN is ineffect for this signal.
Portability
ANSI C requires raise, but allows the full set of signal numbersto vary from one implementation to another.
Required OS subroutines: getpid, kill.
Next: signal—specify handler subroutine for a signal, Previous: raise—send a signal, Up: Signal Handling (signal.h)   [Contents][Index]
sig2str, str2sig—Translate between signal number and nameSynopsis
#include <signal.h>int sig2str(int signum, char *str);int str2sig(const char *restrict str, int *restrict pnum);
Description
The sig2str function translates the signal number specified by signum toa signal name and stores this string in the location specified by str. Theapplication must ensure that str points to a location that can store thestring including the terminating null byte. The symbolic constantSIG2STR_MAX defined in ‘signal.h’ gives the maximum number of bytesrequired.
The str2sig function translates the signal name in the string pointed to bystr to a signal number and stores this value in the location specified bypnum.
Returnssig2str returns 0 if signum> is a valid, supported signal number.Otherwise, it returns -1.
str2sig returns 0 if it stores a value in the location pointed to bypnum. Otherwise it returns -1.
Previous: sig2str, str2sig—Translate between signal number and name, Up: Signal Handling (signal.h)   [Contents][Index]
signal—specify handler subroutine for a signalSynopsis
#include <signal.h>void (*signal(int sig, void(*func)(int))) (int);void (*_signal_r(void *reent, int sig, void(*func)(int))) (int);
Descriptionsignal provides a simple signal-handling implementation for embeddedtargets.
signal allows you to request changed treatment for a particularsignal sig. You can use one of the predefined macros SIG_DFL(select system default handling) or SIG_IGN (ignore this signal)as the value of func; otherwise, func is a function pointerthat identifies a subroutine in your program as the handler for this signal.
Some of the execution environment for signal handlers isunpredictable; notably, the only library function required to workcorrectly from within a signal handler is signal itself, andonly when used to redefine the handler for the current signal value.
Static storage is likewise unreliable for signal handlers, with oneexception: if you declare a static storage location as ‘volatilesig_atomic_t’, then you may use that location in a signal handler tostore signal values.
If your signal handler terminates using return (or implicitreturn), your program’s execution continues at the pointwhere it was when the signal was raised (whether by your programitself, or by an external event). Signal handlers can alsouse functions such as exit and abort to avoid returning.
The alternate function _signal_r is the reentrant version.The extra argument reent is a pointer to a reentrancy structure.
Returns
If your request for a signal handler cannot be honored, the result isSIG_ERR; a specific error number is also recorded in errno.
Otherwise, the result is the previous handler (a function pointer orone of the predefined macros).
Portability
ANSI C requires signal.
No supporting OS subroutines are required to link with signal, butit will not have any useful effects, except for software generated signals,without an operating system that can actually raise exceptions.
Next: Locale (locale.h), Previous: Signal Handling (signal.h), Up: The Red Hat newlib C Library [Contents][Index]
This chapter groups functions used either for reporting on time(elapsed, current, or compute time) or to perform calculations basedon time.
The header file time.h defines three types. clock_t andtime_t are both used for representations of time particularlysuitable for arithmetic. (In this implementation, quantities of typeclock_t have the highest resolution possible on your machine,and quantities of type time_t resolve to seconds.) size_tis also defined if necessary for quantities representing sizes. 
time.h also defines the structure tm for the traditionalrepresentation of Gregorian calendar time as a series of numbers, withthe following fields: 
tm_secSeconds, between 0 and 60 inclusive (60 allows for leap seconds).
tm_minMinutes, between 0 and 59 inclusive.
tm_hourHours, between 0 and 23 inclusive.
tm_mdayDay of the month, between 1 and 31 inclusive.
tm_monMonth, between 0 (January) and 11 (December).
tm_yearYear (since 1900), can be negative for earlier years.
tm_wdayDay of week, between 0 (Sunday) and 6 (Saturday).
tm_ydayNumber of days elapsed since last January 1, between 0 and 365 inclusive.
tm_isdstDaylight Savings Time flag: positive means DST in effect, zero means DSTnot in effect, negative means no information about DST is available.Although for mktime(), negative means that it should decide if DST is ineffect or not.
asctime—format time as stringclock—cumulative processor timectime—convert time to local and format as stringdifftime—subtract two timesgmtime—convert time to UTC traditional formlocaltime—convert time to local representationmktime—convert time to arithmetic representationstrftime, strftime_l—convert date and time to a formatted stringtime—get current calendar time (as single number)__tz_lock, __tz_unlock—lock time zone global variablestzset—set timezone characteristics from TZ environment variableNext: clock—cumulative processor time, Up: Time Functions (time.h)   [Contents][Index]
asctime—format time as stringSynopsis
#include <time.h>char *asctime(const struct tm *clock);char *_asctime_r(const struct tm *clock, char *buf);
Description
Format the time value at clock into a string of the form
Wed Jun 15 11:38:07 1988\n\0
The string is generated in a static buffer; each call to asctimeoverwrites the string generated by previous calls.
Returns
A pointer to the string containing a formatted timestamp.
Portability
ANSI C requires asctime.
asctime requires no supporting OS subroutines.
Next: ctime—convert time to local and format as string, Previous: asctime—format time as string, Up: Time Functions (time.h)   [Contents][Index]
clock—cumulative processor timeSynopsis
#include <time.h>clock_t clock(void);
Description
Calculates the best available approximation of the cumulative amountof time used by your program since it started. To convert the resultinto seconds, divide by the macro CLOCKS_PER_SEC.
Returns
The amount of processor time used so far by your program, in unitsdefined by the machine-dependent macro CLOCKS_PER_SEC. If nomeasurement is available, the result is (clock_t)-1.
Portability
ANSI C requires clock and CLOCKS_PER_SEC.
Supporting OS subroutine required: times.
Next: difftime—subtract two times, Previous: clock—cumulative processor time, Up: Time Functions (time.h)   [Contents][Index]
ctime—convert time to local and format as stringSynopsis
#include <time.h>char *ctime(const time_t *clock);char *ctime_r(const time_t *clock, char *buf);
Description
Convert the time value at clock to local time (like localtime)and format it into a string of the form
Wed Jun 15 11:38:07 1988\n\0
(like asctime).
Returns
A pointer to the string containing a formatted timestamp.
Portability
ANSI C requires ctime.
ctime requires no supporting OS subroutines.
Next: gmtime—convert time to UTC traditional form, Previous: ctime—convert time to local and format as string, Up: Time Functions (time.h)   [Contents][Index]
difftime—subtract two timesSynopsis
#include <time.h>double difftime(time_t tim1, time_t tim2);
Description
Subtracts the two times in the arguments: ‘tim1 - tim2’.
Returns
The difference (in seconds) between tim2 and tim1, as a double.
Portability
ANSI C requires difftime, and defines its result to be in secondsin all implementations.
difftime requires no supporting OS subroutines.
Next: localtime—convert time to local representation, Previous: difftime—subtract two times, Up: Time Functions (time.h)   [Contents][Index]
gmtime—convert time to UTC traditional formSynopsis
#include <time.h>struct tm *gmtime(const time_t *clock);struct tm *gmtime_r(const time_t *clock, struct tm *res);
Descriptiongmtime takes the time at clock representing the numberof elapsed seconds since 00:00:00 on January 1, 1970, UniversalCoordinated Time (UTC, also known in some countries as GMT,Greenwich Mean time) and converts it to a struct tmrepresentation.
gmtime constructs the traditional time representation in staticstorage; each call to gmtime or localtime will overwrite theinformation generated by previous calls to either function.
Returns
A pointer to the traditional time representation (struct tm).
Portability
ANSI C requires gmtime.
gmtime requires no supporting OS subroutines.
Next: mktime—convert time to arithmetic representation, Previous: gmtime—convert time to UTC traditional form, Up: Time Functions (time.h)   [Contents][Index]
localtime—convert time to local representationSynopsis
#include <time.h>struct tm *localtime(time_t *clock);struct tm *localtime_r(time_t *clock, struct tm *res);
Descriptionlocaltime converts the time at clock into local time, thenconverts its representation from the arithmetic representation to thetraditional representation defined by struct tm.
localtime constructs the traditional time representation in staticstorage; each call to gmtime or localtime will overwrite theinformation generated by previous calls to either function.
mktime is the inverse of localtime.
Returns
A pointer to the traditional time representation (struct tm).
Portability
ANSI C requires localtime.
localtime requires no supporting OS subroutines.
Next: strftime, strftime_l—convert date and time to a formatted string, Previous: localtime—convert time to local representation, Up: Time Functions (time.h)   [Contents][Index]
mktime—convert time to arithmetic representationSynopsis
#include <time.h>time_t mktime(struct tm *timp);
Descriptionmktime assumes the time at timp is a local time, and convertsits representation from the traditional representation defined bystruct tm into a representation suitable for arithmetic.
localtime is the inverse of mktime.
Returns
If the contents of the structure at timp do not form a validcalendar time representation, the result is -1. Otherwise, theresult is the time, converted to a time_t value.
Portability
ANSI C requires mktime.
mktime requires no supporting OS subroutines.
Next: time—get current calendar time (as single number), Previous: mktime—convert time to arithmetic representation, Up: Time Functions (time.h)   [Contents][Index]
strftime, strftime_l—convert date and time to a formatted stringSynopsis
#include <time.h>size_t strftime(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timp);size_t strftime_l(char *restrict s, size_t maxsize, const char *restrict format, const struct tm *restrict timp, locale_t locale);
Descriptionstrftime converts a struct tm representation of the time (attimp) into a null-terminated string, starting at s and occupyingno more than maxsize characters.
strftime_l is like strftime but creates a string in a formatas expected in locale locale. If locale is LC_GLOBAL_LOCALE ornot a valid locale object, the behaviour is undefined.
You control the format of the output using the string at format.*format can contain two kinds of specifications: text to becopied literally into the formatted string, and time conversionspecifications. Time conversion specifications are two- andthree-character sequences beginning with ‘%’ (use ‘%%’ toinclude a percent sign in the output). Each defined conversionspecification selects only the specified field(s) of calendar timedata from *timp, and converts it to a string in one of thefollowing ways:
%aThe abbreviated weekday name according to the current locale. [tm_wday]
%AThe full weekday name according to the current locale.In the default "C" locale, one of ‘Sunday’, ‘Monday’, ‘Tuesday’,‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’. [tm_wday]
%bThe abbreviated month name according to the current locale. [tm_mon]
%BThe full month name according to the current locale.In the default "C" locale, one of ‘January’, ‘February’,‘March’, ‘April’, ‘May’, ‘June’, ‘July’,‘August’, ‘September’, ‘October’, ‘November’,‘December’. [tm_mon]
%cThe preferred date and time representation for the current locale.[tm_sec, tm_min, tm_hour, tm_mday, tm_mon, tm_year, tm_wday]
%CThe century, that is, the year divided by 100 then truncated. For4-digit years, the result is zero-padded and exactly two characters;but for other years, there may a negative sign or more digits. Inthis way, ‘%C%y’ is equivalent to ‘%Y’. [tm_year]
%dThe day of the month, formatted with two digits (from ‘01’ to‘31’). [tm_mday]
%DA string representing the date, in the form ‘"%m/%d/%y"’.[tm_mday, tm_mon, tm_year]
%eThe day of the month, formatted with leading space if single digit(from ‘1’ to ‘31’). [tm_mday]
%ExIn some locales, the E modifier selects alternative representations ofcertain modifiers x. In newlib, it is ignored, and treated as %x.
%FA string representing the ISO 8601:2000 date format, in the form‘"%Y-%m-%d"’. [tm_mday, tm_mon, tm_year]
%gThe last two digits of the week-based year, see specifier %G (from‘00’ to ‘99’). [tm_year, tm_wday, tm_yday]
%GThe week-based year. In the ISO 8601:2000 calendar, week 1 of the yearincludes January 4th, and begin on Mondays. Therefore, if January 1st,2nd, or 3rd falls on a Sunday, that day and earlier belong to the lastweek of the previous year; and if December 29th, 30th, or 31st fallson Monday, that day and later belong to week 1 of the next year. Forconsistency with %Y, it always has at least four characters.Example: "%G" for Saturday 2nd January 1999 gives "1998", and forTuesday 30th December 1997 gives "1998". [tm_year, tm_wday, tm_yday]
%hSynonym for "%b". [tm_mon]
%HThe hour (on a 24-hour clock), formatted with two digits (from‘00’ to ‘23’). [tm_hour]
%IThe hour (on a 12-hour clock), formatted with two digits (from‘01’ to ‘12’). [tm_hour]
%jThe count of days in the year, formatted with three digits(from ‘001’ to ‘366’). [tm_yday]
%kThe hour (on a 24-hour clock), formatted with leading space if singledigit (from ‘0’ to ‘23’). Non-POSIX extension (c.p. %I). [tm_hour]
%lThe hour (on a 12-hour clock), formatted with leading space if singledigit (from ‘1’ to ‘12’). Non-POSIX extension (c.p. %H). [tm_hour]
%mThe month number, formatted with two digits (from ‘01’ to ‘12’).[tm_mon]
%MThe minute, formatted with two digits (from ‘00’ to ‘59’). [tm_min]
%nA newline character (‘\n’).
%OxIn some locales, the O modifier selects alternative digit charactersfor certain modifiers x. In newlib, it is ignored, and treated as %x.
%pEither ‘AM’ or ‘PM’ as appropriate, or the corresponding strings forthe current locale. [tm_hour]
%PSame as ’%p’, but in lowercase. This is a GNU extension. [tm_hour]
%rReplaced by the time in a.m. and p.m. notation. In the "C" locale thisis equivalent to "%I:%M:%S %p". In locales which don’t define a.m./p.m.notations, the result is an empty string. [tm_sec, tm_min, tm_hour]
%RThe 24-hour time, to the minute. Equivalent to "%H:%M". [tm_min, tm_hour]
%sThe time elapsed, in seconds, since the start of the Unix epoch at1970-01-01 00:00:00 UTC.
%SThe second, formatted with two digits (from ‘00’ to ‘60’). Thevalue 60 accounts for the occasional leap second. [tm_sec]
%tA tab character (‘\t’).
%TThe 24-hour time, to the second. Equivalent to "%H:%M:%S". [tm_sec,tm_min, tm_hour]
%uThe weekday as a number, 1-based from Monday (from ‘1’ to‘7’). [tm_wday]
%UThe week number, where weeks start on Sunday, week 1 contains the firstSunday in a year, and earlier days are in week 0. Formatted with twodigits (from ‘00’ to ‘53’). See also %W. [tm_wday, tm_yday]
%VThe week number, where weeks start on Monday, week 1 contains January 4th,and earlier days are in the previous year. Formatted with two digits(from ‘01’ to ‘53’). See also %G. [tm_year, tm_wday, tm_yday]
%wThe weekday as a number, 0-based from Sunday (from ‘0’ to ‘6’).[tm_wday]
%WThe week number, where weeks start on Monday, week 1 contains the firstMonday in a year, and earlier days are in week 0. Formatted with twodigits (from ‘00’ to ‘53’). [tm_wday, tm_yday]
%xReplaced by the preferred date representation in the current locale.In the "C" locale this is equivalent to "%m/%d/%y".[tm_mon, tm_mday, tm_year]
%XReplaced by the preferred time representation in the current locale.In the "C" locale this is equivalent to "%H:%M:%S". [tm_sec, tm_min, tm_hour]
%yThe last two digits of the year (from ‘00’ to ‘99’). [tm_year](Implementation interpretation: always positive, even for negative years.)
%YThe full year, equivalent to %C%y. It will always have at least fourcharacters, but may have more. The year is accurate even when tm_yearadded to the offset of 1900 overflows an int. [tm_year]
%zThe offset from UTC. The format consists of a sign (negative is west ofGreewich), two characters for hour, then two characters for minutes(-hhmm or +hhmm). If tm_isdst is negative, the offset is unknown and nooutput is generated; if it is zero, the offset is the standard offset forthe current time zone; and if it is positive, the offset is the daylightsavings offset for the current timezone. The offset is determined fromthe TZ environment variable, as if by calling tzset(). [tm_isdst]
%ZThe time zone name. If tm_isdst is negative, no output is generated.Otherwise, the time zone name is based on the TZ environment variable,as if by calling tzset(). [tm_isdst]
%%A single character, ‘%’.
Returns
When the formatted time takes up no more than maxsize characters,the result is the length of the formatted string. Otherwise, if theformatting operation was abandoned due to lack of room, the result is0, and the string starting at s corresponds to just thoseparts of *format that could be completely filled in within themaxsize limit.
Portability
ANSI C requires strftime, but does not specify the contents of*s when the formatted string would require more thanmaxsize characters. Unrecognized specifiers and fields oftimp that are out of range cause undefined results. Since someformats expand to 0 bytes, it is wise to set *s to a nonzerovalue beforehand to distinguish between failure and an empty string.This implementation does not support s being NULL, nor overlappings and format.
strftime_l is POSIX-1.2008.
strftime and strftime_l require no supporting OS subroutines.
Bugs
(NOT Cygwin:) strftime ignores the LC_TIME category of the currentlocale, hard-coding the "C" locale settings.
Next: __tz_lock, __tz_unlock—lock time zone global variables, Previous: strftime, strftime_l—convert date and time to a formatted string, Up: Time Functions (time.h)   [Contents][Index]
time—get current calendar time (as single number)Synopsis
#include <time.h>time_t time(time_t *t);
Descriptiontime looks up the best available representation of the currenttime and returns it, encoded as a time_t. It stores the samevalue at t unless the argument is NULL.
Returns
A -1 result means the current time is not available; otherwise theresult represents the current time.
Portability
ANSI C requires time.
Supporting OS subroutine required: Some implementations requiregettimeofday.
Next: tzset—set timezone characteristics from TZ environment variable, Previous: time—get current calendar time (as single number), Up: Time Functions (time.h)   [Contents][Index]
__tz_lock, __tz_unlock—lock time zone global variablesSynopsis
#include "local.h"void __tz_lock (void);void __tz_unlock (void);
Description
The tzset facility functions call these functions when they need toensure the values of global variables. The version of these routinessupplied in the library use the lock API defined in sys/lock.h. If multiplethreads of execution can call the time functions and give up scheduling inthe middle, then you you need to define your own versions of these functionsin order to safely lock the time zone variables during a call. If you donot, the results of localtime, mktime, ctime, and strftimeare undefined.
The lock __tz_lock may not be called recursively; that is,a call __tz_lock will always lock all subsequent __tz_lock callsuntil the corresponding __tz_unlock call on the same thread is made.
Previous: __tz_lock, __tz_unlock—lock time zone global variables, Up: Time Functions (time.h)   [Contents][Index]
tzset—set timezone characteristics from TZ environment variableSynopsis
#include <time.h>void tzset(void);void _tzset_r (struct _reent *reent_ptr);
Descriptiontzset examines the TZ environment variable and sets up the threeexternal variables: _timezone, _daylight, and tzname. Thevalue of _timezone shall be the offset from the current time zoneto GMT. The value of _daylight shall be 0 if there is no daylightsavings time for the current time zone, otherwise it will be non-zero.The tzname array has two entries: the first is the name of thestandard time zone, the second is the name of the daylight-savings timezone.
The TZ environment variable is expected to be in the following POSIXformat:
stdoffset1[dst[offset2][,start[/time1],end[/time2]]]
where: std is the name of the standard time-zone (minimum 3 chars)offset1 is the value to add to local time to arrive at Universal timeit has the form: hh[:mm[:ss]]dst is the name of the alternate (daylight-savings) time-zone (min 3 chars)offset2 is the value to add to local time to arrive at Universal timeit has the same format as the std offsetstart is the day that the alternate time-zone startstime1 is the optional time that the alternate time-zone starts(this is in local time and defaults to 02:00:00 if not specified)end is the day that the alternate time-zone endstime2 is the time that the alternate time-zone ends(it is in local time and defaults to 02:00:00 if not specified)
Note that there is no white-space padding between fields. Also note thatif TZ is null, the default is Universal GMT which has no daylight-savingstime. If TZ is empty, the default EST5EDT is used.
The function _tzset_r is identical to tzset only it is reentrantand is used for applications that use multiple threads.
Returns
There is no return value.
Portabilitytzset is part of the POSIX standard.
Supporting OS subroutine required: None
Next: Reentrancy, Previous: Time Functions (time.h), Up: The Red Hat newlib C Library [Contents][Index]
A locale is the name for a collection of parameters (affectingcollating sequences and formatting conventions) that may be differentdepending on location or culture. The "C" locale is the onlyone defined in the ANSI C standard.
This is a minimal implementation, supporting only the required "C"value for locale; strings representing other locales are nothonored. ("" is also accepted; it represents the default localefor an implementation, here equivalent to "C").
locale.h defines the structure lconv to collect theinformation on a locale, with the following fields:
char *decimal_pointThe decimal point character used to format “ordinary” numbers (allnumbers except those referring to amounts of money). "." in theC locale. 
char *thousands_sepThe character (if any) used to separate groups of digits, whenformatting ordinary numbers."" in the C locale.
char *groupingSpecifications for how many digits to group (if any grouping is done atall) when formatting ordinary numbers. The numeric value of eachcharacter in the string represents the number of digits for the nextgroup, and a value of 0 (that is, the string’s trailingNULL) means to continue grouping digits using the last valuespecified. Use CHAR_MAX to indicate that no further grouping isdesired. "" in the C locale. 
char *int_curr_symbolThe international currency symbol (first three characters), if any, andthe character used to separate it from numbers."" in the C locale.
char *currency_symbolThe local currency symbol, if any."" in the C locale.
char *mon_decimal_pointThe symbol used to delimit fractions in amounts of money."" in the C locale.
char *mon_thousands_sepSimilar to thousands_sep, but used for amounts of money."" in the C locale.
char *mon_groupingSimilar to grouping, but used for amounts of money."" in the C locale.
char *positive_signA string to flag positive amounts of money when formatting."" in the C locale.
char *negative_signA string to flag negative amounts of money when formatting."" in the C locale.
char int_frac_digitsThe number of digits to display when formatting amounts of money tointernational conventions.CHAR_MAX (the largest number representable as a char) inthe C locale. 
char frac_digitsThe number of digits to display when formatting amounts of money tolocal conventions.CHAR_MAX in the C locale. 
char p_cs_precedes1 indicates the local currency symbol is used before apositive or zero formatted amount of money; 0 indicatesthe currency symbol is placed after the formatted number.CHAR_MAX in the C locale. 
char p_sep_by_space1 indicates the local currency symbol must be separated frompositive or zero numbers by a space; 0 indicates that itis immediately adjacent to numbers.CHAR_MAX in the C locale. 
char n_cs_precedes1 indicates the local currency symbol is used before anegative formatted amount of money; 0 indicatesthe currency symbol is placed after the formatted number.CHAR_MAX in the C locale. 
char n_sep_by_space1 indicates the local currency symbol must be separated fromnegative numbers by a space; 0 indicates that itis immediately adjacent to numbers.CHAR_MAX in the C locale. 
char p_sign_posnControls the position of the positive sign fornumbers representing money. 0 means parentheses surround thenumber; 1 means the sign is placed before both the number and thecurrency symbol; 2 means the sign is placed after both the numberand the currency symbol; 3 means the sign is placed just beforethe currency symbol; and 4 means the sign is placed just afterthe currency symbol.CHAR_MAX in the C locale. 
char n_sign_posnControls the position of the negative sign for numbersrepresenting money, using the same rules as p_sign_posn.CHAR_MAX in the C locale. 
Up: Locale (locale.h) [Contents][Index]
setlocale, localeconv—select or query localeSynopsis
#include <locale.h>char *setlocale(int category, const char *locale);lconv *localeconv(void);char *_setlocale_r(void *reent, int category, const char *locale);lconv *_localeconv_r(void *reent);
Descriptionsetlocale is the facility defined by ANSI C to condition theexecution environment for international collating and formattinginformation; localeconv reports on the settings of the currentlocale.
This is a minimal implementation, supporting only the required "POSIX"and "C" values for locale; strings representing other locales are nothonored unless _MB_CAPABLE is defined.
If _MB_CAPABLE is defined, POSIX locale strings are allowed, followingthe form
language[_TERRITORY][.charset][@modifier]
"language" is a two character string per ISO 639, or, if not availablefor a given language, a three character string per ISO 639-3."TERRITORY" is a country code per ISO 3166. For "charset" and"modifier" see below.
Additionally to the POSIX specifier, the following extension is supportedfor backward compatibility with older implementations using newlib:"C-charset".Instead of "C-", you can also specify "C.". Both variations allowto specify language neutral locales while using other charsets than ASCII,for instance "C.UTF-8", which keeps all settings as in the C locale,but uses the UTF-8 charset.
The following charsets are recognized:"UTF-8", "JIS", "EUCJP", "SJIS", "KOI8-R", "KOI8-U","GEORGIAN-PS", "PT154", "TIS-620", "ISO-8859-x" with1 <= x <= 16, or "CPxxx" with xxx in [437, 720, 737, 775, 850, 852, 855,857, 858, 862, 866, 874, 932, 1125, 1250, 1251, 1252, 1253, 1254, 1255, 1256,1257, 1258].
Charsets are case insensitive. For instance, "EUCJP" and "eucJP"are equivalent. Charset names with dashes can also be written withoutdashes, as in "UTF8", "iso88591" or "koi8r". "EUCJP" and"EUCKR" are also recognized with dash, "EUC-JP" and "EUC-KR".
Full support for all of the above charsets requires that newlib has beenbuild with multibyte support and support for all ISO and Windows Codepage.Otherwise all singlebyte charsets are simply mapped to ASCII. Right now,only newlib for Cygwin is built with full charset support by default.Under Cygwin, this implementation additionally supports the charsets"GBK", "GB2312", "eucCN", "eucKR", and "Big5". Cygwindoes not support "JIS".
Cygwin additionally supports locales from the file/usr/share/locale/locale.alias.
("" is also accepted; if given, the settings are read from thecorresponding LC_* environment variables and $LANG according to POSIX rules.)
This implementation also supports the modifiers "cjknarrow" and"cjkwide", which affect how the functions wcwidth and wcswidthhandle characters from the "CJK Ambiguous Width" category of charactersdescribed at http://www.unicode.org/reports/tr11/#Ambiguous.These characters have a width of 1 for singlebyte charsets and UTF-8,and a width of 2 for multibyte charsets other than UTF-8. Specifying"cjknarrow" or "cjkwide" forces a width of 1 or 2, respectively.
This implementation also supports the modifier "cjksingle"to enforce single-width character properties.
If you use NULL as the locale argument, setlocale returns apointer to the string representing the current locale. The acceptablevalues for category are defined in ‘locale.h’ as macrosbeginning with "LC_".
localeconv returns a pointer to a structure (also defined in‘locale.h’) describing the locale-specific conventions currentlyin effect. 
_localeconv_r and _setlocale_r are reentrant versions oflocaleconv and setlocale respectively. The extra argumentreent is a pointer to a reentrancy structure.
Returns
A successful call to setlocale returns a pointer to a stringassociated with the specified category for the new locale. The stringreturned by setlocale is such that a subsequent call using thatstring will restore that category (or all categories in case of LC_ALL),to that state. The application shall not modify the string returnedwhich may be overwritten by a subsequent call to setlocale.On error, setlocale returns NULL.
localeconv returns a pointer to a structure of type lconv,which describes the formatting and collating conventions in effect (inthis implementation, always those of the C locale).
Portability
ANSI C requires setlocale, but the only locale required across allimplementations is the C locale.
Notes
There is no ISO-8859-12 codepage. It’s also refused by this implementation.
No supporting OS subroutines are required.
Next: Miscellaneous Macros and Functions, Previous: Locale (locale.h), Up: The Red Hat newlib C Library [Contents][Index]
Reentrancy is a characteristic of library functions which allows multipleprocesses to use the same address space with assurance that the values storedin those spaces will remain constant between calls. The Red Hatnewlib implementation of the library functions ensures thatwhenever possible, these library functions are reentrant. However,there are some functions that can not be trivially made reentrant.Hooks have been provided to allow you to use these functions in a fullyreentrant fashion.
These hooks use the structure _reent defined in reent.h.A variable defined as ‘struct _reent’ is called a reentrancystructure. All functions which must manipulate global information areavailable in two versions. The first version has the usual name, anduses a single global instance of the reentrancy structure. The secondhas a different name, normally formed by prepending ‘_’ andappending ‘_r’, and takes a pointer to the particular reentrancystructure to use.
For example, the function fopen takes two arguments, fileand mode, and uses the global reentrancy structure. The function_fopen_r takes the arguments, struct_reent, which is apointer to an instance of the reentrancy structure, fileand mode.
There are two versions of ‘struct _reent’, a normal one and onefor small memory systems, controlled by the _REENT_SMALLdefinition from the (automatically included) <sys/config.h>.
Each function which uses the global reentrancy structure uses the globalvariable _impure_ptr, which points to a reentrancy structure.
This means that you have two ways to achieve reentrancy. Both requirethat each thread of execution control initialize a unique globalvariable of type ‘struct _reent’:
_impure_ptr,and call the standard library subroutines.The following functions are provided in both reentrantand non-reentrant versions.
Equivalent for errno variable:
_errno_r
Locale functions:
_localeconv_r _setlocale_r
Equivalents for stdio variables:
_stdin_r _stdout_r _stderr_r
Stdio functions:
_fdopen_r _perror_r _tempnam_r_fopen_r _putchar_r _tmpnam_r_getchar_r _puts_r _tmpfile_r_gets_r _remove_r _vfprintf_r_iprintf_r _rename_r _vsnprintf_r_mkstemp_r _snprintf_r _vsprintf_r_mktemp_t _sprintf_r
Signal functions:
_init_signal_r _signal_r_kill_r __sigtramp_r_raise_r
Stdlib functions:
_calloc_r _mblen_r _setenv_r_dtoa_r _mbstowcs_r _srand_r_free_r _mbtowc_r _strtod_r_getenv_r _memalign_r _strtol_r_mallinfo_r _mstats_r _strtoul_r_malloc_r _putenv_r _system_r_malloc_r _rand_r _wcstombs_r_malloc_stats_r _realloc_r _wctomb_r
String functions:
_strdup_r _strtok_r
System functions:
_close_r _link_r _unlink_r_execve_r _lseek_r _wait_r_fcntl_r _open_r _write_r_fork_r _read_r_fstat_r _sbrk_r_gettimeofday_r _stat_r_getpid_r _times_r
Time function:
_asctime_r
Next: Posix Functions, Previous: Reentrancy, Up: The Red Hat newlib C Library [Contents][Index]
This chapter describes miscellaneous routines not covered elsewhere.
ffs—find first bit set in a word__retarget_lock_init, __retarget_lock_init_recursive, __retarget_lock_close, __retarget_lock_close_recursive, __retarget_lock_acquire, __retarget_lock_acquire_recursive, __retarget_lock_try_acquire, __retarget_lock_try_acquire_recursive, __retarget_lock_release, __retarget_lock_release_recursive—locking routinesunctrl—get printable representation of a characterNext: __retarget_lock_init, __retarget_lock_init_recursive, __retarget_lock_close, __retarget_lock_close_recursive, __retarget_lock_acquire, __retarget_lock_acquire_recursive, __retarget_lock_try_acquire, __retarget_lock_try_acquire_recursive, __retarget_lock_release, __retarget_lock_release_recursive—locking routines, Up: Miscellaneous Macros and Functions   [Contents][Index]
ffs—find first bit set in a wordSynopsis
#include <strings.h>int ffs(int word);
Description
ffs returns the first bit set in a word.
Returnsffs returns 0 if c is 0, 1 if c is odd, 2 if c is a multiple of2, etc.
Portabilityffs is not ANSI C.
No supporting OS subroutines are required.
Next: unctrl—get printable representation of a character, Previous: ffs—find first bit set in a word, Up: Miscellaneous Macros and Functions   [Contents][Index]
__retarget_lock_init, __retarget_lock_init_recursive, __retarget_lock_close, __retarget_lock_close_recursive, __retarget_lock_acquire, __retarget_lock_acquire_recursive, __retarget_lock_try_acquire, __retarget_lock_try_acquire_recursive, __retarget_lock_release, __retarget_lock_release_recursive—locking routinesSynopsis
#include <lock.h>struct __lock __lock___sinit_recursive_mutex;struct __lock __lock___sfp_recursive_mutex;struct __lock __lock___atexit_recursive_mutex;struct __lock __lock___at_quick_exit_mutex;struct __lock __lock___malloc_recursive_mutex;struct __lock __lock___env_recursive_mutex;struct __lock __lock___tz_mutex;struct __lock __lock___dd_hash_mutex;struct __lock __lock___arc4random_mutex;void __retarget_lock_init (_LOCK_T * lock_ptr);void __retarget_lock_init_recursive (_LOCK_T * lock_ptr);void __retarget_lock_close (_LOCK_T lock);void __retarget_lock_close_recursive (_LOCK_T lock);void __retarget_lock_acquire (_LOCK_T lock);void __retarget_lock_acquire_recursive (_LOCK_T lock);int __retarget_lock_try_acquire (_LOCK_T lock);int __retarget_lock_try_acquire_recursive (_LOCK_T lock);void __retarget_lock_release (_LOCK_T lock);void __retarget_lock_release_recursive (_LOCK_T lock);
Description
Newlib was configured to allow the target platform to provide the lockingroutines and static locks at link time. As such, a dummy defaultimplementation of these routines and static locks is provided forsingle-threaded application to link successfully out of the box on bare-metalsystems.
For multi-threaded applications the target platform is required to providean implementation for all these routines and static locks. If someroutines or static locks are missing, the link will fail with doubly definedsymbols.
Portability
These locking routines and static lock are newlib-specific. Supporting OSsubroutines are required for linking multi-threaded applications.
Previous: __retarget_lock_init, __retarget_lock_init_recursive, __retarget_lock_close, __retarget_lock_close_recursive, __retarget_lock_acquire, __retarget_lock_acquire_recursive, __retarget_lock_try_acquire, __retarget_lock_try_acquire_recursive, __retarget_lock_release, __retarget_lock_release_recursive—locking routines, Up: Miscellaneous Macros and Functions   [Contents][Index]
unctrl—get printable representation of a characterSynopsis
#include <unctrl.h>char *unctrl(int c);int unctrllen(int c);
Descriptionunctrl is a macro which returns the printable representation of cas a string.unctrllen is a macro which returns the length of the printablerepresentation of c.
Returnsunctrl returns a string of the printable representation of c.
unctrllen returns the length of the string which is the printablerepresentation of c.
Portabilityunctrl and unctrllen are not ANSI C.
No supporting OS subroutines are required.
Next: Encoding conversions (iconv.h), Previous: Miscellaneous Macros and Functions, Up: The Red Hat newlib C Library [Contents][Index]
This chapter groups several utility functions specified by POSIX, butnot by C. Each function documents which header to use.
popen, pclose—tie a stream to a command stringSynopsis
#include <stdio.h>FILE *popen(const char *s, const char *mode);int pclose(FILE *f);
Description
Use popen to create a stream to a child process executing acommand string *s as processed by /bin/sh on your system.The argument mode must start with either ‘r’, where the streamreads from the child’s stdout, or ‘w’, where the stream writesto the child’s stdin. As an extension, mode may also contain‘e’ to set the close-on-exec bit of the parent’s file descriptor.The stream created by popen must be closed by pclose to avoidresource leaks.
Streams created by prior calls to popen are not visible insubsequent popen children, regardless of the close-on-exec bit.
Use “system(NULL)” to test whether your system has /bin/shavailable.
Returnspopen returns a file stream opened with the specified mode,or NULL if a child process could not be created. pclosereturns -1 if the stream was not created by popen or if theapplication used wait or similar to steal the status; otherwiseit returns the exit status of the child which can be interpretedin the same manner as a status obtained by waitpid.
Portability
POSIX.2 requires popen and pclose, but only specifies a modeof just r or w. Where sh is found is left unspecified.
Supporting OS subroutines required: _exit, _execve, _fork_r,_wait_r, pipe, fcntl, sbrk.
Previous: popen, pclose—tie a stream to a command string, Up: Posix Functions   [Contents][Index]
posix_spawn, posix_spawnp—spawn a processSynopsis
#include <spawn.h>int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]);int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *file_actions, const posix_spawnattr_t *attrp, char *const argv[], char *const envp[]);
Description
Use posix_spawn and posix_spawnp to create a new child processfrom the specified process image file. argc is the argument countand argv is an array of argument strings passed to the new program.envp is an array of stings, which are passed as environment to thenew program.
The path argument to posix_spawn identifies the new processimage file to execute. The file argument to posix_spawnp isused to construct a pathname that identifies the new process imagefile by duplicating the actions of the shell in searching for anexecutable file if the specified filename does not contain a ‘/’character. The file is sought in the colon-separated list ofdirectory pathnames specified in the PATH environment variable.
The file descriptors remain open across posix_spawn andposix_spawnp except for those marked as close-on-exec. The openfile descriptors in the child process can be modified by the spawn fileactions object pointed to by file_actions.
The spawn attributes object type pointed to by attrp argumentmay contain any of the attributes defined in spawn.h.
Returnsposix_spawn and posix_spawnp return the process ID of the newlyspawned child process in the variable pointed by a non-NULL *pidargument and zero as the function return value upon successfulcompletion. Otherwise, posix_spawn and posix_spawnp return anerror number as the function return value to indicate the error; thevalue stored into the variable pointed to by a non-NULL *pidargument is unspecified.
Portability
POSIX.1-2008 requires posix_spawn and posix_spawnp.
Supporting OS subroutines required: _close, dup2, _fcntl,_execve, execvpe, _exit, _open, sigaction,sigprocmask, waitpid, sched_setscheduler,sched_setparam, setegid, seteuid, setpgid, vfork.
Next: Overflow Protection, Previous: Posix Functions, Up: The Red Hat newlib C Library [Contents][Index]
This chapter describes the Newlib iconv library.The iconv functions declarations are iniconv.h.
iconv, iconv_open, iconv_close—charset conversion routinesNext: Introduction to iconv, Up: Encoding conversions (iconv.h) [Contents][Index]
iconv, iconv_open, iconv_close—charset conversion routinesSynopsis
#include <iconv.h>iconv_t iconv_open (const char *to, const char *from);int iconv_close (iconv_t cd);size_t iconv (iconv_t cd, char **restrict inbuf, size_t *restrict inbytesleft, char **restrict outbuf, size_t *restrict outbytesleft);iconv_t _iconv_open_r (struct _reent *rptr, const char *to, const char *from);int _iconv_close_r (struct _reent *rptr, iconv_t cd);size_t _iconv_r (struct _reent *rptr, iconv_t cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);
Description
The function iconv converts characters from in which are in oneencoding to characters of another encoding, outputting them to out.The value inleft specifies the number of input bytes to convert whereasthe value outleft specifies the size remaining in the out buffer.The conversion descriptor cd specifies the conversion being performedand is created via iconv_open.
An iconv conversion stops if: the input bytes are exhausted, the outputbuffer is full, an invalid input character sequence occurs, or theconversion specifier is invalid.
The function iconv_open is used to specify a conversion from oneencoding: from to another: to. The result of the call isto create a conversion specifier that can be used with iconv.
The function iconv_close is used to close a conversion specifier afterit is no longer needed.
The _iconv_r, _iconv_open_r, and _iconv_close_r functions arereentrant versions of iconv, iconv_open, and iconv_close,respectively. An additional reentrancy struct pointer: rptr is passedto properly set errno.
Returns
The iconv function returns the number of non-identical conversionsperformed. If an error occurs, (size_t)-1 is returned and errnois set appropriately. The values of inleft, in, out,and outleft are modified to indicate how much input was processedand how much output was created.
The iconv_open function returns either a valid conversion specifieror (iconv_t)-1 to indicate failure. If failure occurs, errno is setappropriately.
The iconv_close function returns 0 on success or -1 on failure.If failure occurs errno is set appropriately.
Portabilityiconv, iconv_open, and iconv_close are non-ANSI and are specifiedby the Single Unix specification.
No supporting OS subroutine calls are required.
Next: Supported encodings, Previous: iconv, iconv_open, iconv_close—charset conversion routines, Up: Encoding conversions (iconv.h)   [Contents][Index]
The iconv library is intended to convert characters from one encoding toanother. It implements iconv(), iconv_open() and iconv_close()calls, which are defined by the Single Unix Specification.
In addition to these user-level interfaces, the iconv library also hasseveral useful interfaces which are needed to support codingcapabilities of the Newlib Locale infrastructure. Since Localesupport also needs toconvert various character sets to and from the wide charactersset, the iconv library shares it’s capabilities with the Newlib Localesubsystem. Moreover, the iconv library supports several features which areonly needed for the Locale infrastructure (for example, the MB_CUR_MAX value).
The Newlib iconv library was created using concepts from another iconvlibrary implemented by Konstantin Chuguev (ver 2.0). The Newlib iconv librarywas rewritten from scratch and contains a lot of improvements with respect tothe original iconv library.
Terms like encoding or character set aren’t well defined andare often used with various meanings. The following are the definitions of termswhich are used in this documentation as well as in the iconv libraryimplementation:
Users usually deal with encodings, for example, KOI8-R, Unicode, UTF-8,ASCII, etc. Encodings are formed by the following chain of steps:
Thus, an encoding may be considered as one or more CCS + CES.
Sometimes, there is no CES and in such cases encoding is equivalentto CCS, e.g. KOI8-R or ASCII.
An example of a more complicated encoding is UTF-8 which is the UCS(or Unicode) CCS plus the UTF-8 CES.
The following is a brief list of iconv library features:
Next: iconv design decisions, Previous: Introduction to iconv, Up: Encoding conversions (iconv.h) [Contents][Index]
The following is the list of currently supported encodings. The first columncorresponds to the encoding name, the second column is the list of aliases,the third column is its CES and CCS components names, and the fourth columnis a short description.
| Name | Aliases | CES/CCS | Short description | 
| big5 | csbig5, big_five, bigfive, cn_big5, cp950 | table_pcs / big5, us_ascii | The encoding for the Traditional Chinese. | 
| cp775 | ibm775, cspc775baltic | table / cp775 | The updated version of CP 437 that supports the balitic languages. | 
| cp850 | ibm850, 850, cspc850multilingual | table / cp850 | IBM 850 - the updated version of CP 437 where several Latin 1 characters have beenadded instead of some less-often used characters like the line-drawingand the greek ones. | 
| cp852 | ibm852, 852, cspcp852 | IBM 852 - the updated version of CP 437 where several Latin 2 characters have been addedinstead of some less-often used characters like the line-drawing and the greek ones. | |
| cp855 | ibm855, 855, csibm855 | table / cp855 | IBM 855 - the updated version of CP 437 that supports Cyrillic. | 
| cp866 | 866, IBM866, CSIBM866 | table / cp866 | IBM 866 - the updated version of CP 855 which follows more the logical Russian alphabetordering of the alternative variant that is preferred by many Russian users. | 
| euc_jp | eucjp | euc / jis_x0208_1990, jis_x0201_1976, jis_x0212_1990 | EUC-JP - The EUC for Japanese. | 
| euc_kr | euckr | euc / ksx1001 | EUC-KR - The EUC for Korean. | 
| euc_tw | euctw | euc / cns11643_plane1, cns11643_plane2, cns11643_plane14 | EUC-TW - The EUC for Traditional Chinese. | 
| iso_8859_1 | iso8859_1, iso88591, iso_8859_1:1987, iso_ir_100, latin1, l1, ibm819, cp819, csisolatin1 | table / iso_8859_1 | ISO 8859-1:1987 - Latin 1, West European. | 
| iso_8859_10 | iso_8859_10:1992, iso_ir_157, iso885910, latin6, l6, csisolatin6, iso8859_10 | table / iso_8859_10 | ISO 8859-10:1992 - Latin 6, Nordic. | 
| iso_8859_11 | iso8859_11, iso885911 | table / iso_8859_11 | ISO 8859-11 - Thai. | 
| iso_8859_13 | iso_8859_13:1998, iso8859_13, iso885913 | table / iso_8859_13 | ISO 8859-13:1998 - Latin 7, Baltic Rim. | 
| iso_8859_14 | iso_8859_14:1998, iso885914, iso8859_14 | table / iso_8859_14 | ISO 8859-14:1998 - Latin 8, Celtic. | 
| iso_8859_15 | iso885915, iso_8859_15:1998, iso8859_15, | table / iso_8859_15 | ISO 8859-15:1998 - Latin 9, West Europe, successor of Latin 1. | 
| iso_8859_2 | iso8859_2, iso88592, iso_8859_2:1987, iso_ir_101, latin2, l2, csisolatin2 | table / iso_8859_2 | ISO 8859-2:1987 - Latin 2, East European. | 
| iso_8859_3 | iso_8859_3:1988, iso_ir_109, iso8859_3, latin3, l3, csisolatin3, iso88593 | table / iso_8859_3 | ISO 8859-3:1988 - Latin 3, South European. | 
| iso_8859_4 | iso8859_4, iso88594, iso_8859_4:1988, iso_ir_110, latin4, l4, csisolatin4 | table / iso_8859_4 | ISO 8859-4:1988 - Latin 4, North European. | 
| iso_8859_5 | iso8859_5, iso88595, iso_8859_5:1988, iso_ir_144, cyrillic, csisolatincyrillic | table / iso_8859_5 | ISO 8859-5:1988 - Cyrillic. | 
| iso_8859_6 | iso_8859_6:1987, iso_ir_127, iso8859_6, ecma_114, asmo_708, arabic, csisolatinarabic, iso88596 | table / iso_8859_6 | ISO i8859-6:1987 - Arabic. | 
| iso_8859_7 | iso_8859_7:1987, iso_ir_126, iso8859_7, elot_928, ecma_118, greek, greek8, csisolatingreek, iso88597 | table / iso_8859_7 | ISO 8859-7:1987 - Greek. | 
| iso_8859_8 | iso_8859_8:1988, iso_ir_138, iso8859_8, hebrew, csisolatinhebrew, iso88598 | table / iso_8859_8 | ISO 8859-8:1988 - Hebrew. | 
| iso_8859_9 | iso_8859_9:1989, iso_ir_148, iso8859_9, latin5, l5, csisolatin5, iso88599 | table / iso_8859_9 | ISO 8859-9:1989 - Latin 5, Turkish. | 
| iso_ir_111 | ecma_cyrillic, koi8_e, koi8e, csiso111ecmacyrillic | table / iso_ir_111 | ISO IR 111/ECMA Cyrillic. | 
| koi8_r | cskoi8r, koi8r, koi8 | table / koi8_r | RFC 1489 Cyrillic. | 
| koi8_ru | koi8ru | table / koi8_ru | The obsolete Ukrainian. | 
| koi8_u | koi8u | table / koi8_u | RFC 2319 Ukrainian. | 
| koi8_uni | koi8uni | table / koi8_uni | KOI8 Unified. | 
| ucs_2 | ucs2, iso_10646_ucs_2, iso10646_ucs_2, iso_10646_ucs2, iso10646_ucs2, iso10646ucs2, csUnicode | ucs_2 / (UCS) | ISO-10646-UCS-2. Big Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_2_internal | ucs2_internal, ucs_2internal, ucs2internal | ucs_2_internal / (UCS) | ISO-10646-UCS-2 in system byte order.NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_2be | ucs2be | ucs_2 / (UCS) | Big Endian version of ISO-10646-UCS-2 (in fact, equivalent to ucs_2).Big Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_2le | ucs2le | ucs_2 / (UCS) | Little Endian version of ISO-10646-UCS-2.Little Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_4 | ucs4, iso_10646_ucs_4, iso10646_ucs_4, iso_10646_ucs4, iso10646_ucs4, iso10646ucs4 | ucs_4 / (UCS) | ISO-10646-UCS-4. Big Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_4_internal | ucs4_internal, ucs_4internal, ucs4internal | ucs_4_internal / (UCS) | ISO-10646-UCS-4 in system byte order.NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_4be | ucs4be | ucs_4 / (UCS) | Big Endian version of ISO-10646-UCS-4 (in fact, equivalent to ucs_4).Big Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| ucs_4le | ucs4le | ucs_4 / (UCS) | Little Endian version of ISO-10646-UCS-4.Little Endian, NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| us_ascii | ansi_x3.4_1968, ansi_x3.4_1986, iso_646.irv:1991, ascii, iso646_us, us, ibm367, cp367, csascii | us_ascii / (ASCII) | 7-bit ASCII. | 
| utf_16 | utf16 | utf_16 / (UCS) | RFC 2781 UTF-16. The very first NBSP code in stream is interpreted as BOM. | 
| utf_16be | utf16be | utf_16 / (UCS) | Big Endian version of RFC 2781 UTF-16.NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| utf_16le | utf16le | utf_16 / (UCS) | Little Endian version of RFC 2781 UTF-16.NBSP is always interpreted as NBSP (BOM isn’t supported). | 
| utf_8 | utf8 | utf_8 / (UCS) | RFC 3629 UTF-8. | 
| win_1250 | cp1250 | Win-1250 Croatian. | |
| win_1251 | cp1251 | table / win_1251 | Win-1251 - Cyrillic. | 
| win_1252 | cp1252 | table / win_1252 | Win-1252 - Latin 1. | 
| win_1253 | cp1253 | table / win_1253 | Win-1253 - Greek. | 
| win_1254 | cp1254 | table / win_1254 | Win-1254 - Turkish. | 
| win_1255 | cp1255 | table / win_1255 | Win-1255 - Hebrew. | 
| win_1256 | cp1256 | table / win_1256 | Win-1256 - Arabic. | 
| win_1257 | cp1257 | table / win_1257 | Win-1257 - Baltic. | 
| win_1258 | cp1258 | table / win_1258 | Win-1258 - Vietnamese7 that supports Cyrillic. | 
Next: iconv configuration, Previous: Supported encodings, Up: Encoding conversions (iconv.h) [Contents][Index]
The first iconv library design issue arises when considering thefollowing two design approaches:
It’s obvious, that we have tradeoff between commonality/flexibility andefficiency: the first method is more efficient since it convertsdirectly; however, it isn’t so flexible since for eachencoding pair a distinct module is needed.
The Newlib iconv model uses the second method and always converts through the 32-bitUCS but its design also allows one to write specialized conversionmodules if the conversion speed is critical.
The second design issue is how to break down (decompose) encodings.The Newlib iconv library uses the fact that any encoding may beconsidered as one or more CCS plus a CES. It also decomposes itsconversion modules on CES converter plus one or more CCStables. CCS tables map CCS to UCS and vice versa; the CES convertersmap CCS to the encoding and vice versa.
As the example, let’s consider the conversion from the big5 encoding tothe EUC-TW encoding. The big5 encoding may be decomposed to the ASCII and BIG5CCS-es plus the BIG5 CES. EUC-TW may be decomposed on the CNS11643_PLANE1, CNS11643_PLANE2,and CNS11643_PLANE14 CCS-es plus the EUC CES.
The euc_jp -> big5 conversion is performed as follows:
Analogously, the backward conversion is performed as follows:
Note, the above is just an example and real names (which are implementedin the Newlib iconv) of the CES converters and the CCS tables are slightly different.
The third design issue also relates to flexibility. Obviously, it isn’tdesirable to always link all the CES converters and the CCS tables to the librarybut instead, we want to be able to load the needed converters and tablesdynamically on demand. This isn’t a problem on "big" machines such asa PC, but it may be very problematical within "small" embedded systems.
Since the CCS tables are just data, it is possible to load themdynamically from external files. The CES converters, on the other handare algorithms with some code so a dynamic library loadingcapability is required.
Apart from possible restrictions applied by embedded systems (smallRAM for example), Newlib itself has no dynamic library support andtherefore, all the CES converters which will ever be used must be linked intothe library. However, loading of the dynamic CCS tables is possible and isimplemented in the Newlib iconv library. It may be enabled via the Newlibconfigure script options.
The next design issue is fine-tuning the iconv libraryconfiguration. One important ability is for iconv to not link all it’sconverters and tables (if dynamic loading is not enabled) but instead,enable only those encodings which are specified at configurationtime (see the section about the configure script options).
In addition, the Newlib iconv library configure options distinguish betweenconversion directions. This means that not only are supported encodingsselectable, the conversion direction is as well. For example, if user wantsthe configuration which allows conversions from UTF-8 to UTF-16 anddoesn’t plan using the "UTF-16 to UTF-8" conversions, he or she canenable onlythis conversion direction (i.e., no "UTF-16 -> UTF-8"-related code willbe included) thus, saving some memory (note, that such technique allows toexclude one half of a CCS table from linking which may be big enough).
One more design aspect are the speed- and size- optimized tables. Users canselect between them using configure script options. Thespeed-optimized CCS tables are the same as the size-optimized ones incase of 8-bit CCS (e.g.m KOI8-R), but for 16-bit CCS-es the size-optimizedCCS tables may be 1.5 to 2 times less then the speed-optimized ones. On theother hand, conversion with speed tables is several times faster.
Its worth to stress that the new encoding support can’t bedynamically added into an already compiled Newlib library, even if itneeds only an additional CCS table and iconv is configured to usethe external files with CCS tables (this isn’t the fundamental restrictionand the possibility to add new Table-based encoding support dynamically, bymeans of just adding new .cct file, may be easily added).
Theoretically, the compiled-in CCS tables should be more appropriate forembedded systems than dynamically loaded CCS tables. This is because the compiled-in tables are read-only and can be placed in ROMwhereas dynamic loading requires RAM. Moreover, in the current iconvimplementation, a distinct copy of the dynamic CCS file is loaded for each opened iconv descriptor even in case of the same encoding.This means, for example, that if two iconv descriptors for"KOI8-R -> UCS-4BE" and "KOI8-R -> UTF-16BE" are opened, two copies ofkoi8-r .cct file will be loaded (actually, iconv loads only the needed partof these files). On the other hand, in the case of compiled-in CCS tables, there will always be only one copy.
Next: Encoding names, Previous: iconv design decisions, Up: Encoding conversions (iconv.h) [Contents][Index]
To enable an encoding, the –enable-newlib-iconv-encodings configurescript option should be used. This option accepts a comma-separated listof encodings that should be enabled. The option enables each encoding in both("to" and "from") directions.
The --enable-newlib-iconv-from-encodings configure script option enables"from" support for each encoding that was passed to it.
The --enable-newlib-iconv-to-encodings configure script option enables"to" support for each encoding that was passed to it.
Example: if user plans only the "KOI8-R -> UTF-8", "UTF-8 -> ISO-8859-5" and"KOI8-R -> UCS-2" conversions, the most optimal way (minimal iconvcode and data will be linked) is to configure Newlib with the followingoptions:--enable-newlib-iconv-encodings=UTF-8--enable-newlib-iconv-from-encodings=KOI8-R--enable-newlib-iconv-to-encodings=UCS-2,ISO-8859-5
which is the same as--enable-newlib-iconv-from-encodings=KOI8-R,UTF-8--enable-newlib-iconv-to-encodings=UCS-2,ISO-8859-5,UTF-8
User may also just use the--enable-newlib-iconv-encodings=KOI8-R,ISO-8859-5,UTF-8,UCS-2
configure script option, but it isn’t so optimal since there will besome unneeded data and code.
The --enable-newlib-iconv-external-ccs option enables iconv’scapabilities to work with the external CCS files.
The --enable-target-optspace Newlib configure script option also affectsthe iconv library. If this option is present, the library uses the sizeoptimized CCS tables. This means, that only the size-optimized CCStables will be linked or, if the--enable-newlib-iconv-external-ccs configure script option was used,the iconv library will load the size-optimized tables. If the--enable-target-optspaceconfigure script option is disabled,the speed-optimized CCS tables are used.
Note: .cct files are searched by iconv_open in the $NLSPATH/iconv_data/ directory.Thus, the NLSPATH environment variable should be set.
Next: CCS tables, Previous: iconv configuration, Up: Encoding conversions (iconv.h) [Contents][Index]
Each encoding has one name and a number of aliases. Whenuser works with the iconv library (i.e., when the iconv_open callis used) both name or aliases may be used. The same is when encodingnames are used in configure script options.
Names and aliases may be specified in any case (small or capitalletters) and the - symbol is equivalent to the _ symbol.
Internally the Newlib iconv library always converts aliases to names. Italso converts names and aliases in the normalized form which meansthat all capital letters are converted to small letters and the -symbols are converted to _ symbols.
Next: CES converters, Previous: Encoding names, Up: Encoding conversions (iconv.h) [Contents][Index]
The iconv library stores files with CCS tables in the the ccs/subdirectory. The CCS tables for any CCS may be kept in two forms - in the binary form(.cct files, see the ccs/binary/ subdirectory) and in formof compilable .c source files. The .cct files are only used when the--enable-newlib-iconv-external-ccs configure script option is enabled.The .c files are linked to the Newlib library if the correspondingencoding is enabled.
As stated earlier, the Newlib iconv library performs allconversions through the 32-bit UCS, but the codes which are usedin most CCS-es, fit into the first 16-bit subset of the 32-bit UCS set.Thus, in order to make the CCS tables more compact, the 16-bit UCS-2 isused instead of the 32-bit UCS-4.
CCS tables may be 8- or 16-bit wide. 8-bit CCS tables map 8-bit CCS to16-bit UCS-2 and vice versa while 16-bit CCS tables map16-bit CCS to 16-bit UCS-2 and vice versa.8-bit tables are small (in size) while 16-bit tables may be big enough.Because of this, 16-bit CCS tables may beeither speed- or size-optimized. Size-optimized CCS tables aresmaller then speed-optimized ones, but the conversion process isslower if the size-optimized CCS tables are used. 8-bit CCS tables have onlysize-optimized variant.
Each CCS table (both speed- and size-optimized) consists offrom_ucs and to_ucs subtables. "from_ucs" subtable mapsUCS-2 codes to CCS codes, while "to_ucs" subtable maps CCS codes toUCS-2 codes.
Almost all 16-bit CCS tables contain less then 0xFFFF codes anda lot of gaps exist.
In case of 8-bit speed-optimized CCS tables the "to_ucs" subtables format istrivial - it is just the array of 256 16-bit UCS codes. Therefore, anUCS-2 code Y corresponding to a X CCS code is calculatesas Y = to_ucs[X].
Obviously, the simplest way to create the "from_ucs" table or the16-bit "to_ucs" table is to use the huge 16-bit array like in caseof the 8-bit "to_ucs" table. But almost all the 16-bit CCS tables containless then 0xFFFF code maps and this fact may be exploited to reducethe size of the CCS tables.
In this chapter the "UCS-2 -> CCS" 8-bit CCS table format is described. The16-bit "CCS -> UCS-2" CCS table format is the same, except the mappingdirection and the CCS bits number.
In case of the 8-bit speed-optimized table the "from_ucs" subtablecorresponds the "from_ucs" array and has the following layout:
from_ucs array:
————————————-
0xFF mapping (2 bytes) (only for8-bit table).
————————————-
Heading block
————————————-
Block 1
————————————-
Block 2
————————————-
 ...
————————————-
Block N
————————————-
The 0x0000-0xFFFF 16-bit code range is divided to 256 code subranges. Eachsubrange is represented by an 256-element block (256 1-byteelements or 256 2-byte element in case of 16-bit CCS table) withelements which are equivalent to the CCS codes of this subrange.If the "UCS-2 -> CCS" mapping has big enough gaps, some blocks will beabsent and there will be less then 256 blocks.
Any element number m of the heading block (which contains256 2-byte elements) corresponds to the m-th 256-element subrange.If the subrange contains some codes, the value of the m-th element ofthe heading block contains the offset of the corresponding block in the"from_ucs" array. If there is no codes in the subrange, the headingblock element contains 0xFFFF.
If there are some gaps in a block, the corresponding block elements havethe 0xFF value. If there is an 0xFF code present in the CCS, it’s mappingis defined in the first 2-byte element of the "from_ucs" array.
Having such a table format, the algorithm of searching the CCS codeX which corresponds to the UCS-2 code Y is as follows.
As it is stated above, size-optimized tables exist only for 16-bit CCS-es.This is because there is too small difference between the speed-optimizedand the size-optimized table sizes in case of 8-bit CCS-es.
Formats of the "to_ucs" and "from_ucs" subtables are equivalent in case ofsize-optimized tables.
This sections describes the format of the "UCS-2 -> CCS" size-optimizedCCS table. The format of "CCS -> UCS-2" table is the same.
The idea of the size-optimized tables is to split the UCS-2 codes("from" codes) on ranges (range is a number of consecutive UCS-2 codes).Then CCS codes ("to" codes) are stored only for the codes from theseranges. Distinct "from" codes, which have no range (unranged codes, are storedtogether with the corresponding "to" codes.
The following is the layout of the size-optimized table array:
size_arr array:
————————————-
Ranges number (2 bytes)
————————————-
Unranged codes number (2 bytes)
————————————-
Unranged codes array index (2 bytes)
————————————-
Ranges indexes (triads)
————————————-
Ranges
————————————-
Unranged codes array
————————————-
The Unranged codes array index size_arr section helps to findthe offset of the needed range in the size_arr and hasthe following format (triads):
the first code in range, the last code in range, range offset.
The array of these triads is sorted by the firs element, therefore it ispossible to quickly find the needed range index.
Each range has the corresponding sub-array containing the "to" codes. Thesesub-arrays are stored in the place marked as "Ranges" in the layoutdiagram.
The "Unranged codes array" contains pairs ("from" code, "to" code") foreach unranged code. The array of these pairs is sorted by "from" codevalues, therefore it is possible to find the needed pair quickly.
Note, that each range requires 6 bytes to form its index. If, forexample, there are two ranges (1 - 5 and 9 - 10), and one unranged code(7), 12 bytes are needed for two range indexes and 4 bytes for the unrangedcode (total 16). But it is better to join both ranges as 1 - 10 andmark codes 6 and 8 as absent. In this case, only 6 additional bytes for therange index and 4 bytes to mark codes 6 and 8 as absent are needed(total 10 bytes). This optimization is done in the size-optimized tables.Thus, ranges may contain small gaps. The absent codes in ranges are markedas 0xFFFF.
Note, a pair of "from" codes is stored by means of unranged codes sincethe number of bytes which are needed to form the range is greater thanthe number of bytes to store two unranged codes (5 against 4).
The algorithm of searching of the CCS codeX which corresponds to the UCS-2 code Y (input) in the "UCS-2 ->CCS" size-optimized table is as follows.
The .c source files for 8-bit CCS tables have "to_ucs" and "from_ucs"speed-optimized tables. The .c source files for 16-bit CCS tables have"to_ucs_speed", "to_ucs_size", "from_ucs_speed" and "from_ucs_size"tables.
When .c files are compiled and used, all the 16-bit and 32-bit valueshave the native endian format (Big Endian for the BE systems and LittleEndian for the LE systems) since they are compile for the system beforethey are used.
In case of .cct files, which are intended for dynamic CCS tablesloading, the CCS tables are stored either in LE or BE format. Since the.cct files are generated by the ’mktbl.pl’ Perl script, it is possibleto choose the endianess of the tables. It is also possible to store twocopies (both LE and BE) of the CCS tables in one .cct file. The default.cct files (which come with the Newlib sources) have both LE and BE CCStables. The Newlib iconv library automatically chooses the needed CCS tables(with appropriate endianess).
Note, the .cct files are only used when the--enable-newlib-iconv-external-ccs is used.
The ’mktbl.pl’ script is intended to generate .cct and .c CCS tablefiles from the CCS source files.
The CCS source files are just text files which has one or more colonswith CCS <-> UCS-2 codes mapping. To see an example of the CCS tablesource files see one of them using URL-s which will be given bellow.
The following table describes where the source files for CCS table filesprovided by the Newlib distribution are located.
| Name | URL | 
| big5 | http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT | 
| cns11643_plane1cns11643_plane14cns11643_plane2 | http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/CNS11643.TXT | 
| cp775cp850cp852cp855cp866 | http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/ | 
| iso_8859_1iso_8859_2iso_8859_3iso_8859_4iso_8859_5iso_8859_6iso_8859_7iso_8859_8iso_8859_9iso_8859_10iso_8859_11iso_8859_13iso_8859_14iso_8859_15 | http://www.unicode.org/Public/MAPPINGS/ISO8859/ | 
| iso_ir_111 | http://crl.nmsu.edu/~mleisher/csets/ISOIR111.TXT | 
| jis_x0201_1976jis_x0208_1990jis_x0212_1990 | http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/JIS/JIS0201.TXT | 
| koi8_r | http://www.unicode.org/Public/MAPPINGS/VENDORS/MISC/KOI8-R.TXT | 
| koi8_ru | http://crl.nmsu.edu/~mleisher/csets/KOI8RU.TXT | 
| koi8_u | http://crl.nmsu.edu/~mleisher/csets/KOI8U.TXT | 
| koi8_uni | http://crl.nmsu.edu/~mleisher/csets/KOI8UNI.TXT | 
| ksx1001 | http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/KSC/KSX1001.TXT | 
| win_1250win_1251win_1252win_1253win_1254win_1255win_1256win_1257win_1258 | http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/PC/ | 
The CCS source files aren’t distributed with Newlib because of Licenserestrictions in most Unicode.org’s files.
The following are ’mktbl.pl’ options which were used to generate .cctfiles. Note, to generate CCS tables source files -s optionshould be added.
For more info about the ’mktbl.pl’ options, see the ’mktbl.pl -h’ output.
It is assumed that CCS codes are 16 or less bits wide. If there are wider CCS codesin the CCS source file, the bits which are higher then 16 defines plane (see thecns11643.txt CCS source file).
Sometimes, it is impossible to map some CCS codes to the 16-bit UCS if, for example,several different CCS codes are mapped to one UCS-2 code or one CCS code is mapped tothe pair of UCS-2 codes. In these cases, such CCS codes (lostcodes) aren’t just rejected but instead, they are mapped to the defaultUCS-2 code (which is currently the ? character’s code).
Next: The encodings description file, Previous: CCS tables, Up: Encoding conversions (iconv.h) [Contents][Index]
Similar to the CCS tables, CES converters are also split into "from UCS"and "to UCS" parts. Depending on the iconv library configuration, theseparts are enabled or disabled.
The following it the list of CES converters which are currently presentin the Newlib iconv library.
Next: How to add new encoding, Previous: CES converters, Up: Encoding conversions (iconv.h) [Contents][Index]
To simplify the process of adding new encodings support allowing toautomatically generate a lot of "glue" files.
There is the ’encoding.deps’ file in the lib/ subdirectory whichis used to describe encoding’s properties. The ’mkdeps.pl’ Perl scriptuses ’encoding.deps’ to generates the "glue" files.
The ’encoding.deps’ file is composed of sections, each section consistsof entries, each entry contains some encoding/CES/CCS description.
The ’encoding.deps’ file’s syntax is very simple. Currently only twosections are defined: ENCODINGS and CES_DEPENDENCIES.
Each ENCODINGS section’s entry describes one encoding andcontains the following information.
Note all names in the ’encoding.deps’ file have to have the normalizedform.
Each CES_DEPENDENCIES section’s entry describes dependencies ofone CES converted. For example, the euc CES converter depends onthe table and the us_ascii CES converter since theeuc CES converter uses them. This means, that both tableand us_ascii CES converters should be linked if the eucCES converter is enabled.
The CES_DEPENDENCIES section defines the following:
The ’mktbl.pl’ Perl script automatically solves the following tasks.
The ’mktbl.pl’ Perl script is intended to interpret the ’encoding.deps’file and generates the following files.
_iconv_from_ucs_ces and _iconv_to_ucs_ces) which containdescription of enabled "to UCS" and "from UCS" CES converters and thenames of encodings which are supported by these CES converters.Next: The locale support interfaces, Previous: The encodings description file, Up: Encoding conversions (iconv.h) [Contents][Index]
At first, the new encoding should be broken down to CCS and CES. Then,the process of adding new encoding is split to the following activities.
In case a new encoding doesn’t fit to the CES/CCS decomposition model orit is desired to add the specialized (non UCS-based) conversion support,the Newlib iconv library code should be upgraded.
Next: Contact, Previous: How to add new encoding, Up: Encoding conversions (iconv.h) [Contents][Index]
The newlib iconv library also has some interface functions (besides theiconv, iconv_open and iconv_close interfaces) whichare intended for the Locale subsystem. All the locale-related code isplaced in the lib/iconvnls.c file.
The following is the description of the locale-related interfaces:
_iconv_nls_open - opens two iconv descriptors for "CCS ->wchar_t" and "wchar_t -> CCS" conversions. The normalized CCS name ispassed in the function parameters. The wchar_t characters encoding iseither ucs_2_internal or ucs_4_internal depending on size ofwchar_t._iconv_nls_conv - the function is similar to the iconvfunctions, but if there is no character in the output encoding whichcorresponds to the character in the input encoding, the defaultconversion isn’t performed (the iconv function sets such outputcharacters to the ? symbol and this is the behavior, which isspecified in SUSv3)._iconv_nls_get_state - returns the current encoding’s shift state(the mbstate_t object)._iconv_nls_set_state sets the current encoding’s shift state (thembstate_t object)._iconv_nls_is_stateful - checks whether the encoding is statefulor stateless._iconv_nls_get_mb_cur_max - returns the maximum length (themaximum bytes number) of the encoding’s characters.Previous: The locale support interfaces, Up: Encoding conversions (iconv.h) [Contents][Index]
The author of the original BSD iconv library (Alexander Chuguev) no longersupports that code.
Any questions regarding the iconv library may be forwarded toArtem B. Bityuckiy (dedekind@oktetlabs.ru or dedekind@mail.ru) aswell as to the public Newlib mailing list.
Next: Variable Argument Lists, Previous: Encoding conversions (iconv.h), Up: The Red Hat newlib C Library [Contents][Index]
Next: Object Size Checking, Up: Overflow Protection [Contents][Index]
Stack Smashing Protection is a compiler feature which emits extra codeto check for stack smashing attacks. It depends on a canary, which isinitialized with the process, and functions for process termination whenan overflow is detected. These are private entry points intended solelyfor use by the compiler, and are used when any of the -fstack-protector,-fstack-protector-all, -fstack-protector-explicit, or-fstack-protector-strong compiler flags are enabled.
Previous: Stack Smashing Protection, Up: Overflow Protection [Contents][Index]
Object Size Checking is a feature which wraps certain functions with checksto prevent buffer overflows. These are enabled when compiling withoptimization (-O1 and higher) and _FORTIFY_SOURCE definedto 1, or for stricter checks, to 2.
The following functions use object size checking to detect buffer overflowswhen enabled:
String functions:
bcopy memmove strcpybzero mempcpy strcatexplicit_bzero memset strncatmemcpy stpcpy strncpy
Wide Character String functions:
fgetws wcrtomb wcsrtombsfgetws_unlocked wcscat wmemcpymbsnrtowcs wcscpy wmemmovembsrtowcs wcsncat wmempcpywcpcpy wcsncpy wmemsetwcpncpy wcsnrtombs
Stdio functions:
fgets fread_unlocked sprintffgets_unlocked gets vsnprintffread snprintf vsprintf
Stdlib functions:
mbstowcs wcstombs wctomb
System functions:
getcwd read ttyname_rpread readlink
Next: Document Index, Previous: Overflow Protection, Up: The Red Hat newlib C Library [Contents][Index]
The printf family of functions is defined to accept a variablenumber of arguments, rather than a fixed argument list. You can defineyour own functions with a variable argument list, by using macrodefinitions from either stdarg.h (for compatibility with ANSI C)or from varargs.h (for compatibility with a popular conventionprior to ANSI C). 
Next: Traditional macros, varargs.h, Up: Variable Argument Lists [Contents][Index]
In ANSI C, a function has a variable number of arguments when itsparameter list ends in an ellipsis (...). The parameter listmust also include at least one explicitly named argument; that argumentis used to initialize the variable list data structure.
ANSI C defines three macros (va_start, va_arg, andva_end) to operate on variable argument lists. stdarg.halso defines a special type to represent variable argument lists: thistype is called va_list. 
Synopsis
#include <stdarg.h>void va_start(va_list ap, rightmost);
Description
Use va_start to initialize the variable argument list ap,so that va_arg can extract values from it. rightmost isthe name of the last explicit argument in the parameter list (theargument immediately preceding the ellipsis ‘...’ that flagsvariable arguments in an ANSI C function header). You can only useva_start in a function declared using this ellipsis notation(not, for example, in one of its subfunctions).
Returnsva_start does not return a result.
Portability
ANSI C requires va_start.
Next: Abandon a variable argument list, Previous: Initialize variable argument list, Up: ANSI-standard macros, stdarg.h [Contents][Index]
Synopsis
#include <stdarg.h>type va_arg(va_list ap, type);
Descriptionva_arg returns the next unprocessed value from a variableargument list ap (which you must previously create withva_start). Specify the type for the value as the second parameterto the macro, type.
You may pass a va_list object ap to a subfunction, and useva_arg from the subfunction rather than from the functionactually declared with an ellipsis in the header; however, in that caseyou may only use va_arg from the subfunction. ANSI C doesnot permit extracting successive values from a single variable-argumentlist from different levels of the calling stack.
There is no mechanism for testing whether there is actually a nextargument available; you might instead pass an argument count (or someother data that implies an argument count) as one of the fixed argumentsin your function call.
Returnsva_arg returns the next argument, an object of type type.
Portability
ANSI C requires va_arg.
Previous: Extract a value from argument list, Up: ANSI-standard macros, stdarg.h [Contents][Index]
Synopsis
#include <stdarg.h>void va_end(va_list ap);
Description
Use va_end to declare that your program will not use the variableargument list ap any further.
Returnsva_end does not return a result.
Portability
ANSI C requires va_end.
Previous: ANSI-standard macros, stdarg.h, Up: Variable Argument Lists [Contents][Index]
If your C compiler predates ANSI C, you may still be able to usevariable argument lists using the macros from the varargs.hheader file. These macros resemble their ANSI counterparts, but haveimportant differences in usage. In particular, since traditional C hasno declaration mechanism for variable argument lists, two additionalmacros are provided simply for the purpose of defining functions withvariable argument lists.
As with stdarg.h, the type va_list is used to hold a datastructure representing a variable argument list.
Synopsis
#include <varargs.h>function(va_alist)va_dcl
Description
To use the varargs.h version of variable argument lists, you mustdeclare your function with a call to the macro va_alist as itsargument list, and use va_dcl as the declaration. Do notuse a semicolon after va_dcl. 
Returns
These macros cannot be used in a context where a return is syntacticallypossible. 
Portability
va_alist and va_dcl were the most widespread method ofdeclaring variable argument lists prior to ANSI C.
Next: Extract a value from argument list, Previous: Declare variable arguments, Up: Traditional macros, varargs.h [Contents][Index]
Synopsis
#include <varargs.h>va_list ap;va_start(ap);
Description
With the varargs.h macros, use va_start to initialize adata structure ap to permit manipulating a variable argument list.ap must have the type va_alist.
Returnsva_start does not return a result.
Portabilityva_start is also defined as a macro in ANSI C, but thedefinitions are incompatible; the ANSI version has another parameterbesides ap.
Next: Abandon a variable argument list, Previous: Initialize variable argument list, Up: Traditional macros, varargs.h [Contents][Index]
Synopsis
#include <varargs.h>type va_arg(va_list ap, type);
Descriptionva_arg returns the next unprocessed value from a variableargument list ap (which you must previously create withva_start). Specify the type for the value as the second parameterto the macro, type.
Returnsva_arg returns the next argument, an object of type type.
Portability
The va_arg defined in varargs.h has the same syntax andusage as the ANSI C version from stdarg.h.
Previous: Extract a value from argument list, Up: Traditional macros, varargs.h [Contents][Index]
Synopsis
#include <varargs.h>va_end(va_list ap);
Description
Use va_end to declare that your program will not use the variableargument list ap any further.
Returnsva_end does not return a result.
Portability
The va_end defined in varargs.h has the same syntax andusage as the ANSI C version from stdarg.h.
Previous: Variable Argument Lists, Up: The Red Hat newlib C Library [Contents][Index]
| Jump to: | E G L O R S | 
|---|
| Jump to: | E G L O R S | 
|---|