═══ 1. How to Use the Online C Library Reference ═══ The C/C++ Tools Online C Library Reference is a library reference guide for C and C++ programmers. It provides information about the C/C++ Tools implementation of the C language library, including code examples, to enable you to write C and C++ programs. This document is a reference rather than a tutorial. It assumes you are already familiar with C programming concepts. Information applies to the C language, but many of the functions and macros can be called from C++ language applications Before you begin to use this information, it would be helpful to understand how you can: o Expand the Contents to see all available topics o Obtain additional information for a highlighted word or phrase o Use action bar choices How to Use the Contents When the Contents window first appears, some topics have a plus (+) sign beside them. The plus sign indicates that additional topics are available. To expand the Contents if you are using a mouse, click on the plus sign. If you are using the keyboard, use the Up or Down Arrow key to highlight the topic, and press the plus (+) key. For example, Preprocessor Directives has a plus sign beside it. To see additional topics for that heading, click on the plus sign or highlight that topic and press the plus (+) key. To view a topic, double-click on the topic (or press the Up or Down Arrow key to highlight the topic, and then press the Enter key). How to Obtain Additional Information After you select a topic, the information for that topic appears in a window. Highlighted words or phrases indicate that additional information is available. You will notice that certain words and phrases are highlighted in green letters, or in white letters on a black background. These are called hypertext terms. If you are using a mouse, double-click on the highlighted word. If you are using a keyboard, press the Tab key to move to the highlighted word, and then press the Enter key. Additional information then appears in a window. How to Use Action Bar Choices Several choices are available for managing information presented in the C/C++Tools Online Language Reference. There are three pull-down menus on the action bar: the Services menu, the Options menu, and the Help menu. The actions that are selectable from the Services menu operate on the active window currently displayed on the screen. These actions include the following: Bookmark Allows you to set a placeholder so you can retrieve information of interest to you. When you place a bookmark on a topic, it is added to a list of bookmarks you have previously set. You can view the list, and you can remove one or all bookmarks from the list. If you have not set any bookmarks, the list is empty. To set a bookmark, do the following: 1. Select a topic from the Contents. 2. When that topic appears, choose the Bookmark option from the Services pull-down. 3. If you want to change the name used for the bookmark, type the new name in the field. 4. Click on the Place radio button (or press the Up or Down Arrow key to select it). 5. Click on OK (or select it and press Enter). The bookmark is then added to the bookmark list. Search Allows you to find occurrences of a word or phrase in the current topic, selected topics, or all topics. You can specify a word or phrase to be searched. You can also limit the search to a set of topics by first marking the topics in the Contents list. To search for a word or phrase in all topics, do the following: 1. Choose the Search option from the Services pull-down. 2. Type the word or words to be searched for. 3. Click on All sections (or press the Up or Down Arrow keys to select it). 4. Click on Search (or select it and press Enter) to begin the search. 5. The list of topics where the word or phrase appears is displayed. Print Allows you to print one or more topics. You can also print a set of topics by first marking the topics in the Contents list. To print the document Contents list, do the following: 1. Choose Print from the Services pull-down. 2. Click on Contents (or press the Up or Down Arrow key to select it). 3. Click on Print (or select it and press Enter). 4. The Contents list is printed on your printer. Copy Allows you to copy a topic that you are viewing to the System Clipboard or to a file that you can edit. This is particularly useful for copying syntax definitions and program samples into the application that you are developing. You can copy a topic that you are viewing in two ways: o Copy copies the topic that you are viewing into the System Clipboard. If you are using a Presentation Manager* (PM) editor (for example, the Enhanced Editor) that copies or cuts (or both) to the System Clipboard, and pastes to the System Clipboard, you can easily add the copied information to your program source module. o Copy to file copies the topic that you are viewing into a temporary file named TEXT.TMP. You can later edit that file by using any editor. TEXT.TMP is placed in the directory where your viewable document resides. To copy a topic, do the following: 1. Expand the Contents list and select a topic. 2. When the topic appears, choose Copy to file from the Services pull-down. 3. The system puts the text pertaining to that topic into the temporary file TEXT.TMP. For information on any of the choices in the Services pull-down, highlight the choice and press the F1 key. The actions that are selectable from the Options menu allow you to change the way your Contents list is displayed. To expand the Contents and show all levels for all topics, choose Expand all from the Options pull-down. You can also press the Ctrl and * keys together. For information on any of the choices in the Options pull-down, highlight the choice and press the F1 key. The actions that are selectable from the Help menu allow you to select different types of help information. You can also press the F1 key for help information about the Information Presentation Facility (IPF). ═══ Related Information ═══ o Copyright o Edition Notice o Notices o Trademarks and Service Marks ═══ 1.1. Copyright ═══ Copyright International Business Machines Corporation, 1993. All rights reserved. Note to U.S. Government Users - Documentation related to restricted rights - Use, duplication, or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM* Corp. ═══ 1.2. Edition Notice ═══ Second Edition, November 1993. This edition applies to Version 2.01 of IBM C/C++ Tools (82G3733, 82G3735, 82G3736) and to all subsequent releases and modifications until otherwise indicated in new editions. This publication could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; any such changes will be reported in subsequent revisions. Requests for publications and for technical information about IBM* products should be made to your IBM Authorized Dealer or your IBM Marketing Representative. When you send information to IBM, you grant IBM a nonexclusive right to use or distribute the information in any ways it believes appropriate without incurring any obligation to you. ═══ 1.3. Notices ═══ References in this publication to IBM* products, programs, or services do not imply that IBM intends to make these available in all countries in which IBM operates. Any reference to an IBM product, program, or service is not intended to state or imply that only IBM's product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any of IBM's intellectual property rights may be used instead of the IBM product, program, or service. Evaluation and verification of operation in conjunction with other products, programs, or services, except those expressly designated by IBM, are the user's responsibility. IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to the IBM Director of Commercial Relations, IBM Corporation, Purchase, NY 10577. ═══ 1.4. Trademarks and Service Marks ═══ The following terms, denoted by an asterisk (*) in this publication, are trademarks or service marks of IBM* Corporation in the United States or other countries: C/2 C Set/2 C Set ++ Common User Access CUA IBM Operating System/2 OS/2 Personal System/2 Presentation Manager PS/2 SAA Systems Application Architecture WorkFrame/2 The following terms, denoted by a double asterisk (**) in this publication, are trademarks of another county as follows: AT&T AT&T Corporation ═══ IBM Trademark ═══ Trademark of the IBM Corporation. ═══ Non-IBM Trademarks ═══ AT&T is a trademark of AT&T Corporation. ═══ 2. The C Library ═══ This section summarizes the available C library functions. Each library function is listed according to the type of function it performs. o Error Handling o Process Control o File and Directory Management o Searching and Sorting o Mathematical o Floating-Point Unit Control o Time Manipulation o Type Conversion o Stream Input/Output o Low-Level Input/Output o Handling Argument Lists o Pseudorandom Numbers o Dynamic Memory Management o Memory Objects o Environment Interaction o String Operations o Character Testing o Character Case Mapping o Multibyte Character Manipulation o C/C++ Tools Extensions o Intrinsic Functions ═══ 2.1. Error Handling ═══ o assert - Verify Condition o atexit - Record Program Termination Function o _matherr - Process Math Library Errors o perror - Print Error Message o raise - Send Signal o _set_crt_msg_handle - Change Runtime Message Output Handle o signal Install Interrupt Handlers o strerror - Set Pointer to Runtime Error Message o _strerror - Set Pointer to System Error String ═══ 2.2. Process Control ═══ o _beginthread - Create New Thread o _cwait - Wait for Child Process o _disable - Disable Interrupts o _enable - Enable Interrupts o _endthread - Terminate Current Thread o _execl - _execvp - Load and Run Child Process o _exit - End Process o _freemod - Free User DLL o _getpid - Get Process Identifier o _getTIBvalue - Get TIB Value o _interrupt - Call Interrupt Procedure o _loadmod - Load User DLL o _onexit - Record Termination Function o _putenv - Modify Environment Variables o _searchenv - Search for File o _spawnl -_spawnvpe -Start and Run Child Processes o _threadstore - Access Thread-Specific Storage ═══ 2.3. File and Directory Management ═══ o _chdir - Change Current Working Directory o _chdrive - Change Current Working Drive o _fstat - Information about Open File o _fullpath - Get Full Path Name of Partial Path o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _getdrive - Get Current Working Drive o _makepath - Create Path o _mkdir - Create New Directory o _rmdir - Remove Directory o _splitpath - Decompose Path Name o _stat - Get Information about File or Directory ═══ 2.4. Searching and Sorting ═══ o bsearch - Search Arrays o _lfind - _lsearch - Find Key in Array o _lfind - _lsearch - Find Key in Array o qsort - Sort Array ═══ 2.5. Mathematical ═══ o abs - Calculate Integer Absolute Value o acos - Calculate Arccosine o asin - Calculate Arcsine o atan - atan2 - Calculate Arctangent o _cabs - Calculate Absolute Value of Complex Number o ceil - Integer >= Argument o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o div - Calculate Quotient and Remainder o erf - Calculate Error Functions o exp - Exponential Function o fabs - Calculate Floating-Point Absolute Value o _facos - Calculate Arccosine o _fasin - Calculate Arcsine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o floor - Integer <= Argument o fmod - Floating-Point Remainder o _fpatan - Calculate Arctangent o _fptan - Calculate Tangent o frexp - Separate Floating-Point Value o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine o _fsqrt - Calculate Square Root o _fyl2x - Calculate y * log2(x) o _fyl2xp1 - Calculate y * log2(x + 1) o _f2xm1 - Calculate (2**x) - 1 o gamma - Gamma Function o hypot - Calculate Hypotenuse o labs - Calculate long Absolute Value o ldexp - Multiply by a Power of Two o ldiv - Long Division o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o _lrotl - _lrotr - Rotate Bits o _lrotl - _lrotr - Rotate Bits o max - Return Larger of Two Values o min - Return Lesser of Two Values o modf - Separate Floating-Point Value o pow - Compute Power o _rotl - _rotr - Bit Rotation o _rotl - _rotr - Bit Rotation o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o sqrt - Calculate Square Root o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o Bessel Functions ═══ 2.6. Floating-Point Unit Control ═══ o _clear87 - Clear Floating-Point Status Word o _control87 - Set Floating-Point Status Word o _fpreset - Reset Floating-Point Unit o _status87 - Get Floating-Point Status Word ═══ 2.7. Time Manipulation ═══ o asctime - Convert Time o clock - Determine Processor Time o ctime - Convert Time o difftime - Compute Time Difference o _ftime - Store Current Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o _strdate - Copy Current Date o strftime - Convert to Formatted Time o _strtime - Copy Time o time - Determine Current Time o _tzset - Assign Values to Locale Information o _utime - Set Modification Time ═══ 2.8. Type Conversion ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o _itoa - Convert Integer to String o _ltoa - Convert Long Integer to String o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o strtoul - Convert String Segment to Unsigned Integer o _ultoa - Convert Unsigned Long Integer to String ═══ 2.9. Stream Input/Output ═══ Formatted Input/Output o fprintf - Write Formatted Data o fscanf - Read Formatted Data o printf - Formatted Print o scanf - Read Data o sprintf - Formatted Print to Buffer o sscanf - Read Data o vfprintf - Print Argument Data o vprintf - Print Argument Data o vsprintf - Print Argument Data Character and String Input/Output o fgetc - Read a Character o _fgetchar - Read Single Character from stdin o fgets - Read a String o fputc - Write a Character o _fputchar - Write Character o fputs - Print Strings o getc - Read a Character o gets - Read a Line o putc - putchar - Write a Character o putc - putchar - Write a Character o puts - Write a String o ungetc - Push Character onto Input Stream Direct Input/Output o clearerr - Reset Error Indicators o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fread - Read Items o fwrite - Write Items File Positioning o fgetpos - Get File Position o fseek - Reposition File Position o fsetpos - Set File Position o ftell - Get Current Position o _lseek - Move File Pointer o rewind - Adjust Current File Position File Access o fclose - Close Stream o _fcloseall - Close All Open Streams o _fdopen - Associates Input Or Output With File o fflush - Write Buffer to File o _flushall - Write Buffers to Files o fopen - Open Files o freopen - Redirect Open Files o setbuf - Control Buffering o _setmode - Set File Translation Mode o setvbuf - Control Buffering File Operations o _fileno - Determine File Handle o remove - Delete File o rename - Rename File o _rmtmp - Remove Temporary Files o _tempnam - Produce Temporary File Name o tmpfile - Create Temporary File o tmpnam - Produce Temporary File Name o _unlink - Delete File ═══ 2.10. Low-Level Input/Output ═══ o _inp - Read Byte from Input Port o _inpd - Read Double Word from Input Port o _inpw - Read Unsigned Short from Input Port o _outp - Write Byte to Output Port o _outpd - Write Double Word to Output Port o _outpw - Write Word to Output Port o _umask - Sets File Mask of Current Process Character and String Input/Output o _cgets - Read String of Characters from Keyboard o _cprintf - Print Characters to Screen o _cputs - Write String to Screen o _cscanf - Read Data from Keyboard o _getch - _getche - Read Character from Keyboard o _kbhit - Test for Keystroke o _putch - Write Character to Screen o _ungetch - Push Character Back to Keyboard File Positioning o __eof - Determine End of File o _tell - Get Pointer Position File Access o _access - Determine Access Mode o _chmod - Change File Permission Setting o _close - Closes File Associated with Handle o _creat - Create New File o _dup -Associate Second Handle with Open File o _dup2 -Associate Second Handle with Open File o _isatty - Test Handle for Character Device o _open - Open File o _read - Read Into Buffer o _sopen - Open Shared File o _read - Read Into Buffer File Operations o _chsize - Alter Length of File o _filelength - Determine File Length ═══ 2.11. Handling Argument Lists ═══ o va_arg - va_end - va_start - Access Function Arguments ═══ 2.12. Pseudorandom Numbers ═══ o rand - Generate Random Number o srand - Set Seed for rand Function ═══ 2.13. Dynamic Memory Management ═══ o _alloca - Temporarily Reserve Storage Block o calloc - Reserve and Initialize Storage o _debug_calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_heapmin - Release Unused Memory in the Heap o _debug_malloc - Reserve Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _dump_allocated - Get Information about Allocated Storage o free - Release Storage Blocks o _heap_check - Validate Run-Time Storage Heap o _heapmin - Release Unused Memory in the Heap o malloc - Reserve Storage Block o _heap_check - Validate Run-Time Storage Heap o realloc - Change Reserved Storage Block Size o _tcalloc - Reserve Tiled Storage Block o _tfree - Free Tiled Storage Block o _tmalloc - Reserve Tiled Storage Block o _trealloc - Reallocate Tiled Storage Block ═══ 2.14. Memory Objects ═══ o memccpy - Copy Bytes o memchr - Search Buffer o memcmp - Compare Buffers o memcpy - Copy Bytes o memicmp - Compare Bytes o memmove - Copy Bytes o memset - Set Bytes to Value o _swab - Swap Adjacent Bytes ═══ 2.15. Environment Interaction ═══ o abort - Stop a Program o exit - End Program o getenv - Search for Environment Variables o localeconv - Query Locale Conventions o longjmp - Restore Stack Environment o __parmdwords - Get Number of dwords in Parameter List o setjmp - Preserve Environment o setlocale - Set Locale o system - Invoke the Command Processor ═══ 2.16. String Operations ═══ o strcat - Concatenate Strings o strchr - Search for Character o strcmp - Compare Strings o strcmpi - Compare Strings o strcoll - Compare Strings o strcpy - Copy Strings o strcspn - Compare Strings o strdup - Duplicate String o stricmp - Compare Strings o strlen - Determine String Length o strncat - Concatenate Strings o strncmp - Compare Strings o strncpy - Copy Strings o strnicmp - Compare Strings o strnset - strset - Set Characters in String o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strrev - Reverse String o strnset - strset - Set Characters in String o strspn - Search Strings o strstr - Locate Substring o strtok - Tokenize String o strxfrm - Transform Strings ═══ 2.17. Character Testing ═══ o isalnum to isxdigit - Test Integer Value o _isascii - Test Integer Values o _iscsym - _iscsymf - Test Integer o _iscsym - _iscsymf - Test Integer ═══ 2.18. Character Case Mapping ═══ o strlwr - Convert Uppercase to Lowercase o strupr - Convert Lowercase to Uppercase o tolower - toupper - Convert Character Case o tolower - toupper - Convert Character Case o tolower - toupper - Convert Character Case o tolower - toupper - Convert Character Case ═══ 2.19. Multibyte Character Manipulation ═══ o mblen - Multibyte String Length o mbstowcs - Convert Multibyte Characters to wchar_t Characters o mbtowc - Convert Multibyte Character to wchar_t o wctomb - Convert wchar_t Character to Multibyte Character o wcstombs - Convert wchar_t String to Multibyte Character String o wcscat - Append wchar_t Strings o wcschr - Search wchar_t String for Given wchar_t o wcscmp - Compare wchar_t Strings o wcscpy - Copy wchar_t Strings o wcscspn - Find Offset of First wchar_t Match o wcslen - Calculate Length of wchar_t String o wcsncat - Concatenate wchar_t Strings o wcsncmp - Compare wchar_t Strings o wcsncpy - Copy wchar_t Strings o wcspbrk - Locate wchar_t Characters in String o wcsspn - Search wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcswcs - Locate wchar_t Substring in wchar_t String ═══ 2.20. C/C++ Tools Extensions ═══ o _access - Determine Access Mode o _alloca - Temporarily Reserve Storage Block o _atold - Convert ASCII String to Long Double o _beginthread - Create New Thread o _cabs - Calculate Absolute Value of Complex Number o _cgets - Read String of Characters from Keyboard o _chdir - Change Current Working Directory o _chdrive - Change Current Working Drive o _chmod - Change File Permission Setting o _chsize - Alter Length of File o _clear87 - Clear Floating-Point Status Word o _close - Closes File Associated with Handle o _control87 - Set Floating-Point Status Word o _cprintf - Print Characters to Screen o _cputs - Write String to Screen o _creat - Create New File o _cscanf - Read Data from Keyboard o _cwait - Wait for Child Process o _dup -Associate Second Handle with Open File o _dup2 -Associate Second Handle with Open File o _ecvt - Convert Floating-Point to Character o _endthread - Terminate Current Thread o __eof - Determine End of File o _execl - _execvp - Load and Run Child Process o _exit - End Process o _fcloseall - Close All Open Streams o _fcvt - Convert Floating-Point to String o _fdopen - Associates Input Or Output With File o _filelength - Determine File Length o _fileno - Determine File Handle o _flushall - Write Buffers to Files o _fpreset - Reset Floating-Point Unit o _fputchar - Write Character o _freemod - Free User DLL o _fstat - Information about Open File o _ftime - Store Current Time o _fullpath - Get Full Path Name of Partial Path o _gcvt - Convert Floating-Point to String o _getch - _getche - Read Character from Keyboard o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _getdrive - Get Current Working Drive o _getpid - Get Process Identifier o _heapmin - Release Unused Memory in the Heap o _isascii - Test Integer Values o _isatty - Test Handle for Character Device o _iscsym - _iscsymf - Test Integer o _itoa - Convert Integer to String o _kbhit - Test for Keystroke o _lfind - _lsearch - Find Key in Array o _loadmod - Load User DLL o _lrotl - _lrotr - Rotate Bits o _lseek - Move File Pointer o _ltoa - Convert Long Integer to String o _makepath - Create Path o _matherr - Process Math Library Errors o max - Return Larger of Two Values o memccpy - Copy Bytes o memicmp - Compare Bytes o min - Return Lesser of Two Values o _mkdir - Create New Directory o _msize - Return Number of Bytes Allocated o _onexit - Record Termination Function o _open - Open File o __parmdwords - Get Number of dwords in Parameter List o _putch - Write Character to Screen o _putenv - Modify Environment Variables o _read - Read Into Buffer o _rmdir - Remove Directory o _rmtmp - Remove Temporary Files o _rotl - _rotr - Bit Rotation o _searchenv - Search for File o _setmode - Set File Translation Mode o signal Install Interrupt Handlers o _sopen - Open Shared File o spawnl - spawnvpe - Start and Run Child Processes o _splitpath - Decompose Path Name o _stat - Get Information about File or Directory o _status87 - Get Floating-Point Status Word o strcmpi - Compare Strings o _strdate - Copy Current Date o strdup - Duplicate String o _strerror - Set Pointer to System Error String o stricmp - Compare Strings o strlwr - Convert Uppercase to Lowercase o strnicmp - Compare Strings o strnset - strset - Set Characters in String o strrev - Reverse String o _strtime - Copy Time o strtold - Convert String to Long Double o strupr - Convert Lowercase to Uppercase o _swab - Swap Adjacent Bytes o system - Invoke the Command Processor o _tell - Get Pointer Position o _tempnam - Produce Temporary File Name o _toascii - _tolower - _toupper - Convert Character o _tzset - Assign Values to Locale Information o _ultoa - Convert Unsigned Long Integer to String o _umask - Sets File Mask of Current Process o _ungetch - Push Character Back to Keyboard o _unlink - Delete File o _utime - Set Modification Time o _wait - Wait for Child Process o _write - Writes from Buffer to File ═══ 2.21. Intrinsic Functions ═══ When optimization is on, the C/C++ Tools compiler by default generates code instead of a function call for the following C library functions: abs _clear87 _control87 fabs labs memchr memcmp memcpy memmove memset _status87 strcat strchr strcmp strcpy strlen strncat strncmp strncpy strrchr When you #include the appropriate header file in which the function prototype and the #define and #pragma statements for the function are found, the C/C++Tools compiler generates code instead of a function call for these functions. You can override the header either by undefining the macro or by placing the name of the function in parentheses, thus disabling the processor substitution. The function then remains a function call, and is not replaced by the code. The size of your object module is reduced, but your application program runs more slowly. Note: The following functions are built-in functions, meaning they do not have any backing library functions, and are always inlined: _alloca _disable _enable _facos _fasin _fcos _fcossin _fpatan _fptan _fsin _fsincos _fyl2x _fyl2xp1 _f2xm1 _getTIBvalue _inp _inpd _inpw _interrupt _outp _outpd _outpw __parmdwords The built-in functions are all defined in , in addition to the standard header definitions. ═══ 3. Memory Management Functions ═══ This section describes two types of memory management functions: o Debug Memory Management Functions o Tiled Memory Management Functions These functions are extensions to the ANSI/SAA memory management functions that you can use. A brief description is provided for each function, as well as a description of how the functions are invoked and used. ═══ 3.1. Debug Memory Management Functions ═══ The C/C++ Tools compiler provides a set of seven functions to assist you in debugging memory management problems associated with memory allocated by the calloc, malloc, or realloc functions. The debug memory management functions are provided in both the standard and subsystem development libraries, and can help you find where memory is being allocated, written to, or freed incorrectly. This section describes the following debug memory management functions: o _debug_calloc, _debug_free, _debug_heapmin, _debug_malloc, _debug_realloc These functions are variations of the calloc, free, _heapmin, malloc, and realloc functions respectively. They build internal data structures to allow checks to be made on the run-time heap. Each call to one of these functions also automatically calls the _heap_check function. o _heap_check This function checks all memory blocks allocated or freed by the functions listed above to make sure that no overwriting has occurred outside the bounds of allocated blocks or in a free memory block. o _dump_allocated This function prints out information about each memory block currently allocated by the functions listed above. All output from these functions is sent to the OS/2 file handle 2, which is usually associated with stderr. Note: The information provided by these functions is Diagnosis, Modification, and Tuning information only. It is not intended to be used as a programming interface. ═══ Related Information ═══ o Using the Debug Memory Management Functions o Library Functions o Tiled Memory Management Functions ═══ 3.1.1. Using the Debug Memory Management Functions ═══ To use the debug memory management functions: 1. Define the macro __DEBUG_ALLOC__ This macro defines the malloc, calloc, realloc, free, and _heapmin functions to the corresponding debug memory management function. You can define the macro in your source files, or on the command line (using the /D option). 2. Include in each of your source files. If you define __DEBUG_ALLOC__ in your source file, that definition must appear before the #include directive. 3. Place a #pragma strings(readonly) directive at the top of each source file. This directive is not essential, but it ensures that the file name passed to the debug memory management functions cannot be overwritten, and that only one copy of the file name string is included in the object module. Once you have followed the above steps, the _debug_malloc, _debug_calloc, _debug_realloc, _debug_free, and _debug_heapmin functions are automatically called in place of the regular memory management functions in your code. Do not parenthesize any calls to these functions, because parentheses will disable the definition of the function name to the debug function name. The _heap_check function is also called automatically by each of these functions, or you can call it explicitly. To use the _dump_allocated function, you must explicitly call it in your code. Note: o To use the debug memory management functions, set the language level to extended. Specify the /Se option on the command line, or include the #pragma langlvl(extended) directive in your code. o The debug memory management functions are not available if you are using tiled memory (with the /Gt compiler option). o All memory blocks allocated by the _debug_malloc, _debug_calloc, and _debug_realloc functions must be freed using _debug_free, not the free function. If you do not use _debug_free, a message is generated and the process terminates. To ensure that _debug_free is used, define the __DEBUG_ALLOC__ macro in all your modules. o If you copy the examples from the online help and compile and run them, the format of the output you will see will be the same as that shown in the sample output, but the values may be different. ═══ Related Information ═══ o #define o #include o malloc.h o stdlib.h o #pragma langlvl o #pragma strings o /D option o /Gt option o Debug Memory Management Functions o Tiled Memory Management Functions ═══ 3.2. Tiled Memory Management Functions ═══ The C/C++ Tools compiler provides a set of four functions to allow you to manipulate tiled memory. These functions are the 16-bit versions of the C/C++Tools memory functions. This section describes the following tiled memory functions: o _tcalloc, _tfree, _tmalloc, _trealloc. These functions are variations of the calloc, free, malloc, and realloc functions, respectively. They work exactly like the original functions, except that the memory allocated or freed is guaranteed not to cross 64K boundaries, allowing object to be used in 16-bit programs. The tiled memory functions should be used if you have applications that depend on APIs or subroutines that are only available as 16-bit code. Note: Data items larger than 64K in size can be allocated. They will be aligned on 64K boundaries, but they will also cross 64K boundaries. ═══ Related Information ═══ o Using the Tiled Memory Functions o Library Functions ═══ 3.2.1. Using the Tiled Memory Functions ═══ To use the tiled memory management functions: 1. Define the macro __TILED__ in your code. This macro defines the malloc, calloc, free, and realloc functions to the corresponding tiled memory function. You can also define the macro on your command line by setting the /Gt+ compiler option. 2. Include in each of your source files. If you define __TILED__ in your source file, that definition must appear before the #include directive. Once you have followed the above steps, the _tcalloc, _tfree, _tmalloc, and _trealloc functions are automatically called in place of the regular memory management functions in your code. Do not parenthesize any calls to these functions, because parentheses will disable the definition of the function name to the tiled memory function name. Note: o To use the tiled memory management functions, set the language level to extended. Specify the /Se option on the command line, or include the #pragma langlvl(extended) directive in your code. o The debug memory management functions are not available if you are using tiled memory (with the /Gt compiler option). o All memory blocks allocated by the _tcalloc, _tmalloc, and _trealloc functions must be freed using _tfree, not the free function. If you do not use _tfree, a message is generated and the process terminates. To ensure that _tfree is used, define the __TILED__ macro in all your modules. ═══ Related Information ═══ o #define o #include o malloc.h o stdlib.h o /D option o /Gt option o Debug Memory Management Functions ═══ 4. Infinity and NaN Support ═══ The C/C++ Tools compiler supports the use of infinity and NaN (not-a-number) values. Infinity is a value with an associated sign that is mathematically greater in magnitude than any binary floating-point number. A NaN is a value in floating-point computations that is not interpreted as a mathematical value, and that contains a mask state and a sequence of binary digits. The value of infinity can be computed from 1.0 / 0.0 . The value of a NaN can be computed from 0.0 / 0.0 . Depending on its bit pattern, a NaN can be either quiet (NaNQ) or signalling (NaNS), as defined in the ANSI/IEEE Standard for Binary Floating-Point Arithmetic (754-1982). A NaNQ is masked and never generates exceptions. A NaNS may be masked and may generate an exception, but does not necessarily do so. The C/C++ Tools compiler supports only quiet NaN values; all NaN values discussed below refer to quiet NaNs. NaN and infinity values are defined as macro constants in the header file. The macros are: Macro Description _INFINITYF Infinity of type float _INFINITY Infinity of type double _INFINITYL Infinity of type long double _INFF Same as _INFINITYF _INF Same as _INFINITY _INFL Same as _INFINITYL _NANF Quiet NaN of type float _NAN Quiet NaN of type double _NANL Quiet NaN of type long double. The corresponding negative values can be obtained by using the unary minus operator (for example, -_INF). Because these macros are actually references to constant variables, you cannot use them to initialize static variables. For example, the following statements are not allowed: static double infval = _INF; static float nanval = 1.0 + _NANF; However, you can initialize static variables to the numeric values of infinity and Nan: static double infval = 1.0 / 0.0; static float nanval = 0.0 / 0.0; Note: While positive and negative infinities are specific bit patterns, NaNs are not. A NaN value is not equal to itself or to any other value. For example, if you assign a NaN value to a variable x, you cannot check the value of x with the statement if (_NAN == x). Instead, use the statement if (x != x). All relational and equality expressions involving NaN values always evaluate to FALSE or zero (0), with the exception of not equal (!=), which always evaluates to TRUE or one (1). For information on the bit mapping and storage mapping of NaN and infinity values, see the Programming Guide. ═══ Related Information ═══ o Infinity and NaN in Library Functions o Assignment Expression o Equality o Relational o float.h ═══ 4.1. Infinity and NaN in Library Functions ═══ When the language level is set to extended (using the /Se option or the #pragma langlvl(extended) directive), which is the default, infinity and NaN values can be passed as arguments to the scanf and printf families of library functions, and to the string conversion and math functions. At other language levels, these functions work as described in this reference. The following sections describe how the library functions handle the infinity and NaN values: o scanf Family o printf Family o String Conversion Functions o Math Functions ═══ Related Information ═══ o Infinity and NaN Support o #pragma langlvl o /Se option. ═══ 4.1.1. scanf Family ═══ The scanf family of functions includes the SAA functions scanf, fscanf, and sscanf. When reading in floating-point numbers, these functions convert the strings INFINITY, INF, and NAN (in upper-, lower-, or mixed case) to the corresponding floating-point value. The sign of the value is determined by the format specification. Given a string that consists of NAN, INF, or INFINITY, followed by other characters, the scanf functions read in only the NaN or infinity value, and consider the rest of the string to be a second input field. For example, Nancy would be scanned as two fields, Nan and cy. Note: In the case of a string that begins with INF, the functions check the fourth letter. If that letter is not I (in upper- or lowercase), INF is read and converted and the rest of the string is left for the next format specification. If the fourth letter is I, the functions continue to scan for the full INFINITY string. If the string is other than INFINITY, the entire string is discarded. Example of fscanf with NaN and Infinity Values ═══ Example of fscanf with NaN and Infinity Values ═══ /************************************************************************ * In the following example, fscanf converts NaN and infinity strings to their numeric values. * ************************************************************************/ #include int main(void) { int n, count; double d1, d2, d3; FILE *stream; stream = tmpfile(); fputs(" INFINITY NAn INF", stream); rewind(stream); n = fscanf(stream, "%lF%lf%lF%n", &d1, &d2, &d3, &count); if (n != EOF) { printf("Number of fields converted = %d\n", n); printf("Number of characters read = %d\n", count); printf("Output = %f %F %F\n", d1, d2, d3); } return 0; /* The expected output is: Number of fields converted = 3 Number of characters read = 17 Output = infinity NAN INFINITY */ } ═══ Related Information ═══ o Infinity and NaN Support o fscanf - Read Formatted Data o scanf - Read Data o sscanf - Read Data ═══ 4.1.2. printf Family ═══ The printf family of functions includes the SAA functions printf, fprintf, sprintf, vfprintf, vprintf, and vsprintf. These functions convert floating-point values of infinity and NaN to the strings "INFINITY" or "infinity" and "NAN" or "nan". The case is determined by the format specification, as is the sign (positive or negative). When converting these values, the printf functions ignore the precision width given by the format specification. Example of printf with Nan and Infinity Values ═══ Example of printf with Nan and Infinity Values ═══ /************************************************************************ * In the following example, printf converts the NaN and infinity values and prints out the corresponding string. * ************************************************************************/ #include #include int main(void) { double infval = -(_INF); float nanval = _NANF; printf("-_INF is the same as %-15.30f\n", infval); printf("_NANF is the same as %-15.30F\n", nanval); return 0; /* The expected output is: -_INF is the same as -infinity _NANF is the same as NAN */ } ═══ Related Information ═══ o Infinity and NaN Support o fprintf - Write Formatted Data o printf - Formatted Print o sprintf - Formatted Print to Buffer o vfprintf - Print Argument Data o vprintf - Print Argument Data o vsprintf - Print Argument Data ═══ 4.1.3. String Conversion Functions ═══ The string conversion functions include the SAA functions atof and strtod, and the C/C++ Tools standard extensions _atold, _ecvt, _fcvt, _gcvt, and strtold. The atof, _atold, strtod, and strtold functions accept the strings INFINITY, INF, and NAN (in upper-, lower-, or mixed case) as input, and convert these strings to the corresponding macro value defined in . The _ecvt, _fcvt, and _gcvt functions convert infinity and NaN values to the strings INFINITY and NAN, respectively. Note: If a signalling NaN string is passed to a string conversion function, a quiet NaN value is returned, and no signal is raised. Example of atof with NaN and Infinity Values ═══ Example of atof with NaN and Infinity Values ═══ /************************************************************************ * The following example uses atof to convert the strings "naN" and "infinity" to the corresponding macro value. * ************************************************************************/ #include #include int main(void) { char *nanstr; char *infstr; nanstr = "naN"; printf( "Result of atof = %.10e\n", atof(nanstr) ); infstr = "inf"; printf( "Result of atof = %.10E\n", atof(infstr) ); return 0; /* The expected output is: Result of atof = nan Result of atof = INFINITY */ } ═══ Related Information ═══ o Infinity and NaN Support o atof - Convert Character Strings o _atold - Convert ASCII String to Long Double o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o strtod - Convert Character String to Numeric o strtold - Convert String to Long Double ═══ 4.1.4. Math Functions ═══ Most math functions accept infinity, negative infinity, and NaN values as input. (For information on those functions that do not accept these values, see Math Functions without Infinity and NaN Support.) In general, a NaN value as input will result in a NaN value as output, and infinity values as input usually result in infinity values. If the input value is outside the domain or range of the function, errno is set to EDOM or ERANGE, respectively. The following tables display the results of each math function when NaN or infinity values are input, and the associated errno value if one exists. The first table lists the functions that take only one argument; the second lists those that take two arguments. Note: In some cases, infinity is always a valid input value for the function regardless of the language level (for example, atan). These cases do not appear in the tables. ┌──────────────────────────────────────────────────────────────────────────────┐ │ NaN and Infinity Values in Math Functions │ ├───────────────────┬───────────────────┬───────────────────┬──────────────────┤ │ FUNCTION │ INPUT │ RESULT │ "ERRNO" VALUE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ " │ NaN │ NaN " │ │ │ acos │ infinity │ 0 │ EDOM │ │ asin " │ -infinity │ 0 " │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "atan" │ NaN │ NaN │ │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ " │ NaN │ NaN │ │ │ ceil │ infinity │ infinity │ │ │ floor " │ -infinity │ -infinity │ │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ " │ NaN │ NaN │ EDOM │ │ cos │ infinity │ NaN │ ERANGE │ │ tan " │ -infinity │ NaN │ ERANGE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "cosh" │ NaN │ NaN │ │ │ │ infinity │ infinity │ ERANGE │ │ │ -infinity │ infinity │ ERANGE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "erf" │ NaN │ NaN " │ EDOM │ │ │ infinity │ 1 │ │ │ │ -infinity │ -1 " │ │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "erfc" │ NaN │ NaN " │ EDOM │ │ │ infinity │ 0 │ │ │ │ -infinity │ 2 " │ │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "exp" │ NaN │ NaN │ │ │ │ infinity │ infinity " │ ERANGE │ │ │ -infinity │ 0 " │ ERANGE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "fabs" │ NaN │ NaN │ │ │ │ infinity │ infinity │ │ │ │ -infinity │ infinity │ │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "frexp" │ NaN │ NaN, "0" │ EDOM │ │ │ infinity │ NaN, "0" │ EDOM │ │ │ -infinity │ NaN, "0" │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "gamma" │ NaN │ NaN │ EDOM │ │ │ infinity │ infinity │ ERANGE │ │ │ -infinity │ NaN │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ " │ NaN │ NaN │ │ │ log │ infinity " │ infinity │ │ │ log10 " │ 0 │ -infinity │ ERANGE │ │ │ <0 " │ NaN │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "modf" │ NaN │ NaN, NaN │ EDOM │ │ │ infinity │ NaN, infinity │ EDOM │ │ │ -infinity │ NaN, -infinity │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "sin" │ NaN │ NaN │ EDOM │ │ │ infinity │ NaN │ ERANGE │ │ │ -infinity │ NaN │ ERANGE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "sinh" │ NaN │ NaN │ EDOM │ │ │ infinity │ infinity │ ERANGE │ │ │ -infinity │ -infinity │ ERANGE │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "sqrt" │ NaN │ NaN │ │ │ │ infinity │ infinity " │ │ │ │ -infinity │ 0 " │ EDOM │ ├───────────────────┼───────────────────┼───────────────────┼──────────────────┤ │ "tanh" │ NaN │ NaN " │ EDOM │ │ │ infinity │ 1 │ │ │ │ -infinity │ -1 " │ │ └───────────────────┴───────────────────┴───────────────────┴──────────────────┘ The functions in the following table take two arguments. The results from NaN and infinity values vary depending on which argument they are passed as. ┌──────────────────────────────────────────────────────────────────────────────┐ │ Infinity and NaN Values in Math Functions │ ├───────────────┬───────────────┬───────────────┬───────────────┬──────────────┤ │ FUNCTION │ ARGUMENT 1 │ ARGUMENT 2 │ RESULT │ "ERRNO" │ │ │ │ │ │ VALUE │ ├───────────────┼───────────────┼───────────────┼───────────────┼──────────────┤ │ "atan2" │ NaN │ any number │ NaN │ EDOM │ │ │ any number │ NaN │ NaN │ │ ├───────────────┼───────────────┼───────────────┼───────────────┼──────────────┤ │ "fmod" │ NaN │ any number │ NaN │ EDOM │ │ │ any number │ NaN │ NaN │ EDOM │ │ │ ёinfinity │ any number │ 0 │ EDOM │ ├───────────────┼───────────────┼───────────────┼───────────────┼──────────────┤ │ "ldexp" │ infinity │ any number │ infinity │ ERANGE │ │ │ -infinity │ any number │ -infinity │ ERANGE │ │ │ NaN │ any number │ NaN │ EDOM │ ├───────────────┼───────────────┼───────────────┼───────────────┼──────────────┤ │ "pow" │ ёinfinity │ "0" │ NaN │ EDOM │ │ │ infinity │ -infinity │ NaN │ EDOM │ │ │ -infinity │ ёinfinity │ NaN │ EDOM │ │ │ -infinity │ <-1 │ NaN │ EDOM │ │ │ -infinity │ <1, >-1 │ NaN │ EDOM │ │ │ -infinity │ >1 │ NaN │ EDOM │ │ │ NaN │ any number │ NaN │ EDOM │ │ │ any number │ NaN │ NaN │ EDOM │ │ │ =<0 │ infinity │ NaN │ EDOM │ │ │ 1 │ ёinfinity │ NaN │ EDOM │ │ │ ёinfinity │ ё1 │ 0 │ ERANGE │ │ │ >0, <1 │ infinity │ 0 │ ERANGE │ │ │ >0, <1 │ -infinity │ infinity │ ERANGE │ └───────────────┴───────────────┴───────────────┴───────────────┴──────────────┘ Note: If a signalling NaN is passed to a math function, the behavior is undefined. ═══ 4.1.5. Math Functions without Infinity and NaN Support ═══ The following floating-point unit functions are not supported for use with infinity or NaN values. In general, a NaN or infinity value as input for these functions will result in an undefined value, an invalid operation exception, or both. These functions do not set errno. _facos _fasin _fcos _fcossin _fpatan _fptan _fsin _fsincos _fsqrt _fyl2x _fyl2xp1 _f2xm1 Note: If you expect the return value of a math function to be infinity or NaN, you should use the functions that are supported for these values. The advantage in using the floating-point unit math functions is a reduction in the processing time. :enote. ═══ Related Information ═══ o Infinity and NaN Support o math.h o acos - Calculate Arccosine o asin - Calculate Arcsine o atan - atan2 - Calculate Arctangent o ceil - Integer >= Argument o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o erf - Calculate Error Functions o exp - Exponential Function o fabs - Calculate Floating-Point Absolute Value o floor - Integer <= Argument o fmod - Floating-Point Remainder o frexp - Separate Floating-Point Value o gamma - Gamma Function o ldexp - Multiply by a Power of Two o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o modf - Separate Floating-Point Value o pow - Compute Power o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o sqrt - Calculate Square Root o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent ═══ 5. Using Low-Level I/O Functions ═══ The C/C++ Tools compiler supports both stream I/O and low-level I/O. The primary difference between the two types of I/O is that low-level I/O leaves the responsibility of buffering and formatting up to the user. In general, you should not mix input or output from low-level I/O with that from stream I/O. The only way to communicate between stream I/O and low-level I/O is by using the _fdopen or _fileno functions. The low-level I/O functions include: _access _fstat _chmod _isatty _chsize _lseek _close _open _creat _read _dup _setmode _dup2 _sopen __eof _stat _fdopen _tell _filelength _umask _fileno _write When you are using the low-level I/O functions, you should be aware of the following information: o A handle is a value created by the system and used by low-level I/O that identifies a file. The conversion between C and OS/2 API handles is given by: API_handle = C_handle Handles may be passed between library environments without restriction. If a handle is acquired other than by using the C/C++ Tools library functions _open, _creat, _sopen, or _fileno, the function _setmode must be run for that handle before using it with the C/C++ Tools library functions. o The default open-sharing mode is SH_DENYWR. Use _sopen to obtain other sharing modes. o Text mode will delete `\r' characters on input and will change `\n' to `\r\n' on output. o In a multithread environment, it is your responsibility to ensure that two threads do not attempt to perform low level I/O operations on the same file at the same time. You must make sure that one I/O process is completed before another begins. o Low level I/O uses a named shared memory segment, with a name of the form \SHAREMEM\DDE4xxxx.xxx, where x may be any character other than blank. Using a named shared memory segment of this form may cause low level I/O to operate incorrectly. o If the file mode is text, the low-level I/O functions treat the character x1a in the following ways: - The character x1a is treated as end of file on input if it is detected in a nonseekable file. It is only treated as end of file if it is the last character of a seekable file. - If a file is opened as text with either the O_APPEND or O_RDWR flags, and x1a is the last character of the file, the last character of the file is deleted. ═══ Related Information ═══ o Low-Level Input/Output ═══ 6. Library Functions ═══ The C/C++ Tools libraries are divided into two parts: o Standard libraries, which define the SAA features and the C/C++ Tools standard extensions to SAA o Subsystem libraries, which are a subset of the standard library, and are used for subsystem development. This section lists alphabetically and describes all the functions that the C/C++Tools product offers, including the extensions to the SAA C definition. For information on the subsystem libraries and the functions in them, see the chapter called "Developing Subsystems" in the Programming Guide. Each function description includes the following subsections: Format The prototyped declaration of the function and the header file in which it is found. You do not need to include the declaration in your code; it is included with the header file. Language Level The C language standard that each function belongs to. The standard is one of the following: ANSI Functions defined in the ANSI C standard. SAA Functions defined in the SAA C standard. POSIX Functions defined in the POSIX C standard. Extension Functions offered by the C/C++ Tools product as extensions to the above standards. Description A brief description of what the function does, what parameters it takes, and how to use the function. Example A short example of how to use the function. Related Information A list of other functions that are similar to or related to the function. You can use the Copy to File choice from the Services pull-down menu to copy any function example to a separate file (called TEXT.TMP by default). You can then compile, link, and run the example. ═══ 6.1. abort - Stop a Program ═══ ═══ Format ═══ #include void abort(void); ═══ Description ═══ Language Level: ANSI, SAA, Extension The abort function causes an abnormal program termination and returns control to the host environment. The abort function is similar to exit, except that abort does not flush buffers and close open files before ending the program. Calls to abort raise the SIGABRT signal. Example of abort ═══ Example of abort ═══ /************************************************************************ * This example tests for successful opening of the file myfile. If an error occurs, an error message is printed and the program ends with a call to the abort function. * ************************************************************************/ #include #include int main(void) { FILE *stream; if ((stream = fopen("myfile.dat", "r")) == NULL) { perror("Could not open data file"); abort(); } } ═══ Related Information ═══ o exit - End Program o _exit - End Process o signal Install Interrupt Handlers o stdlib.h ═══ 6.2. abs - Calculate Integer Absolute Value ═══ ═══ Format ═══ #include int abs(int n); ═══ Description ═══ Language Level: ANSI, SAA The abs function returns the absolute value of an integer argument n. There is no error return value. The result is undefined when the absolute value of the argument cannot be represented as an integer. The value of the minimum allowable integer is defined by INT_MIN in the include file. Example of abs ═══ Example of abs ═══ /************************************************************************ * This example calculates the absolute value of an integer x and assigns it to y. * ************************************************************************/ #include #include int main(void) { int x = -4, y; y = abs(x); printf("The absolute value of x is %d.\n", y); /********************* Output ************************** The absolute value of x is 4. */ } ═══ Related Information ═══ o _cabs - Calculate Absolute Value of Complex Number o fabs - Calculate Floating-Point Absolute Value o labs - Calculate long Absolute Value o limits.h o stdlib.h ═══ 6.3. _access - Determine Access Mode ═══ ═══ Format ═══ #include int _access(char *pathname, int mode); ═══ Description ═══ Language Level: Extension The _access function determines whether the specified file exists and whether you can get access to it in the given mode. The following list gives possible values for the mode and their meaning in the access call: Value Meaning 06 Check for permission to read from and write to the file. 04 Check for permission to read from the file. 02 Check for permission to write to the file. 00 Check only for the existence of the file. The _access function returns the value 0 if you can get access to the file in the specified mode. A return value of -1 shows that the file does not exist or is inaccessible in the given mode, and the system sets errno to one of the following values: Value Meaning EACCESS Access is denied; the permission setting of the file does not allow you to get access to the file in the specified mode. ENOENT The system cannot find the file or the path that you specified, or the file name was incorrect. EINVAL The mode specified was not valid. EOS2ERR The call to the operating system was not successful. Example of _access ═══ Example of _access ═══ /************************************************************************ * This example checks for the existence of the file sample.dat. If the file does not exist, it is created. * ************************************************************************/ #include #include #include int main(void) { if (-1 == _access("sample.dat",00)) { printf("File sample.dat does not exist.\n"); printf("Creating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (0 == _access("sample.dat",00)) printf("File sample.dat created.\n"); } else printf("File sample.dat exists.\n"); return 0; /**************** The output should be similar to: ******************** File sample.dat does not exist. Creating sample.dat. File sample.dat created. */ } ═══ Related Information ═══ o _chmod - Change File Permission Setting o _sopen - Open Shared File o _umask - Sets File Mask of Current Process o io.h ═══ 6.4. acos - Calculate Arccosine ═══ ═══ Format ═══ #include double acos(double x); ═══ Description ═══ Language Level: ANSI, SAA The acos function calculates the arc cosine of x, expressed in radians, in the range 0 to у. The value of x must be between -1 and 1 inclusive. If x is less than -1 or greater than 1, acos sets errno to EDOM and returns 0. Example of acos ═══ Example of acos ═══ /************************************************************************ * This example prompts for a value for x. It prints an error message if x is greater than 1 or less than -1; otherwise, it assigns the arc cosine of x to y. * ************************************************************************/ #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x, y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for acos\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for acos\n", x ); else { y = acos( x ); printf( "acos( %lf ) = %lf\n", x, y ); } } /******* Expected output if 0.4 is entered: ********* Enter x acos( 0.400000 ) = 1.159279 */ ═══ Related Information ═══ o asin - Calculate Arcsine o atan - atan2 - Calculate Arctangent o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _facos - Calculate Arccosine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.5. _alloca - Temporarily Reserve Storage Block ═══ ═══ Format ═══ #include /* also defined in */ /* and */ void *_alloca(size_t size); ═══ Description ═══ Language Level: Extended The _alloca function is a built-in function that temporarily allocates size bytes of storage space from the program's stack. The memory space is automatically freed when the function that called _alloca returns. Note: The _alloca function is faster than other allocation functions such as malloc, but it has several limitations: o Because it is a built-in function and has no backing code in the library: - You cannot take the address of _alloca. - You cannot parenthesize an _alloca function call because parentheses specify a call to the backing code for the function in the library, and _alloca has no backing code. o Because _alloca automatically frees storage after the function that calls it returns, you cannot pass the pointer value returned by _alloca as an argument to the free function. o You cannot pass memory allocated by _alloca to 16-bit programs, because it is never tiled. Because _alloca uses automatic storage, programs calling _alloca must not be compiled using the /Gs+ switch. This switch disables stack probes and does not guarantee that enough stack storage will be available. You should use the /Gs- switch, which is the default setting. The _alloca function returns a pointer to the reserved space. If _alloca cannot reserve the requested space, the program gets an out of stack exception. Example of _alloca ═══ Example of alloca ═══ /************************************************************************ * This example uses srand to generate five random numbers. The numbers determine how much space _alloca is to allocate for the array barstr. The result is a ragged two-dimensional array of strings. * ************************************************************************/ #include #include #include int main(void) { char *fullbar = "1 2 3 4 5"; int range, rval; char *barstr[5]; int i; printf("Bar representation of 5 random numbers\n "); printf("(each generated from 1 to 5):\n\n"); srand( (unsigned int)time(NULL) ); /* set seed for rand function */ /* using time in seconds */ for (i = 0; i < 5; i++) { rval = (rand() + 1) % 5; /* generate random number from 0 to 4 */ /* for partial copy of fullbar, allocate space on stack for barstr from 2 to 10 characters long + one space for a null character */ barstr[i] = _alloca( (rval * sizeof(char) << 1) + 3 ); memset(barstr[i], '\0', (rval 8 sizeof(char) <<1) + 3); /* copy random sized portion of fullbar */ strncpy(barstr[i], fullbar, ((rval +1) * 2) ); printf("%s\n", barstr[i]); /* print random length bar */ } return 0; /*************** Possible output could be: ******************** Bar representation of 5 random numbers (each generated from 1 to 5): 1 1 2 3 4 1 2 3 1 2 3 4 5 1 2 */ } ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o free - Release Storage Blocks o malloc - Reserve Storage Block o realloc - Change Reserved Storage Block Size o /Gs option o malloc.h o stdlib.h ═══ 6.6. asctime - Convert Time ═══ ═══ Format ═══ #include char *asctime(const struct tm *time); ═══ Description ═══ Language Level: ANSI, SAA The asctime function converts time stored as a structure pointed to by time to a character string. The time value may be obtained from a call to gmtime or localtime; either returns a pointer to a tm structure defined in . See gmtime - Convert Time for a description of the tm structure fields. The string result that asctime produces contains exactly 26 characters and has the format: "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n" See printf - Formatted Print for a description of format specifications. The following are examples of the string returned: Sat Jul 04 02:03:55 1991\n\0 or Sat Jul 04 2:03:55 1991\n\0 The asctime function uses a 24-hour-clock format. The days are abbreviated to: Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have constant width. Days with only one digit are preceded either with a zero or a blank space. The new-line character (\n) and the null character (\0) occupy the last two positions of the string. The time and date functions begin at 00:00:00 Universal Time, January 1, 1970. The asctime function returns a pointer to the resulting character string. There is no error return value. Note: The asctime, ctime, and other time functions may use a common, statically allocated buffer to hold the return string. Each call to one of these functions may destroy the result of the previous call. Example of asctime ═══ Example of asctime ═══ /************************************************************************ * This example polls the system clock and prints a message giving the current time. * ************************************************************************/ #include #include int main(void) { struct tm *newtime; time_t ltime; /* Get the time in seconds */ time(<ime); /* Convert it to the structure tm */ newtime = localtime(<ime); /* Print the local time as a string */ printf("The current date and time are %s", asctime(newtime)); } /**************** Output should be similar to: ****************** The current date and time are Fri Mar 26 13:29:51 1993 */ ═══ Related Information ═══ o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o strftime - Convert to Formatted Time o time - Determine Current Time o printf - Formatted Print o time.h ═══ 6.7. asin - Calculate Arcsine ═══ ═══ Format ═══ #include double asin(double x); ═══ Description ═══ Language Level: ANSI, SAA The asin function calculates the arc sine of x, in the range -у/2 to у/2 radians. The value of x must be between -1 and 1. If x is less than -1 or greater than 1, asin sets errno to EDOM, and returns a value of 0. Example of asin ═══ Example of asin ═══ /************************************************************************ * This example prompts for a value for x. It prints an error message if x is greater than 1 or less than -1; otherwise, it assigns the arc sine of x to y. * ************************************************************************/ #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x, y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for asin\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for asin\n", x ); else { y = asin( x ); printf( "asin( %lf ) = %lf\n", x, y ); } } /**************** Output should be similar to: ****************** Enter x asin( 0.200000 ) = 0.201358 */ ═══ Related Information ═══ o acos - Calculate Arccosine o atan - atan2 - Calculate Arctangent o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _fasin - Calculate Arcsine o _fcossin - Calculate Cosine and Sine o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.8. assert - Verify Condition ═══ ═══ Format ═══ #include void assert(int expression); ═══ Description ═══ Language Level: ANSI, SAA The assert function prints a diagnostic message to stderr and aborts the program if expression is false (zero). The diagnostic message has the format: Assertion failed: expression, file filename, line line-number. The assert function takes no action if the expression is true (nonzero). Use the assert function to identify program logic errors. Choose an expression that holds true only if the program is operating as you intend. After you have debugged the program, you can use the special no-debug identifier NDEBUG to remove the assert calls from the program. If you define NDEBUG to any value with a #define directive, the C preprocessor expands all assert invocations to void expressions. If you use NDEBUG, you must define it before you include in the program. There is no return value. Note: The assert function is a macro. Do not use the #undef directive with the assert function. Example of assert ═══ Example of assert ═══ /************************************************************************ * In this example, the assert function tests the string argument for a null string and an empty string and verifies that the length argument is positive before processing these arguments. * ************************************************************************/ #include #include void analyze (char *, int); int main(void) { char *string = "ABC"; int length = 3; analyze(string, length); printf("The string %s is not null or empty, " "and has length %d \n", string, length); } void analyze(char *string, int length) { assert(string != NULL); /* cannot be NULL */ assert(*string != '\0'); /* cannot be empty */ assert(length > 0); /* must be positive */ } /**************** Output should be similar to: ****************** The string ABC is not null or empty, and has length 3 */ ═══ Related Information ═══ o abort - Stop a Program o assert.h o #define o #undef ═══ 6.9. atan - atan2 - Calculate Arctangent ═══ ═══ Format ═══ #include double atan(double x); double atan2(double y, double x); ═══ Description ═══ Language Level: ANSI, SAA The atan and atan2 functions calculate the arc tangent of x and y/x, respectively. The atan function returns a value in the range -у/2 to у/2 radians. The atan2 function returns a value in the range -у to у radians. If both arguments of atan2 are zero, the function sets errno to EDOM, and returns a value of zero (0). Example of atan - atan2 ═══ Example of atan - atan2 ═══ /************************************************************************ * This example calculates arc tangents using the atan and atan2 functions. * ************************************************************************/ #include #include int main(void) { double a,b,c,d; c = 0.45; d = 0.23; a = atan(c); b = atan2(c,d); printf("atan( %lf ) = %lf\n", c, a); printf("atan2( %lf, %lf ) = %lf\n", c, d, b); } /**************** Output should be similar to: ****************** atan( 0.450000 ) = 0.422854 atan2( 0.450000, 0.230000 ) = 1.098299 */ ═══ Related Information ═══ o acos - Calculate Arccosine o asin - Calculate Arcsine o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _fpatan - Calculate Arctangent o _fptan - Calculate Tangent o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.10. atexit - Record Program Termination Function ═══ ═══ Format ═══ #include int atexit(void (*func)(void)); ═══ Description ═══ Language Level: ANSI, SAA The atexit function records a function, pointed to by func, that the system calls at normal program termination. For portability, you should use atexit to register up to 32 functions only. The functions are executed in a last in, first out order. The atexit function returns zero (0) if it is successful, and nonzero if it fails. Example of atexit ═══ Example of atexit ═══ /************************************************************************ * This example uses the atexit function to call the function goodbye at program termination. * ************************************************************************/ #include #include int main(void) { void goodbye(void); int rc; rc = atexit(goodbye); if (rc != 0) perror("Error in atexit"); exit(0); } void goodbye(void) /* This function is called at normal program termination */ { printf("The function goodbye was called at program termination\n"); } /**************** Output should be similar to: ****************** The function goodbye was called at program termination */ ═══ Related Information ═══ o exit - End Program o _exit - End Process o _onexit - Record Termination Function o signal Install Interrupt Handlers o stdlib.h ═══ 6.11. atof - Convert Character Strings ═══ ═══ Format ═══ #include double atof(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, Extension This function converts a character string to a double-precision floating-point value. The input string is a sequence of characters that can be interpreted as a numerical value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number; this character can be the null character that ends the string. The atof function expects a string in the following form: ─┬──────────────┬──┬───────┬──┬─────────────────────────────────┬─ │ │ │ │ │ │ └──whitespace──┘ ├── + ──┤ ├─digits───┬──────┬───┬────────┬──┤ │ │ │ │ │ │ │ │ └── - ──┘ │ └── . ─┘ └─digits─┘ │ │ │ └──────── . ──digits──────────────┘ ─┬───────────────────────────┬── │ │ ├──e──┬───┬─────┬───digits──┘ │ │ │ │ └──E──┘ ├─ + ─┤ │ │ └─ - ─┘ The white space consists of the same characters for which the isspace function is true, such as spaces and tabs. The atof function ignores leading white-space characters. For the atof function, digits is one or more decimal digits; if no digits appear before the decimal point, at least one digit must appear after the decimal point. The decimal digits can precede an exponent, introduced by the letter e or E. The exponent is a decimal integer, which may be signed. The string can also be "infinity", "inf", or "nan". These strings are case insensitive, and can be preceded by a unary minus (-). They are converted to infinity and NaN values. The atof function returns a double value produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type. The return value is undefined in case of overflow. Example of atof ═══ Example of atof ═══ /************************************************************************ * This example shows how to convert numbers stored as strings to numerical values using the atof function. * ************************************************************************/ #include int main(void) { double x; char *s; s = " -2309.12E-15"; x = atof(s); /* x = -2309.12E-15 */ } ═══ Related Information ═══ o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o Infinity and NaN Support o stdlib.h ═══ 6.12. atoi - Convert Character Strings ═══ ═══ Format ═══ #include int atoi(const char *string); ═══ Description ═══ Language Level: ANSI, SAA This function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numerical value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number; this character can be the null character which ends the string. The atoi function does not recognize decimal points nor exponents. The string argument for this function has the form: ──┬──────────────┬──┬───────┬──digits── │ │ │ │ └──whitespace──┘ ├── + ──┤ │ │ └── - ──┘ where whitespace consists of the same characters for which the isspace function is true, such as spaces and tabs. The atoi function ignores leading white-space characters. digits is one or more decimal digits. atoi returns an int value produced by interpreting the input characters as a number. The return value is 0 if the function cannot convert the input to a value of that type. The return value is undefined in the case of an overflow. Example of atoi ═══ Example of atoi ═══ /************************************************************************ * This example shows how to convert numbers stored as strings to numerical values using the atoi function. * ************************************************************************/ #include int main(void) { int i; char *s; s = " -9885"; i = atoi(s); /* i = -9885 */ } ═══ Related Information ═══ o atof - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o stdlib.h ═══ 6.13. atol - Convert Character Strings ═══ ═══ Format ═══ #include long int atol(const char *string); ═══ Description ═══ Language Level: ANSI, SAA This function converts a character string to a long value. The input string is a sequence of characters that can be interpreted as a numerical value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number; this character can be the null character that ends the string. The atol function does not recognize decimal points nor exponents. The string argument for this function has the form: ──┬──────────────┬──┬───────┬──digits── │ │ │ │ └──whitespace──┘ ├── + ──┤ │ │ └── - ──┘ where whitespace consists of the same characters for which the isspace function is true, such as spaces and tabs. The atol function ignores leading white-space characters. digits is one or more decimal digits. atol returns a long value produced by interpreting the input characters as a number. The return value is 0L if the function cannot convert the input to a value of that type. The return value is undefined in case of overflow. Example of atol ═══ Example of atol ═══ /************************************************************************ * The example shows how to convert numbers stored as strings to numerical values using the atol function. * ************************************************************************/ #include int main(void) { long l; char *s; s = "98854 dollars"; l = atol(s); /* l = 98854 */ } ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o stdlib.h ═══ 6.14. _atold - Convert ASCII String to Long Double ═══ ═══ Format ═══ #include /* also defined in */ long double _atold(const char *nptr); ═══ Description ═══ Language Level: Extension The _atold function converts a character string pointed to by nptr to a long double value. The function continues until it reads a character it does not recognize as part of a number. This character may be the ending null character. Except for its behavior on error, _atold is equivalent to strtold(nptr, (char **)NULL) The string pointed to by nptr must have the following format: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬────────────┬──┬────────────────────────────────────────┬──> │ │ └─whitespace─┘ └─┬─────┬──┬─digits──┬───┬──┬────────┬─┬─┘ │ │ ├─ + ─┤ │ └─.─┘ └─digits─┘ │ │ │ └─ ┴ ─┘ └─.──digits─────────────────┘ │ │ │ │ >──┬──────────────────────────┬──>< │ │ └─┬─ e ─┬──┬─────┬──digits─┘ │ │ └─ E ─┘ ├─ + ─┤ │ │ └─ ┴ ─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ The digits are one or more decimal digits. If no digits appear before the decimal point, at least one digit must follow the decimal point. You can place an exponent expressed as a decimal integer after the digits. The exponent can be signed. The value of nptr can also be one of the strings infinity, inf, or nan. These strings are case insensitive, and can be preceded by a unary minus (-). They are converted to infinity and NaN values. For more information on NaN and infinity values, see Infinity and NaN Support. The _atold function ignores any whitespace characters, as defined by the isspace function. The _atold function returns the converted long double value. In the case of an underflow, it returns 0. In the case of a positive overflow, _atold returns positive _LHUGE_VAL, and negative _LHUGE_VAL for a negative overflow. Example of _atold ═══ Example of _atold ═══ /************************************************************************ * This example uses _atold to convert two strings, " -001234.5678e10end of string" and "NaNQ", to their corresponding long double values. * ************************************************************************/ #include #include int main(void) { char *string; string = " -001234.5678e10end of string"; printf("_atold = %.10Le\n", _atold(string) ); string = "NaNQ"; printf("_atold = %.10Le\n", _atold(string) ); return 0; /* The expected output is: _atold = -1.2345678000e+13 _atold = nan */ } ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o stdlib.h o math.h ═══ 6.15. _beginthread - Create New Thread ═══ ═══ Format ═══ #include /* also defined in */ int _beginthread(void (*start_address) (void *), (void *)stack, unsigned stack_size, void *arglist); ═══ Description ═══ Language Level: Extension The _beginthread function creates a new thread. It takes the following arguments: start_address This parameter is the address of the function that the newly created thread will execute. When the thread returns from that function, it is terminated automatically. You can also explicitly terminate the thread by calling _endthread. stack This parameter is ignored, but is retained to ease migration of C/2 programs. The C/2 compiler requires the second parameter to be the address of the bottom of the stack that the new thread will use. Because the OS/2 operating system automatically takes care of stack allocation, the parameter is not needed. stack_size The size of the stack, in bytes, which is to be allocated for the new thread. The stack size should be a nonzero multiple of 4K and a minimum of 8K. Memory is used when needed, one page at a time. arglist A parameter to be passed to the newly created thread. It is the size of a pointer, and is usually the address of a data item to be passed to the new thread, such as a char string. It provides _beginthread with a value to pass to the child thread. NULL can be used as a placeholder. The function that the new thread will perform must be declared and compiled using _Optlink linkage. An alternative to this function is the OS/2 DosCreateThread API. If you use DosCreateThread, you must also use a #pragma handler statement for the thread function to ensure proper C exception handling. You should also call the _fpreset function at the start of the thread to preset the 387 control status word properly. The use of DosCreateThread requires the use of _endthread to terminate the thread. Note: When using the _beginthread and _endthread functions, you must specify the /Gm+ compiler option to use the multithread libraries. If successful, _beginthread returns the thread ID number of the new thread. It returns -1 to indicate an error. Example of _beginthread ═══ Example of _beginthread ═══ /************************************************************************ * This example uses _beginthread to start a new thread bonjour, which prints Bonjour! five times and then implicitly ends itself. The program then prints a statement indicating the thread identifier number for bonjour. Note: To run this example, you must compile it using the /Gm+ compiler option. * ************************************************************************/ #define INCL_DOS #include #include #include static int wait = 1; void bonjour(void *arg) { int i = 0; while (wait) /* wait until the thread id has been printed */ DosSleep(0l); while ( i++ < 5 ) printf("Bonjour!\n"); } int main(void) { unsigned long tid; tid = _beginthread(bonjour, NULL, 8192, NULL); if ( tid == -1 ) { printf("Unable to start thread.\n"); exit(-1); } else { printf("Thread started with thread identifier number %d.\n", tid); wait = 0; } DosWaitThread( &tid, DCWW_WAIT ); /* wait for thread bonjour to end */ /* before ending main thread */ return 0; /* The expected output (with possible thread id number) is: Thread started with thread identifier number 2. Bonjour! Bonjour! Bonjour! Bonjour! Bonjour! */ } ═══ Related Information ═══ o _endthread - Terminate Current Thread o _threadstore - Access Thread-Specific Storage o /Gm+ option o stdlib.h o process.h ═══ 6.16. Bessel Functions ═══ ═══ Format ═══ #include /* SAA extensions to ANSI */ double _j0(double x); double _j1(double x); double _jn(int n, double x); double _y0(double x); double _y1(double x); double _yn(int n, double x); ═══ Description ═══ Language Level: SAA Bessel functions solve certain types of differential equations. The _j0, _j1, and _jn functions are Bessel functions of the first kind for orders 0, 1, and n, respectively. The _y0, _y1, and _yn functions are Bessel functions of the second kind for orders 0, 1, and n, respectively. The argument x must be positive. The argument n should be greater than or equal to zero. If n is less than zero, it will be a negative exponent. For _j0, _j1, _y0, or _y1, if the absolute value of x is too large, the function sets errno to ERANGE, and returns 0. For _y0, _y1, or _yn, if x is negative, the function sets errno to EDOM and returns the value -HUGE_VAL. For _y0, _y1, or _yn, if x causes overflow, the function sets errno to ERANGE and returns the value -HUGE_VAL. Example of Bessel Functions ═══ Example of Bessel Functions ═══ /************************************************************************ * This example computes y to be the order 0 Bessel function of the first kind for x and z to be the order 3 Bessel function of the second kind for x. * ************************************************************************/ #include int main(void) { double x, y, z; x = 4.27; y = _j0(x); /* y = -0.3660 is the order 0 bessel */ /* function of the first kind for x */ z = _yn(3,x); /* z = -0.0875 is the order 3 bessel */ /* function of the second kind for x */ } ═══ Related Information ═══ o erf - Calculate Error Functions o gamma - Gamma Function o math.h ═══ 6.17. bsearch - Search Arrays ═══ ═══ Format ═══ #include /* also defined in */ void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compare) (const void *element1, const void *element2)); ═══ Description ═══ Language Level: ANSI, SAA, Extension The bsearch function performs a binary search of an array of num elements, each of size bytes The array must be sorted in ascending order by the function pointed to by compare. The base is a pointer to the base of the array to search, and key is the value being sought. The compare variable is a pointer to a function you must supply that compares two array elements and returns a value specifying their relationship. The bsearch function calls this function one or more times during the search, passing the key and the pointer to one array element on each call. The function must compare the elements and then return one of the following values: Value Meaning Less than 0 element1 less than element2 0 element1 identical to element2 Greater than 0 element1 greater than element2 The bsearch function returns a pointer to key in the array to which base points. If two keys are equal, which element key will point to is unspecified. If bsearch cannot find the key, it returns NULL. Example of bsearch ═══ Example of bsearch ═══ /************************************************************************ * This example performs a binary search on the argv array of pointers to the program parameters and finds the position of the argument PATH. It first removes the program name from argv, and then sorts the array alphabetically before calling bsearch. The functions compare1 and compare2 compare the values pointed to by arg1 and arg2 and return the result to bsearch. * ************************************************************************/ #include #include #include int compare1(const void *arg1, const void *arg2); int compare2(const void *arg1, const void *arg2); int main(int argc, char *argv[]) { char **result; char *key = "PATH"; int i; argv++; argc--; qsort((char *)argv, argc, sizeof(char *), compare1); result = (char**)bsearch(key, argv, argc, sizeof(char *), compare2); if (result != NULL) { printf("result = <%s>\n",*result); } else printf("result is null\n"); } int compare1(const void *arg1, const void *arg2) { return (strcmp(*(char **)arg1, *(char **)arg2)); } int compare2(const void *arg1, const void *arg2) { return (strcmp((char *)arg1, *(char **)arg2)); } /******************** Output should be similar to: ************** progname where is PATH in this phrase? result = */ ═══ Related Information ═══ o _lfind - _lsearch - Find Key in Array o qsort - Sort Array o stdlib.h ═══ 6.18. _cabs - Calculate Absolute Value of Complex Number ═══ ═══ Format ═══ #include double _cabs(struct complex z); ═══ Description ═══ Language Level: Extension The _cabs function calculates the absolute value of a complex number. This complex number is represented as a structure with the tag complex containing the real and imaginary parts. The following type declaration is in : struct complex {double x,y;}; A call to _cabs is equivalent to: sqrt(z.x * z.x + z.y * z.y) Note: For portability, use the SAA function hypot to replace _cabs. The _cabs function returns the absolute value as a double value. If an overflow results, _cabs calls the _matherr routine and, if necessary, sets errno to ERANGE and returns the value HUGE_VAL. Example of _cabs ═══ Example of _cabs ═══ /************************************************************************ * * The following program computes the absolute value of the complex number (3.0, 4.0). * ************************************************************************/ #include #include int main(void) { struct complex value; double d; value.x = 3.0; value.y = 4.0; d = _cabs(value); printf("The complex absolute value of %f and %f is %f\n", value.x, value.y, d); return 0; /************ Output should be: ******************************* /* */ The complex absolute value of 3.000000 and 4.000000 is 5.000000 */ } ═══ Related Information ═══ o abs - Calculate Integer Absolute Value o fabs - Calculate Floating-Point Absolute Value o hypot - Calculate Hypotenuse o labs - Calculate long Absolute Value o _matherr - Process Math Library Errors o sqrt - Calculate Square Root o math.h ═══ 6.19. calloc - Reserve and Initialize Storage ═══ ═══ Format ═══ #include /* also defined in */ void *calloc(size_t num, size_t size); ═══ Description ═══ Language Level: ANSI, SAA The calloc function reserves storage space for an array of num elements, each of length size bytes. The calloc function then gives all the bits of each element an initial value of 0. The calloc function returns a pointer to the reserved space. The storage space to which the return value points is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type, use a type cast on the return value. The return value is NULL if there is not enough storage, or if num or size is 0. Example of calloc ═══ Example of calloc ═══ /************************************************************************ * This example prompts for the number of array entries required and then reserves enough space in storage for the entries. If calloc is successful, the example prints out each entry; otherwise, it prints out an error. * ************************************************************************/ #include #include int main(void) { long * array; /* start of the array */ long * index; /* index variable */ int i; /* index variable */ int num; /* number of entries of the array */ printf( "Enter the size of the array\n" ); scanf( "%i", &num ); /* allocate num entries */ if ( (index = array = calloc( num, sizeof( long ))) != NULL ) { for ( i = 0; i < num; ++i ) /* put values in array */ *index++ = i; /* using pointer notation */ for ( i = 0; i < num; ++i ) /* print the array out */ printf( "array[ %i ] = %i\n", i, array[i] ); } else { /* out of storage */ perror( "Out of storage" ); abort(); } } /****************** Output should be similar to: ********************** Enter the size of the array array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2 */ ═══ Related Information ═══ o _alloca - Temporarily Reserve Storage Block o _debug_calloc - Reserve and Initialize Storage o malloc - Reserve Storage Block o _tcalloc - Reserve Tiled Storage Block o free - Release Storage Blocks o malloc - Reserve Storage Block o realloc - Change Reserved Storage Block Size o malloc.h o stdlib.h ═══ 6.20. ceil - Integer >= Argument ═══ ═══ Format ═══ #include double ceil(double x); ═══ Description ═══ Language Level: ANSI, SAA The ceil function computes the smallest integer that is greater than or equal to x. The ceil function returns a double value. Example of ceil ═══ Example of ceil ═══ /************************************************************************ * This example sets y to the smallest integer greater than 1.05, and then to the smallest integer greater than -1.05. The results are 2. and -1., respectively. * ************************************************************************/ #include int main(void) { double y, z; y = ceil(1.05); /* y = 2.0 */ z = ceil(-1.05); /* z = -1.0 */ } ═══ Related Information ═══ o floor - Integer <= Argument o fmod - Floating-Point Remainder o math.h ═══ 6.21. _cgets - Read String of Characters from Keyboard ═══ ═══ Format ═══ #include char *_cgets(char *str); ═══ Description ═══ Language Level: Extension The _cgets function reads a string of characters directly from the keyboard and stores the string and its length in the location pointed to by str. The _cgets function continues to read characters until it meets a carriage-return followed by a line-feed (CR-LF) or until it reads the specified number of characters. It stores the string starting at str[2]. If _cgets reads a CR-LF combination, it replaces this combination with a null character ('\0') before storing the string. The _cgets function then stores the actual length of the string in the second array element, str[1]. The str variable must be a pointer to a character array. The first element of the array, str[0], must contain the maximum length, in characters, of the string to be read. The array must have enough elements to hold the string, a final null character, and 2 additional bytes. If successful, the _cgets function returns a pointer to the actual start of the string, str[2]. Otherwise, _cgets returns NULL. Example of _cgets ═══ Example of _cgets ═══ /************************************************************************ * * This example creates a buffer and initializes the first byte to the size of the buffer. The program then accepts an input string using cgetsand displays the size and text of that string. * ************************************************************************/ #include #include void nothing(void) { } int main(void) { char buffer[82] = { 80, 0 }; char * buffer2; int i; _cputs("\nPress any key to continue."); printf("\n"); while (_kbhit() == 0) { nothing(); } _getch(); _cputs("\nEnter a line of text:"); printf("\n"); buffer2= _cgets(buffer); printf("\nText entered was: %s",buffer2); return 0; } ═══ Related Information ═══ o conio.h o _cputs - Write String to Screen o fgets - Read a String o gets - Read a Line o _getch - _getche - Read Character from Keyboard ═══ 6.22. _chdir - Change Current Working Directory ═══ ═══ Format ═══ #include int _chdir(char *pathname); ═══ Description ═══ Language Level: Extension The _chdir function causes the current working directory to change to the directory specified by pathname. The pathname must refer to an existing directory. Note: This function can change the current working directory on any drive. It cannot change the default drive. For example, if A:\BIN is the current working directory and A: is the default drive, the following changes only the current working directory on drive C:. _chdir ("c:\\emp"); A: is still the default drive. An alternative to this function is the DosSetCurrentDir API call. The _chdir function returns a value of 0 if the working directory was successfully changed. A return value of -1 indicates an error; in this case, _chdir sets errno to ENOENT, showing that _chdir cannot find the specified path name. No error occurs if pathname specifies the current working directory. Example of _chdir ═══ Example of _chdir ═══ /************************************************************************ * * This example changes the current working directory to the root directory, and then to the \red\green\blue directory: * ************************************************************************/ #include #include int main(void) { printf("Changing to the root directory.\n"); if (_chdir("\\")) perror(NULL); else printf("Changed to the root directory.\n\n"); printf("Changing to directory '\\red\\green\\blue'.\n"); if (_chdir("\\red\\green\\blue")) perror(NULL); else printf("Changed to directory '\\red\\green\\blue'.\n"); return 0; /*********** The output should be similar to: ********** Changing to the root directory. Changed to the root directory. Changing to directory '\red\green\blue'. Changed to directory '\red\green\blue'. */ } ═══ Related Information ═══ o _chdrive - Change Current Working Drive o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _getdrive - Get Current Working Drive o system - Invoke the Command Processor o _mkdir - Create New Directory o _rmdir - Remove Directory o system - Invoke the Command Processor o direct.h ═══ 6.23. _chdrive - Change Current Working Drive ═══ ═══ Format ═══ #include int _chdrive(int drive); ═══ Description ═══ Language Level: Extension The _chdrive function changes the current working drive to the drive specified. The drive variable is an integer value representing the number of the new working drive (A: is 1, B: is 2, and so on). To change the default drive, include , define INCL_DOSFILEMGR, and use DosSetDefaultDisk to pass the appropriate command to the operating system. You can also use DosQueryCurrentDisk to query the disk. For more information, refer to the OS/2 2.0 Toolkit documentation. If _chdrive is successful in changing the working drive, it returns 0. A return value of -1 indicates an error; in this case, _chdrive sets errno to EOS2ERR. Example of _chdrive ═══ Example of _chdrive ═══ /************************************************************************ * This example uses _chdrive to change the current working drive to C:. * ************************************************************************/ #include #include int main(void) { if (_chdrive(3)) printf("Cannot change current working drive to 'C' drive.\n"); else { printf("Current working drive changed to "); printf("'%c' drive.\n", ('A'+_getdrive() - 1) ); } return 0; /************** The output should be similar to: ********************** Current working drive changed to 'C' drive. */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _getdrive - Get Current Working Drive o _mkdir - Create New Directory o _rmdir - Remove Directory o direct.h ═══ 6.24. _chmod - Change File Permission Setting ═══ ═══ Format ═══ #include #include int _chmod(char *pathname, int pmode); ═══ Description ═══ Language Level: Extension The _chmod function changes the permission setting of the file specified by pathname. The permission setting controls access to the file for reading or writing. The pmode expression contains one or both of the constants S_IWRITE and S_IREAD, defined in . You can use the _chmod function only if the file is closed. The meanings of the values of the pmode argument are: Value Meaning S_IREAD Reading permitted S_IWRITE Writing permitted S_IREAD | S_IWRITE Reading and writing permitted. If you do not give permission to write to the file, the _chmod function makes the file read-only. With the OS/2 operating system, all files are readable; you cannot give write-only permission. Thus, the modes S_IWRITE and S_IREAD | S_IWRITE set the same permission. Specifying a pmode of S_IREAD is similar to making a file read-only with the ATTRIB system command. The _chmod function returns the value 0 if it successfully changes the permission setting. A return value of -1 shows an error; in this case, the _chmod function set errno to one of the following values: Value Meaning ENOENT The system cannot find the file or the path that you specified, or the file name was incorrect. EOS2ERR The call to the operating system was not successful. EINVAL The mode specified was not valid. Example of _chmod ═══ Example of _chmod ═══ /************************************************************************ * This example opens the file chmod.dat for writing after checking the file to see if writing is permissible. It then writes from the buffer to the opened file. This program takes file names passed as arguments and sets each to read-only. * ************************************************************************/ #include #include #include #include int main(void) { if (-1 == _access("chmod.dat",00)) /* Check if file exists. */ { printf("\nCreating chmod.dat.\n"); system("echo Sample Program > chmod.dat"); printf("_chmod chmod.dat to be readonly.\n"); if (-1 == _chmod("chmod.dat",S_IREAD)) perror("_chmod failed"); if (-1 == _access("chmod.dat",02)) printf("File chmod.dat is now readonly.\n\n"); printf("Run this program again to erase chmod.dat.\n\n"); } else { printf("\nFile chmod.dat exist.\n"); printf("_chmod chmod.dat to become writable.\n"); if (-1 == _chmod("chmod.dat",S_IWRITE)) perror("_chmod failed"); system("erase chmod.dat"); printf("File chmod.dat removed.\n\n"); } return 0; /************ If chmod.dat does not exist, ************************ ******* the output should be similar to: **************** Creating chmod.dat. _chmod chmod.dat to be readonly. File chmod.dat is now readonly. Run this program again to erase chmod.dat. **********************************************************/ } ═══ Related Information ═══ o _access - Determine Access Mode o _sopen - Open Shared File o _umask - Sets File Mask of Current Process o sys\stat.h o io.h ═══ 6.25. _chsize - Alter Length of File ═══ ═══ Format ═══ #include int _chsize(int handle, long size); ═══ Description ═══ Language Level: Extension The _chsize function lengthens or cuts off the file associated with handle to the length specified by size. You must open the file in a mode that permits writing. The _chsize function adds null characters (\0) when it lengthens the file. When _chsize cuts off the file, it erases all data from the end of the shortened file to the end of the original file. The _chsize function returns the value 0 if it successfully changes the file size. A return value of -1 shows an error, and _chsize sets errno to one of the following values: Value Meaning EACCESS The specified file is locked against access. EBADF The file handle is not valid, or the file is not open for writing. ENOSPC There is no space left on the device. EOS2ERR The call to the operating system was not successful. Example of _chsize ═══ Example of _chsize ═══ /************************************************************************ * This example opens a file named sample.dat and returns the current length of that file. It then alters the size of sample.dat and returns the new length of that file. * ************************************************************************/ #include #include #include #include int main(void) { long length; int fh; printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { printf("Unable to open sample.dat.\n"); return 1; } if (-1 == (length = _filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return 1; } printf("Current length of sample.dat is %d.\n",length); printf("Changing the length of sample.dat to 20.\n"); if (-1 == (_chsize(fh,20))) { perror("_chsize failed"); return 1; } if (-1 == (length = _filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return 1; } printf("New length of sample.dat is %d.\n",length); _close(fh); return 0; /***** The output should be similar to: ************ Creating sample.dat. Current length of sample.dat is 17. Changing the length of sample.dat to 20. New length of sample.dat is 20. */ } ═══ Related Information ═══ o _filelength - Determine File Length o _lseek - Move File Pointer o io.h ═══ 6.26. clearerr - Reset Error Indicators ═══ ═══ Format ═══ #include void clearerr (FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The clearerr function resets the error indicator and end-of-file indicator for the specified stream. Once set, the indicators for a specified stream remain set until your program calls clearerr or rewind. The fseek function also clears the end-of-file indicator. Example of clearerr ═══ Example of clearerr ═══ /************************************************************************ * This example reads a data stream and then checks that a read error has not occurred. * ************************************************************************/ #include #include FILE *stream; int c; int main(void) { if ((stream = fopen("myfile.dat", "r")) != NULL) { if ((c=getc(stream)) == EOF) { if (ferror(stream)) { perror("Read error"); clearerr(stream); } } } else exit(0); } ═══ Related Information ═══ o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o perror - Print Error Message o rewind - Adjust Current File Position o strerror - Set Pointer to Runtime Error Message o _strerror - Set Pointer to System Error String o stdio.h ═══ 6.27. _clear87 - Clear Floating-Point Status Word ═══ ═══ Format ═══ #include /* also defined in */ unsigned int _clear87(void); ═══ Description ═══ Language Level: Extension The _clear87 function gets the floating-point status word and then clears it. The floating-point status word is a combination of the numeric coprocessor status word and other conditions that the numeric exception handler detects, such as floating-point stack overflow and underflow. The _clear87 function only affects the current thread. It does not affect any other threads that may be processing. The bits in the value returned reflect the floating-point status before the call to _clear87 was made. Example of _clear87 ═══ Example of _clear87 ═══ /************************************************************************ * This example takes a number close to 0 as a double and assigns it to a float. The result is a loss of significance, y becomes a denormal number, and the underflow bit of the floating-point status word is set. The _clear87 function gets the current floating-point status word and then clears it, and the printf function prints it as immediate data. The result shows the change in the floating-point word because of the loss of significance. The program then assigns the denormal y to another variable, causing the denormal bit to be set in the floating-point status word. Again, the _clear87 gets the current status word and clears it, and printf prints it to the screen. * ************************************************************************/ #include #include double a = 1e-40; double b; float y; int main(void) { unsigned int statword; unsigned int old_cw; /* change control word to mask all exceptions */ _control87(0x037f,0xffff); /* Assignment of the double to the float y is inexact; */ /* the underflow bit is set. */ y = a; statword = _clear87(); printf("floating-point status = 0x%.4x after underflow\n", statword); statword = _status87(); printf("cleared floating-point status word = 0x%.4x\n", statword); /* reset floating point status word */ _fpreset(); /* change control word to mask all exception */ _control87(0x037f,0xffff); /* Reassigning the denormal y to the double b */ /* causes the denormal bit to be set. */ b = y; statword = _clear87(); printf("floating-point status = 0x%.4x for denormal\n", statword); /* reset floating point status word */ _fpreset(); return 0; /* The expected output is: floating-point status = 0x0030 after underflow cleared floating-point status word = 0x0000 floating-point status = 0x0002 for denormal */ } ═══ Related Information ═══ o _control87 - Set Floating-Point Status Word o _status87 - Get Floating-Point Status Word o _fpreset - Reset Floating-Point Unit o float.h ═══ 6.28. clock - Determine Processor Time ═══ ═══ Format ═══ #include clock_t clock(void); ═══ Description ═══ Language Level: ANSI, SAA The clock function returns an approximation of the processor time used by the program since the beginning of an implementation-defined time-period that is related to the program invocation. To obtain the time in seconds, divide the value returned by clock by the value of the macro CLOCKS_PER_SEC. If the value of the processor time is not available or cannot be represented, clock returns the value (clock_t)-1. To measure the time spent in a program, call the clock function at the start of the program, and subtract its return value from the value returned by subsequent calls to clock. Example of clock ═══ Example of clock ═══ /************************************************************************ * This example prints the time elapsed since the program was invoked. * ************************************************************************/ #include #include double time1, timedif;/* use doubles to show small values */ int main(void) { time1 = (double) clock(); /* get initial time */ time1 = time1 / CLOCKS_PER_SEC; /* in seconds */ . . . /* call clock a second time */ timedif = ( ((double) clock()) / CLOCKS_PER_SEC) - time1; printf("The elapsed time is %lf seconds\n", timedif); } ═══ Related Information ═══ o difftime - Compute Time Difference o time - Determine Current Time o time.h ═══ 6.29. _control87 - Set Floating-Point Status Word ═══ ═══ Format ═══ #include /* also defined in */ unsigned int _control87(unsigned int new, unsigned int mask); ═══ Description ═══ Language Level: Extension The _control87 function gets the current floating-point control word and then sets it. The floating-point control word specifies the precision, rounding, and infinity modes of the floating-point chip. You can mask or unmask current floating-point exceptions using the _control87 function. If the value for the mask is equal to 0, _control87 gets the floating-point control word. If the mask is nonzero, _control87 sets a new value for the control word in the manner described below, and returns the previous value of the control word. For any bit in the mask equal to 1, the corresponding bit in new updates the control word. This is equivalent to the expression: fpcntrl = ((fpcntrl & ~ mask) │ (new & mask)) where fpcntrl is the floating-point control word. The _control87 function is used for the current thread only. It does not affect any other threads that may be processing. Warning: If you change the content of the floating-point control word: o The behavior of the math functions with regard to domain and range errors may be undefined. o Math functions may not handle infinity and NaN values correctly. o Some floating-point exceptions may not occur, while other new ones may occur. o Resetting the EM_INEXACT bit may cause SIG_FPE exceptions, which decrease performance. o If the precision or rounding bits are modified, you can reduce the precision available for float and double variables. For information on bits in the control word and handling floating-point exceptions, see the Programming Guide. The bits in the returned value reflect the floating-point control word before the call. Example of _control187 ═══ Example of _control187 ═══ /************************************************************************ * This example prints the initial control word in hexadecimal, and then illustrates different representations of 0.1, depending on the precision. * ************************************************************************/ #include #include double a = .13; int main(void) { printf("control = 0x%.4x\n", _control87(CW_DEFAULT, 0)); /* Get control word */ printf("a*a = .0169 = %.15e\n",a*a); _control87(PC_24, MCW_PC); /* Set precision to 24 bits */ printf("a*a = .0169 (rounded to 24 bits) = %.15e\n",a*a); _control87(CW_DEFAULT, 0xffff); /* Restore to initial default */ printf("a*a = .0169 = %.15e\n",a*a); return 0; /* Possible output could be: control = 0x0362 a*a = .0169 = 1.690000000000000e-02 a*a = .0169 (rounded to 24 bits) = 1.689999046325684e-03 a*a = .0169 = 1.690000000000000e-02 */ } ═══ Related Information ═══ o _clear87 - Clear Floating-Point Status Word o _status87 - Get Floating-Point Status Word o _fpreset - Reset Floating-Point Unit o Floating Point Variables o signal Install Interrupt Handlers o float.h ═══ 6.30. _close - Closes File Associated with Handle ═══ ═══ Format ═══ #include int _close(int handle); ═══ Description ═══ Language Level: Extension The _close function closes the file associated with the handle. Use _close if you opened the handle with _open. If you opened the handle with fopen, use fclose to close it. The _close function returns 0 if it successfully closes the file. A return value of -1 shows an error, and _close sets errno to EBADF, showing an incorrect file handle argument. Example of _close ═══ Example of _close ═══ /************************************************************************ * This example opens the file edclose.dat and then closes it using the _close function. * ************************************************************************/ #include #include #include #include int main(void) { int fh; printf("\nCreating edclose.dat.\n"); if ( -1 == (fh = _open("edclose.dat", O_RDWR | O_CREAT | O_TRUNC, S_IREAD | S_IWRITE))) { perror("Unable to open edclose.dat"); return 1; } printf("File was successfully opened.\n"); if ( -1 == _close(fh)) { perror("Unable to close edclose.dat"); return 1; } printf("File was successfully closed.\n"); return 0; /**************** The output should be similar to: ******************** Creating edclose.dat. File was successfully opened. File was successfully closed. */ } ═══ Related Information ═══ o fclose - Close Stream o _creat - Create New File o _open - Open File o _sopen - Open Shared File o io.h ═══ 6.31. cos - Calculate Cosine ═══ ═══ Format ═══ #include double cos(double x); /* Calculate the cosine of x */ ═══ Description ═══ Language Level: ANSI, SAA The cos function calculates the cosine of x. The value x is expressed in radians. If x is too large, a partial loss of significance in the result may occur. Example of cos ═══ Example of cos ═══ /************************************************************************ * This example calculates y to be the cosine of x. * ************************************************************************/ #include #include int main(void) { double x, y; x = 7.2; y = cos(x); printf("cos( %lf ) = %lf\n", x, y); } /********************* Output should be similar to: ******************* cos( 7.200000 ) = 0.608351 */ ═══ Related Information ═══ o acos - Calculate Arccosine o cosh - Calculate Hyperbolic Cosine o _facos - Calculate Arccosine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.32. cosh - Calculate Hyperbolic Cosine ═══ ═══ Format ═══ #include double cosh(double x); ═══ Description ═══ Language Level: ANSI, SAA The cosh function calculates the hyperbolic cosine of x. The value x is expressed in radians. If the result is too large, cosh returns the value HUGE_VAL and sets errno to ERANGE. Example of cosh ═══ Example of cosh ═══ /************************************************************************ * This example calculates y to be the hyperbolic cosine of x. * ************************************************************************/ #include #include int main(void) { double x,y; x = 7.2; y = cosh(x); printf("cosh( %lf ) = %lf\n", x, y); } /********************* Output should be similar to: ******************* cosh( 7.200000 ) = 669.715755 */ ═══ Related Information ═══ o acos - Calculate Arccosine o cos - Calculate Cosine o _facos - Calculate Arccosine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.33. _cprintf - Print Characters to Screen ═══ ═══ Format ═══ #include int _cprintf(char *format-string, argument-list); ═══ Description ═══ Language Level: Extension The _cprintf function formats and sends a series of characters and values directly to the screen, using the _putch function to send each character. The format-string has the same form and function as the format-string parameter for printf. Format specifications in the format-string determine the output format for any argument-list that follows. See printf for a description of the format-string. Note: Unlike the fprintf, printf, and sprintf functions, _cprintf does not translate line feed characters into output of a carriage-return followed by a line-feed. The _cprintf function returns the number of characters printed. Example of _cprintf ═══ Example of _cprintf ═══ /************************************************************************ * The following program uses _cprintf to write strings to the screen. * ************************************************************************/ #include int main(void) { char buffer[24]; _cprintf("\nPlease enter a file name:\n"); _cscanf("%23s", buffer); _cprintf("\nThe file name you entered was %23s.", buffer); return 0; /****************** The output should be similar to: ****************** Please enter a file name: file.dat The file name you entered was file.dat. */ } ═══ Related Information ═══ o _cscanf - Read Data from Keyboard o fprintf - Write Formatted Data o printf - Formatted Print o _putch - Write Character to Screen o sprintf - Formatted Print to Buffer o conio.h ═══ 6.34. _cputs - Write String to Screen ═══ ═══ Format ═══ #include int _cputs(char *str); ═══ Description ═══ Language Level: Extension The _cputs function writes directly to the screen the string to which str points. The string str must end with a null character (\0). The _cputs function does not automatically add a carriage-return followed by a line-feed to the string after writing. If successful, _cputs returns 0. Otherwise, it returns a nonzero value. Example of _cputs ═══ Example of _cputs ═══ /************************************************************************ * This example puts a prompt out to the screen. * ************************************************************************/ #include int main(void) { char *buffer = "Insert data disk in drive a: \r\n"; _cputs(buffer); return 0; /*************** The output should be similar to: ********************* Insert data disk in drive a: */ } ═══ Related Information ═══ o _cgets - Read String of Characters from Keyboard o fputs - Print Strings o _putch - Write Character to Screen o puts - Write a String o conio.h ═══ 6.35. _creat - Create New File ═══ ═══ Format ═══ #include #include int _creat(char *pathname, int pmode); ═══ Description ═══ Language Level: Extension The _creat function either creates a new file or opens and truncates an existing file. If the file specified by pathname does not exist, _creat creates a new file with the given permission setting and opens for writing in text mode. If the file already exists, and the read-only attribute and sharing permissions allow writing, _creat truncates the file to length 0. This destroys the previous contents of the file and opens it for writing in text mode. The _creat function always opens a file in text mode for reading and writing. The permission setting pmode applies to newly created files only. The new file receives the specified permission setting after you close it for the first time. The pmode integer expression contains one or both of the constants S_IWRITE and S_IREAD, defined in . The values of the pmode argument and their meanings are: Value Meaning S_IREAD Reading permitted S_IWRITE Writing permitted S_IREAD | S_IWRITE Reading and writing permitted. If you do not give permission to write to the file, the file is a read-only file. On the OS/2 operating system, you cannot give write-only permission. Thus, the modes S_IWRITE and S_IREAD | S_IWRITE have the same results. The _creat function applies the current file permission mask to pmode before setting the permissions. (See _umask - Sets File Mask of Current Process for more information about file permission masks.) When writing new code, you should use _open rather than _creat. Specifying a pmode of S_IREAD is similar to making a file read-only with the ATTRIB system command. The _creat function returns a handle for the created file if the call is successful. A return value of -1 shows an error, and _creat sets errno to one of the following values: Value Meaning EACCESS File sharing violated. EINVAL The mode specified was not valid. EMFILE No more file handles are available. ENOENT The path name was not found, or the file name was incorrect. EOS2ERR The call to the operating system was not successful. Example of _creat ═══ Example of _creat ═══ /************************************************************************ * This example creates the file sample.dat so it can be read from and written to. * ************************************************************************/ #include #include #include int main(void) { int fh; fh = _creat("sample.dat", S_IREAD | S_IWRITE); if ( -1 == fh) { perror("Error in creating sample.dat"); return 1; } else printf("Successfully created sample.dat.\n"); _close(fh); return 0; /****************** Expected output is: ******************************* Successfully created sample.dat. */ } ═══ Related Information ═══ o _chmod - Change File Permission Setting o _close - Closes File Associated with Handle o _open - Open File o _fdopen - Associates Input Or Output With File o _sopen - Open Shared File o _umask - Sets File Mask of Current Process o sys\stat.h o io.h ═══ 6.36. _CRT_init - Initialize DLL Runtime Environment ═══ ═══ Format ═══ int _CRT_init(void); ═══ Description ═══ Language Level: Extended Before you can call any C/C++ Tools library functions, you must first initialize the runtime environment. Use the function _CRT_init, which is provided in the runtime libraries. If the runtime environment is successfully initialized, _CRT_init returns 0. A return code of -1 indicates an error. If an error occurs, an error message is written to file handle 2, which is the usual destination of stderr. If your DLL contains C++ code, you must also call __ctordtorInit after _CRT_init to ensure that static constructors and destructors are initialized properly. The prototype for __ctordtorInit is: void __ctordtorInit(void); Note: If you are providing your own version of the _matherr function to be used in your DLL, you must call the _exception_dllinit function after the runtime environment is initialized. Calling this function ensures that the proper _matherr function will be called during exception handling. The prototype for this function is: void _Optlink _exception_dllinit( int (*)(struct exception *) ); The parameter required is the address of your _matherr function. ═══ Related Information ═══ o _DLL_InitTerm - Initialize and Terminate DLL Environment o _CRT_term - Terminate DLL Runtime Environment ═══ 6.37. _CRT_term - Terminate DLL Runtime Environment ═══ ═══ Format ═══ void _CRT_term(void); ═══ Description ═══ Language Level: Extended If your DLL is statically linked, you must use the _CRT_term function to correctly terminate the C runtime environment. The _CRT_term function is provided in the C/C++ Tools runtime libraries. If your DLL contains C++ code, you must also call __ctordtorTerm before you call _CRT_term to ensure that static constructors and destructors are terminated correctly. The prototype for __ctordtorTerm is: void __ctordtorTerm(void); Once you have called _CRT_term, you cannot call any other library functions. If your DLL is dynamically linked, you cannot call library functions in the termination section of your _DLL_InitTerm function. If your termination routine requires calling library functions, you must register the termination routine with DosExitList. Note that all DosExitList routines are called before DLL termination routines. ═══ Related Information ═══ o _CRT_init - Initialize DLL Runtime Environment o _DLL_InitTerm - Initialize and Terminate DLL Environment ═══ 6.38. _cscanf - Read Data from Keyboard ═══ ═══ Format ═══ #include int _cscanf(char *format-string, argument-list); ═══ Description ═══ Language Level: Extension The _cscanf function reads data directly from the keyboard to the locations given by argument-list, if any are specified. The _cscanf function uses the _getche function to read characters. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string. The format-string controls the interpretation of the input fields and has the same form and function as the format-string argument for the scanf function. See scanf for a description of the format-string. Note: Although _cscanf normally echoes the input character, it does not do so if the last action was a call to _ungetch. The _cscanf function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF for an attempt to read at the end of the file. A return value of 0 means that no fields were assigned. Example of _cscanf ═══ Example of _cscanf ═══ /************************************************************************ * This example uses _cscanf to read strings from the screen. * ************************************************************************/ #include int main(void) { char buffer[24]; _cprintf("\nPlease enter a file name:\n"); _cscanf("%23s", buffer); _cprintf("\nThe file name you entered was %23s.", buffer); return 0; /****************** The output should be similar to: ****************** Please enter a file name: file.dat The file name you entered was file.dat. */ } ═══ Related Information ═══ o fscanf - Read Formatted Data o _getch - _getche - Read Character from Keyboard o scanf - Read Data o sscanf - Read Data o _ungetch - Push Character Back to Keyboard o conio.h ═══ 6.39. ctime - Convert Time ═══ ═══ Format ═══ #include char *ctime(const time_t *time); ═══ Description ═══ Language Level: ANSI, SAA The ctime function converts the time value pointed to by time to local time in the form of a character string. A time value is usually obtained by a call to the time function. The string result produced by ctime contains exactly 26 characters and has the format "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n" for example: Mon Jul 16 02:03:55 1987\n\0 The ctime function uses a 24-hour clock format. The days are abbreviated to: Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have a constant width. Dates with only one digit are preceded either with a zero or a blank space, depending on the compiler. The new-line character (\n) and the null character (\0) occupy the last two positions of the string. Note: The asctime, ctime, and other time functions may use a common, statically allocated buffer for holding the return string. Each call to one of these functions may destroy the result of the previous call. The time and date functions begin at 00:00:00 Universal Time, January 1, 1970. The ctime function returns a pointer to the character string result. There is no error return value. The ctime function is equivalent to: asctime(localtime(&anytime)) Example of ctime ═══ Example of ctime ═══ /************************************************************************ * This example polls the system clock by using the library function time. It then prints a message giving the current date and time. * ************************************************************************/ #include #include int main(void) { time_t ltime; time(<ime); printf("the time is %s", ctime(<ime)); } ═══ Related Information ═══ o asctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o strftime - Convert to Formatted Time o time - Determine Current Time o time.h ═══ 6.40. _cwait - Wait for Child Process ═══ ═══ Format ═══ #include int _cwait(int *stat_loc, int process_id, int action_code); ═══ Description ═══ Language Level: Extension The _cwait function delays the completion of a parent process until the child process specified by process_id ends. The process_id is the value returned by the _spawn function that started the child process. If the specified child process ends before _cwait is called, _cwait returns to the calling process immediately with a value of -1. If the value of process_id is 0, the parent process waits until all of its child processes end. If the variable pointed to by stat_loc is NULL, the _cwait function does not use it. If it is not NULL, _cwait places information about the return status and the return code of the child process in the location to which stat_loc points. If the child process ended normally with a call to the OS/2 DosExit API, the lowest-order byte of the variable pointed to by stat_loc is 0. The next highest-order byte contains the lowest-order byte of the argument passed to DosExit by the child process. The value of this byte depends on how the child process caused the system to call DosExit. If the child called exit, _exit, or return from main, or used a DosExit coded into the program, the byte contains the lowest-order byte of the argument the child passed to exit, _exit, or return. The value of the byte is undefined if the child caused a DosExit call simply by reaching the end of main. If the child process ended abnormally (without a call to DosExit), the lowest-order byte of the variable pointed to by stat_loc contains the return code from the OS/2 DosWaitChild API, and the next higher-order byte is 0. See the OS/2 online reference for details about the DosWaitChild return codes. The action_code specifies when the parent process is to start running again. Values for action_code include: Action Code Meaning WAIT_CHILD The parent process waits until the specified child process ends. WAIT_GRANDCHILD The parent process waits until the child process and all of the child processes of that process end. The action code values are defined in . Note: Because the size of an int is only 2 bytes in 16-bit compilers, if you are migrating a 16-bit program, some parts of your programs may have to be rewritten if they use this function. An alternative to this function is the DosWaitChild API call. At the normal end of the child process, _cwait returns the process identifier of the child to the parent process. If a child process ends abnormally, _cwait returns -1 to the parent process and sets errno to EINTR. In the case of an error, _cwait returns immediately with a value of -1 and sets errno to one of the following values: Value Meaning EINVAL Incorrect action code ECHILD No child process exists, or the process identifier is incorrect. Example of _cwait ═══ Example of _cwait ═══ /************************************************************************ * This example creates a new process called child.exe. The parent calls _cwait and waits for the child to end. The parent then displays the child's return information in hexadecimal. * ***********************************************************************/ #include #include #include int stat_child; int main(void) { int i, result; /* spawn a child and 'cwait' for it to finish*/ if ((result = _spawnl(P_NOWAIT,"child","child","1", NULL)) != -1) { if ((i= _cwait(&stat_child,result,WAIT_CHILD)) != result) printf("Error ...expected pid from child"); else { if (errno == 0) { printf("Child process ended successfully and ...\n"); printf("program returned to the Parent process.\n"); } else printf("Child process had an error\n"); } } else printf("Error ...could not spawn a child process\n"); return 0; } /************** If the source code for child.exe is: **************** #include int main(void) { puts("This line was written by child.exe"); } */ *************** then the output should be similar to: ************** This line was written by child.exe Child process ended successfully and ... program returned to the Parent process. */ ═══ Related Information ═══ o exit - End Program o _exit - End Process o _spawnl -_spawnvpe -Start and Run Child Processes o _wait - Wait for Child Process o return o process.h ═══ 6.41. _debug_calloc - Reserve and Initialize Storage ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void *_debug_calloc(size_t num, size_t size, const char *pFilename, size_t linenum); ═══ Description ═══ Language Level: Extension The _debug_calloc function is the debug version of calloc, and performs the same function as calloc. It reserves storage space for an array of num elements, each of length size bytes, and initializes all bits of each element to 0. In addition, _debug_calloc makes an implicit call to the _heap_check function. It also stores the name of the file pFilename and the line number linenum where the storage is allocated. This information can be used later by _heap_check and the _dump_allocated function. The _debug_calloc function returns a pointer to the reserved space. If not enough storage is available, or if num or size is 0, _debug_calloc returns NULL. Example of _debug_calloc ═══ Example of _debug_calloc ═══ /************************************************************************ * This example reserves storage of 124 bytes. It then attempts to write to storage that was not allocated. When _debug_calloc is called again, _heap_check detects the error, generates several messages, and stops the program. Note: Although the function calloc is coded in the example, the __DEBUG_ALLOC__ macro redefines calloc to _debug_calloc. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr; if (( ptr = calloc(2, 62) ) == NULL) { printf( "Could not allocate memory block.\n" ); return EXIT_FAILURE; } *(ptr + 124) = 'a'; /* overwrites storage that was not allocated */ ptr = calloc(23, 45); /* this call to calloc invokes _heap_check */ printf("_debug_calloc did not detect that a memory block was overwritten.\n"); return EXIT_FAILURE; /* Possible output is: Memory was overwritten after the allocated memory block that starts at address 0x000B0F10. The first eight bytes of the memory block (in hex) are: 0000000000000000. This memory block was (re)allocated at line number 11 in TDCALLC.C. */ } ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_malloc - Reserve Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _dump_allocated - Get Information about Allocated Storage o _heap_check - Validate Run-Time Storage Heap o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.42. _debug_free - Release Storage Blocks ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void _debug_free(void *ptr, const char *pFilename, size_t linenum); ═══ Description ═══ Language Level: Extension The _debug_free function is the debug version of free, and performs the same function as free. It frees the block of storage pointed to by ptr that has been allocated by either a normal or a debug version of the memory management functions. In addition, _debug_free makes an implicit call to the _heap_check function. It also stores the file name pFilename and the line number linenum where the storage is freed. This information can be used later by _heap_check and the _dump_allocated function. Note: If the block of storage pointed to by ptr was not allocated using the memory management functions or was previously freed, a message appears and the program ends. There is no return value. Example of _debug_free ═══ Example of _debug_free ═══ /************************************************************************ * This example reserves two blocks of 62 bytes each. It then frees the first block and attempts to overwrite the freed storage. When _debug_free is called a second time, _heap_check detects the error, prints out several messages, and stops the program. Note: Although the function free is coded in the example, the __DEBUG_ALLOC__ macro redefines free to _debug_free. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr1; char *ptr2; if ( (( ptr1 = malloc(62) ) == NULL) || (( ptr2 = malloc(62) ) == NULL) ) { printf("Could not allocate memory block.\n"); return EXIT_FAILURE; } free(ptr1); *(ptr1 - 1) = 'a'; /* overwrites storage that has been freed */ free(ptr2); /* this call to free invokes _heap_check */ printf("_debug_free did not detect that a free memory block was overwritten.\n"); return EXIT_FAILURE; /* Possible output is: Memory was overwritten before the free memory block that starts at address 0x00150010. The first eight bytes of the memory block (in hex) are: B5B5A5A500000000. This memory block was freed at line number 17 in TDFREE.C. */ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _debug_malloc - Reserve Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _dump_allocated - Get Information about Allocated Storage o free - Release Storage Blocks o _heap_check - Validate Run-Time Storage Heap o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.43. _debug_heapmin - Release Unused Memory in the Heap ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ int _debug_heapmin(const char *pFilename, size_t linenum); ═══ Description ═══ Language Level: Extension The _debug_heapmin function is the debug version of _heapmin, and performs the same function as _heapmin. It returns all unused memory from the run-time heap to the operating system. In addition, _debug_heapmin makes an implicit call to the _heap_check function. It also stores the file name pFilename and the line number linenum where the memory is returned. This information can be used later by _heap_check and the _dump_allocated function. If successful, _debug_heapmin returns 0; otherwise, it returns -1. Example of _debug_heapmin ═══ Example of _debug_heapmin ═══ /************************************************************************ * This example allocates 5000 bytes of storage, then changes the storage size to 35 bytes, and uses _debug_heapmin to return the unused memory to the operating system. The storage is then freed, and the program attempts to overwrite the freed storage. When _debug_heapmin is called again, _heap_check detects the error, generates several messages, and stops the program. Note: Although the function _heapmin is coded in the example, the __DEBUG_ALLOC__ macro redefines _heapmin to _debug_heapmin. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr; ptr = malloc(5000); ptr = realloc(ptr, 35); _heapmin(); /* no allocation problems to detect */ free(ptr); *ptr = 'a'; /* overwrites storage that has been freed */ _heapmin(); /* this call to _heapmin invokes _heap_check */ printf("_debug_heapmin did not detect that a free memory block was accessed\n"); return 0; /* Possible output is: The free memory block that starts at address 0x00150010 has been accessed. The first eight bytes of the memory block (in hex) are: 61B5A5A500000000. This memory block was freed at line number 17 in THPMIN.C. */ } ═══ Related Information ═══ o _dump_allocated - Get Information about Allocated Storage o _heapmin - Release Unused Memory in the Heap o _heap_check - Validate Run-Time Storage Heap o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.44. _debug_malloc - Reserve Storage Blocks ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void *_debug_malloc(size_t size, const char *pFilename, size_t linenum); ═══ Description ═══ Language Level: Extension The _debug_malloc function is the debug version of malloc, and performs the same function as malloc. It reserves a block of storage of size bytes. In addition, _debug_malloc makes an implicit call to the _heap_check function. It also stores the file name pFilename and the line number linenum where the storage is allocated. This information can later be used by _heap_check and the _dump_allocated function. The _debug_malloc function returns a pointer to the reserved space. If not enough storage is available or if size is 0, _debug_malloc returns NULL. Example of _debug_malloc ═══ Example of _debug_malloc ═══ /************************************************************************ * This example allocates 62 bytes of storage. It then attempts to write to storage that was not allocated. When _debug_malloc is called again, _heap_check detects the error, generates several messages, and stops the program. Note: Although the function malloc is coded in the example, the __DEBUG_ALLOC__ macro redefines malloc to _debug_malloc. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr; if ( (ptr = malloc(62) ) == NULL) { printf( "Could not allocate memory block.\n" ); return EXIT_FAILURE; } *(ptr - 1) = 'a'; /* overwrites storage that was not allocated */ ptr = malloc(2345); /* this call to malloc invokes _heap_check */ printf("_debug_malloc did not detect that a memory block was overwritten.\n"); return EXIT_FAILURE; /* Possible output is: Memory was overwritten before the allocated memory block that starts at address 0x00150010. The first eight bytes of the memory block (in hex) are: 0000000000000000. This memory block was (re)allocated at line number 11 in TDMALLC.C. */ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _dump_allocated - Get Information about Allocated Storage o _heap_check - Validate Run-Time Storage Heap o malloc - Reserve Storage Block o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.45. _debug_realloc - Change Reserved Storage Block Size ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void *_debug_realloc(void *ptr, size_t size, const char *pFilename, size_t linenum); ═══ Description ═══ Language Level: Extension The _debug_realloc function is the debug version of realloc, and performs the same function as realloc. It reallocates the block of storage pointed to by ptr to a new size, specified in bytes. In addition, _debug_realloc makes an implicit call to the _heap_check function. It also stores the file name pFilename and the line number linenum where the storage is reallocated. This information can be used later by _heap_check and the _dump_allocated function. If ptr is NULL, _debug_realloc behaves like _debug_malloc. Note: The _debug_realloc function reallocates storage that has been allocated by either a normal or a debug version of the memory management functions. If the block of storage pointed to by ptr was not allocated using the memory management functions or was previously freed, a message will appear and the program will end. The _debug_realloc function returns a pointer to the reallocated storage block. The ptr argument to _debug_realloc is not necessarily the same as the return value, because the storage location might be moved by _debug_realloc. If size is 0, _debug_realloc returns NULL. If not enough storage space is available to expand the block to the given size, the original block is unchanged and NULL is returned. Example of _debug_realloc ═══ Example of _debug_realloc ═══ /************************************************************************ * This example uses _debug_realloc to allocate 62 bytes of storage. It then attempts to write to storage that was not allocated. When _debug_realloc is called again, _heap_check detects the error, generates several messages, and stops the program. Note: Although the function realloc is coded in the example, the __DEBUG_ALLOC__ macro redefines realloc to _debug_realloc. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr; if (( ptr = realloc(NULL, 62) ) == NULL) { printf("Could not allocate memory block.\n"); return EXIT_FAILURE; } *(ptr - 2) = 'a'; /* overwrites storage that was not allocated */ ptr = realloc(ptr, 2345); /* this call to realloc invokes _heap_check */ printf("_debug_realloc did not detect that a memory block was overwritten.\n"); return EXIT_FAILURE; /* Possible output is: Memory was overwritten before the allocated memory block that starts at address 0x00150010. The first eight bytes of the memory block (in hex) are: 0000000000000000. This memory block was (re)allocated at line number 11 in TDRALLC.C. */ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_malloc - Reserve Storage Blocks o _dump_allocated - Get Information about Allocated Storage o _heap_check - Validate Run-Time Storage Heap o realloc - Change Reserved Storage Block Size o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.46. difftime - Compute Time Difference ═══ ═══ Format ═══ #include double difftime(time_t time2, time_t time1); ═══ Description ═══ Language Level: ANSI, SAA The difftime function computes the difference in seconds between time2 and time1. The difftime function returns the elapsed time in seconds from time1 to time2 as a double precision number. Type time_t is defined in . Example of difftime ═══ Example of difftime ═══ /************************************************************************ * This example shows a timing application using difftime. The example calculates how long, on average, it takes to find the prime numbers from 2 to 10000. * ************************************************************************/ #include #include #define RUNS 1000 #define SIZE 10000 int mark[SIZE]; int main(void) { time_t start, finish; int i, loop, n, num; time(&start); /* This loop finds the prime numbers between 2 and SIZE */ for (loop = 0; loop < RUNS; ++loop) { for (n = 0; n < SIZE; ++n) mark [n] = 0; /* This loops marks all the composite numbers with -1 */ for (num = 0, n = 2; n < SIZE; ++n) if ( ! mark[n]) { for (i = 2 * n; i < SIZE; i += n) mark[i] = -1; ++num; } } time(&finish); printf("Program takes an average of %f seconds " "to find %d primes.\n", difftime(finish,start)/RUNS, num); } /******************** Output should be similar: ***************** The program takes an average of 0.106000 seconds to find 1229 primes. */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o strftime - Convert to Formatted Time o time - Determine Current Time o time.h ═══ 6.47. _disable - Disable Interrupts ═══ ═══ Format ═══ #include void _disable( void ); ═══ Description ═══ Language Level: Extension The _disable function disables interrupts by executing the CLI machine instruction. It disables interrupts until the instruction after a call to _enable has been executed. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _disable. o You cannot parenthesize a _disable function call, because parentheses specify a call to the backing code for the function in the library. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. This function has no return value. Example of _disable ═══ Example of _disable ═══ /************************************************************************ * In this example, the _disable function disables interrupts by executing a CLI instruction. * ************************************************************************/ #include int main(void) { /* ------------------------------------------------------ */ /* The expected assembler instruction looks like this : */ /* CLI */ /* -------------------------------------------------------*/ _disable(); return 0; } ═══ Related Information ═══ o _enable - Enable Interrupts o _interrupt - Call Interrupt Procedure ═══ 6.48. div - Calculate Quotient and Remainder ═══ ═══ Format ═══ #include div_t div(int numerator, int denominator); ═══ Description ═══ Language Level: ANSI, SAA The div function calculates the quotient and remainder of the division of numerator by denominator. The div function returns a structure of type div_t, containing both the quotient int quot and the remainder int rem. If the return value cannot be represented, its value is undefined. If denominator is 0, an exception will be raised. Example of div ═══ Example of div ═══ /************************************************************************ * This example uses the div function to calculate the quotients and remainders for a set of two dividends and two divisors. * ************************************************************************/ #include #include int main(void) { int num[2] = {45,-45}; int den[2] = {7,-7}; div_t ans; /* div_t is a struct type containing two ints: 'quot' stores quotient; 'rem' stores remainder */ short i,j; printf("Results of division:\n"); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) { ans = div(num[i],den[j]); printf("Dividend: %6ld Divisor: %6ld", num[i], den[j]); printf(" Quotient: %6ld Remainder: %6ld\n", ans.quot, ans.rem); } } /***************** Output should be similar to: ***************** Results of division: Dividend: 45 Divisor: 7 Quotient: 6 Remainder: 3 Dividend: 45 Divisor: -7 Quotient: -6 Remainder: 3 Dividend: -45 Divisor: 7 Quotient: -6 Remainder: -3 Dividend: -45 Divisor: -7 Quotient: 6 Remainder: -3 */ ═══ Related Information ═══ o ldiv - Long Division o stdlib.h ═══ 6.49. _DLL_InitTerm - Initialize and Terminate DLL Environment ═══ ═══ Format ═══ unsigned long _System _DLL_InitTerm(unsigned long modhandle, unsigned long flag); ═══ Description ═══ Language Level: Extension The initialization and termination entry point for a DLL is the _DLL_InitTerm function. When each new process gains access to the DLL, this function initializes the necessary environment for the DLL, including storage, semaphores, and variables. When each process frees its access to the DLL, the _DLL_InitTerm function terminates the DLL environment created for that process. The default _DLL_InitTerm function supplied by the C/C++ Tools compiler performs the actions required to initialize and terminate the runtime environment. It is called automatically when you link to the DLL. If your DLL requires initialization or termination actions in addition to the actions performed for the runtime environment, you will need to create your own _DLL_InitTerm function. If the value of the flag parameter is 0, the DLL environment is initialized. If the value of the flag parameter is 1, the DLL environment is ended. The modhandle parameter is the module handle assigned by the operating system for this DLL. The module handle can be used as a parameter to various OS/2 API calls. For example, DosQueryModuleName can be used to return the fully qualified path name of the DLL, which tells you where the DLL was loaded from. The return code from _DLL_InitTerm tells the loader if the initialization or termination was performed successfully. If the call was successful, _DLL_InitTerm returns a nonzero value. A return code of 0 indicates that the function failed. If a failure is indicated, the loader will not load the program that is accessing the DLL. Because it is called by the operating system loader, the _DLL_InitTerm function must be compiled using _System linkage. Note: A _DLL_InitTerm function for a subsystem DLL has the same prototype, but the content of the function is different because there is no runtime environment to initialize or terminate. Example of _DLL_InitTerm Example of _DLL_InitTerm for a Subsystem ═══ Example of _DLL_InitTerm ═══ /************************************************************************ * The following example shows the _DLL_InitTerm function from the SAMPLE03 program that is shipped with the C/C++ Tools product. * ************************************************************************/ #define INCL_DOSMODULEMGR #define INCL_DOSPROCESS #include #include #include #include /* _CRT_init is the C run-time environment initialization function. */ /* It will return 0 to indicate success and -1 to indicate failure. */ int _CRT_init(void); #ifdef STATIC_LINK /* _CRT_term is the C run-time environment termination function. */ /* It only needs to be called when the C run-time functions are statically */ /* linked. */ void _CRT_term(void); #else /* A clean up routine registered with DosExitList must be used if runtime */ /* calls are required and the runtime is dynamically linked. This will */ /* guarantee that this clean up routine is run before the library DLL is */ /* terminated. */ static void _System cleanup(ULONG ulReason); #endif size_t nSize; int *pArray; /* _DLL_InitTerm is the function that gets called by the operating system */ /* loader when it loads and frees this DLL for each process that accesses */ /* this DLL. However, it only gets called the first time the DLL is loaded */ /* and the last time it is freed for a particular process. The system */ /* linkage convention MUST be used because the operating system loader is */ /* calling this function. */ unsigned long _System _DLL_InitTerm(unsigned long hModule, unsigned long ulFlag) { size_t i; APIRET rc; char namebuf[CCHMAXPATH]; /* If ulFlag is zero then the DLL is being loaded so initialization should*/ /* be performed. If ulFlag is 1 then the DLL is being freed so */ /* termination should be performed. */ switch (ulFlag) { case 0 : /*******************************************************************/ /* The C run-time environment initialization function must be */ /* called before any calls to C run-time functions that are not */ /* inlined. */ /*******************************************************************/ if (_CRT_init() == -1) return 0UL; #ifndef STATIC_LINK /*******************************************************************/ /* A DosExitList routine must be used to clean up if runtime calls */ /* are required and the runtime is dynamically linked. */ /*******************************************************************/ if (rc = DosExitList(0x0000FF00|EXLST_ADD, cleanup)) printf("DosExitList returned %lu\n", rc); #endif if (rc = DosQueryModuleName(hModule, CCHMAXPATH, namebuf)) printf("DosQueryModuleName returned %lu\n", rc); else printf("The name of this DLL is %s\n", namebuf); srand(17); nSize = (rand()%128)+32; printf("The array size for this process is %u\n", nSize); if ((pArray = malloc(nSize *sizeof(int))) == NULL) { printf("Could not allocate space for unsorted array.\n"); return 0UL; } for (i = 0; i < nSize; ++i) pArray[i] = rand(); break; case 1 : #ifdef STATIC_LINK printf("The array will now be freed.\n"); free(pArray); _CRT_term(); #endif break; default : printf("ulFlag = %lu\n", ulFlag); return 0UL; } /* A non-zero value must be returned to indicate success. */ return 1UL; } #ifndef STATIC_LINK static void cleanup(ULONG ulReason) { if (!ulReason) { printf("The array will now be freed.\n"); free(pArray); } DosExitList(EXLST_EXIT, cleanup); return ; } #endif ═══ Example of _DLL_InitTerm for a Subsystem ═══ /************************************************************************ * The following example shows the _DLL_InitTerm function from the SAMPLE05 program that is shipped with the C/C++ Tools product. * ************************************************************************/ /* _DLL_InitTerm() - called by the loader for DLL initialization/termination */ /* This function must return a non-zero value if successful and a zero value */ /* if unsuccessful. */ unsigned long _DLL_InitTerm( unsigned long hModule, unsigned long ulFlag ) { APIRET rc; /* If ulFlag is zero then initialization is required: */ /* If the shared memory pointer is NULL then the DLL is being loaded */ /* for the first time so acquire the named shared storage for the */ /* process control structures. A linked list of process control */ /* structures will be maintained. Each time a new process loads this */ /* DLL, a new process control structure is created and it is inserted */ /* at the end of the list by calling DLLREGISTER. */ /* */ /* If ulFlag is 1 then termination is required: */ /* Call DLLDEREGISTER which will remove the process control structure */ /* and free the shared memory block from its virtual address space. */ switch( ulFlag ) { case 0: if ( !ulProcessCount ) { /* Create the shared mutex semaphore. */ if ( ( rc = DosCreateMutexSem( SHARED_SEMAPHORE_NAME, &hmtxSharedSem, 0, FALSE ) ) != NO_ERROR ) { printf( "DosCreateMutexSem rc = %lu\n", rc ); return 0; } } /* Register the current process. */ if ( DLLREGISTER( ) ) return 0; break; case 1: /* De-register the current process. */ if ( DLLDEREGISTER( ) ) return 0; break; default: return 0; } /* Indicate success. Non-zero means success!!! */ return 1; } ═══ Related Information ═══ o _CRT_init - Initialize DLL Runtime Environment o _CRT_term - Terminate DLL Runtime Environment ═══ 6.50. _dump_allocated - Get Information about Allocated Storage ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void _dump_allocated(int nbytes); ═══ Description ═══ Language Level: Extension The _dump_allocated function prints out information about each memory block that is currently allocated, if it was allocated by the debug versions of the memory management functions. The nbytes argument specifies how many bytes of each memory block are to be printed. If nbytes is a negative value, all the bytes of each memory block are printed. If nbytes is 0, no bytes are printed. If nbytes is a positive value, the number of bytes printed for each block will be the minimum of the requested size and the block size. Note: You should call the _dump_allocated function at a point in your code where you would like a report of the currently allocated memory. For example, a good place to call _dump_allocated is a point where most of the memory is already freed and you want to find a memory leak, such as the end of a program. Example of _dump_allocated ═══ Example of _dump_allocated ═══ /************************************************************************ * This example allocates three memory blocks, and then calls _dump_allocated to dump information and the first 8 bytes for each memory block. * ************************************************************************/ rules=none. #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include #include #define INIT_STR "It\0works" #define INIT_STR_LEN (sizeof(INIT_STR) - 1) int main(void) { char *pBlock1; char *pBlock2; char *pBlock3; if (( pBlock1 = malloc(35) ) == NULL) /* allocate first memory block */ { printf( "Could not allocate first memory block.\n" ); return EXIT_FAILURE; } memcpy(pBlock1, INIT_STR, INIT_STR_LEN); /* initialize first memory block */ if (( pBlock2 = calloc(2, 120) ) == NULL) /* allocate second memory block */ { printf( "Could not allocate second memory block.\n" ); return EXIT_FAILURE; } memcpy(pBlock2, INIT_STR, INIT_STR_LEN); /* initialize second memory block */ if (( pBlock3 = realloc(NULL, 2235) ) == NULL) /* allocate third memory block */ { printf( "Could not allocate third memory block.\n" ); return EXIT_FAILURE; } memcpy(pBlock3, INIT_STR, INIT_STR_LEN); /* initialize third memory block */ if (( pBlock3 = realloc(pBlock3, 300) ) == NULL) /* reallocate third memory */ /* block to different size */ { printf("Could not reallocate third memory block.\n"); return EXIT_FAILURE; } _dump_allocated(8); /* show first eight bytes of each memory block */ return 0; /* Possible output is: ============================================================================ START OF DUMP OF ALLOCATED MEMORY BLOCKS ============================================================================ Address: 0x00180010 Size: 0x0000012C (300) This memory block was (re)allocated at line number 41 in TDMPAL.C. Memory contents: 49740077 6F726B73 {It.works } ============================================================================ Address: 0x00170010 Size: 0x000000F0 (240) This memory block was (re)allocated at line number 25 in TDMPAL.C. Memory contents: 49740077 6F726B73 {It.works } ============================================================================ Address: 0x00150010 Size: 0x00000023 (35) This memory block was (re)allocated at line number 17 in TDMPAL.C. Memory contents: 49740077 6F726B73 {It.works } ============================================================================ END OF DUMP OF ALLOCATED MEMORY BLOCKS ============================================================================ */ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_malloc - Reserve Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _heap_check - Validate Run-Time Storage Heap o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.51. _dup -Associate Second Handle with Open File ═══ ═══ Format ═══ #include int _dup(int handle); ═══ Description ═══ Language Level: Extension The _dup function associates a second file handle with a currently open file. You can carry out operations on the file using either file handle because all handles associated with a given file use the same file pointer. Creation of a new handle does not affect the type of access allowed for the file. For example, given: handle2 = _dup(handle1) handle2 will have the same file access mode (text or binary) as handle1. In addition, if handle1 was originally opened with the O_APPEND flag (described in _open - Open File), handle2 will also have that attribute. Warning: Both handles share a single file pointer. Therefore, if you reposition a file using handle1, the position in the file returned by handle2 will also change. If you duplicate a file handle for an open stream, the resulting file handle has the same restrictions as the original file handle. The _dup function returns the next available file handle for the given file. The _dup function returns a new file handle. It returns -1 if an error occurs and sets errno to one of the following values: Value Meaning EBADF The file handle is not valid. EMFILE No more file handles are available. EOS2ERR The call to the operating system was not successful. Example of _dup ═══ Example of _dup ═══ /************************************************************************ * This example makes a second file handle, fh3, refer to the same file as the file handle fh1 using _dup. The file handle fh2 is then associated with the file edopen.da2, and finally fh2 is forced to associate with edopen.da1 by the _dup2 function. * ************************************************************************/ #include #include #include #include int main(void) { int fh1, fh2, fh3; if ( -1 == (fh1 = _open("edopen.da1", O_CREAT | O_TRUNC | O_RDWR , S_IREAD | S_IWRITE))) { perror("Unable to open edopen.da1"); return 1; } /* fh3 refers to the sample file as fh1 */ if (-1 == (fh3 = _dup(fh1))) { perror("Unable to dup"); _close(fh1); return 1; } else printf("Successfully performed dup handle.\n"); if ( -1 == (fh2 = _open("edopen.da2", O_CREAT | O_TRUNC | O_RDWR , S_IREAD | S_IWRITE))) { perror("Unable to open edopen.da2"); _close(fh1); _close(fh3); return 1; } if (-1 == _dup2(fh1,fh2)) /* Force fh2 to the refer to the same file */ { /* as fh1. */ perror("Unable to dup2"); } else printf("Successfully performed dup2 handle.\n"); _close(fh1); _close(fh2); _close(fh3); return 0; /****************** The expected output is: *************************** Successfully performed dup handle. Successfully performed dup2 handle. */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _creat - Create New File o _dup2 -Associate Second Handle with Open File o _open - Open File o _sopen - Open Shared File o io.h ═══ 6.52. _dup2 -Associate Second Handle with Open File ═══ ═══ Format ═══ #include int _dup2(int handle1, int handle2); ═══ Description ═══ Language Level: Extension The _dup2 function associates a second file handle with a currently open file. You can carry out operations on the file using either file handle because all handles associated with a given file use the same file pointer. The handle handle2 will point to the same file as handle1, but will retain the file access mode (text or binary) that it had before duplication. In addition, if handle2 was originally opened with the O_APPEND flag, it will also retain that attribute. Warning: Both handles share a single file position. Therefore, if you reposition a file using handle1, the position in the file returned by handle2 will also change. If you duplicate a file handle for an open stream (using fileno), the resulting file handle has the same restrictions as the original file handle. The _dup2 function forces the given handle, handle2, to refer to the same file as handle1. If handle2 is associated with an open file at the time of the call, that file is closed. The _dup2 function returns 0 to indicate success. It returns -1 if an error occurs and sets errno to one of the following values: Value Meaning EBADF The file handle is not valid. EMFILE No more file handles are available. EOS2ERR The call to the operating system was not successful. Example of _dup2 ═══ Example of _dup2 ═══ /************************************************************************ * This example makes a second file handle, fh3, refer to the same file as the file handle fh1 using _dup. The file handle fh2 is then associated with the file edopen.da2, and finally fh2 is forced to associate with edopen.da1 by the _dup2 function. * ************************************************************************/ #include #include #include #include int main(void) { int fh1, fh2, fh3; if ( -1 == (fh1 = _open("edopen.da1", O_CREAT | O_TRUNC | O_RDWR , S_IREAD | S_IWRITE))) { perror("Unable to open edopen.da1"); return 1; } /* fh3 refers to the sample file as fh1 */ if (-1 == (fh3 = _dup(fh1))) { perror("Unable to dup"); _close(fh1); return 1; } else printf("Successfully performed dup handle.\n"); if ( -1 == (fh2 = _open("edopen.da2", O_CREAT | O_TRUNC | O_RDWR , S_IREAD | S_IWRITE))) { perror("Unable to open edopen.da2"); _close(fh1); _close(fh3); return 1; } if (-1 == _dup2(fh1,fh2)) /* Force fh2 to the refer to the same file */ { /* as fh1. */ perror("Unable to dup2"); } else printf("Successfully performed dup2 handle.\n"); _close(fh1); _close(fh2); _close(fh3); return 0; /****************** The expected output is: *************************** Successfully performed dup handle. Successfully performed dup2 handle. */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _creat - Create New File o _dup -Associate Second Handle with Open File o _open - Open File o _sopen - Open Shared File o io.h ═══ 6.53. _ecvt - Convert Floating-Point to Character ═══ ═══ Format ═══ #include char *_ecvt(double value, int ndigits, int *decptr, int *signptr); ═══ Description ═══ Language Level: Extension The _ecvt function converts a floating-point number to a character string. The variable value is the floating-point number to be converted. The _ecvt function stores ndigits digits of value as a string and adds a null character (\0). If the number of digits in value exceeds ndigits, the low-order digit is rounded. If there are fewer than ndigits digits, the string is padded with zeros. Only digits are stored in the string. You can obtain the position of the decimal point and the sign of value after the call from decptr and signptr. The variable decptr points to an integer value that gives the position of the decimal point with respect to the beginning of the string. A 0 or a negative integer value indicates that the decimal point lies to the left of the first digit. The variable signptr points to an integer that indicates the sign of the converted number. If the integer value is 0, the number is positive. If it is not 0, the number is negative. The _ecvt function also converts NaN and infinity values to the strings NAN and INFINITY, respectively. For more information on NaN and infinity values, see Infinity and NaN Support. Warning: For each thread, the _ecvt, _fcvt and _gcvt functions use a single, dynamically allocated buffer for the conversion. Any subsequent call that the same thread makes to these functions destroys the result of the previous call. The _ecvt function returns a pointer to the string of digits. A failure to allocate memory results in a NULL return value, and errno is set to ENOMEM. Because of the limited precision of the double type, no more than 16 decimal digits are significant in any conversion. Example of _ecvt ═══ Example of _ecvt ═══ /************************************************************************ * This example reads in two floating-point numbers, calculates their product, and prints out only the billions digit of its character representation. At most, 16 decimal digits of significance can be expected. The output assumes the user enters the numbers 1000000 and 3000. * ************************************************************************/ #include #include #include int main(void) { float x, y; double z; int w, b, decimal, sign; char *buffer; printf("Enter two floating-point numbers:\n"); if ( scanf("%e %e", &x, 0x) != 2 ) { printf("input error...\n"); exit(-1); } z = x*y; printf("Their product is %g\n", z); w = log10( fabs(z) ) + 1.; buffer = _ecvt(z, w, &decimal, signed); b = decimal - 10; if (b < 0) printf("Their product does not exceed one billion.\n"); else if (b > 15) printf("The billions digit of their product is insignificant.\n"); else printf("The billions digit of their product is %c.\n", buffer[b]); return 0; /***** The expected output on input of 1000000 3000 is ************** Enter two floating point numbers: 1000000 3000 Their product is 3e+09 the billions digit of their product is 3. */ } ═══ Related Information ═══ o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o Infinity and NaN Support o stdlib.h ═══ 6.54. _enable - Enable Interrupts ═══ ═══ Format ═══ #include /* also defined in */ void _enable( void ); ═══ Description ═══ Language Level: Extension The _enable function enables interrupts by generating the STI machine instruction. Interrupts are enabled after the instruction following STI has been executed. If interrupts are disabled and you call _enable followed immediately by a call to _disable, interrupts remain disabled. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _enable. o You cannot parenthesize an _enable function call because parentheses specify a call to the backing code for the function in the library. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception will be generated. There is no return value. Example of _enable ═══ Example of _enable ═══ /************************************************************************ * In this example, the _enable function enables interrupts by executing an STI instruction. * ************************************************************************/ #include int main(void) { /* ------------------------------------------------------ */ /* The expected assembler instruction looks like this : */ /* STI */ /* ------------------------------------------------------ */ _enable(); return 0; } ═══ Related Information ═══ o _disable - Disable Interrupts o _interrupt - Call Interrupt Procedure ═══ 6.55. _endthread - Terminate Current Thread ═══ ═══ Format ═══ #include /* also defined in */ void _endthread(void); ═══ Description ═══ Language Level: Extension The _endthread function explicitly ends a thread that you previously created with _beginthread before the thread has completed its function. For example, if some condition is not met, _endthread terminates the thread. When the thread has finished, it automatically ends itself with an implicit call to _endthread. Note: 1. When using the _beginthread and _endthread functions, you must specify the /Gm+ compiler option to use the multithread libraries. 2. If you use DosCreateThread, you must explicitly call _endthread to terminate the thread. There is no return value. Example of _endthread ═══ Example of _endthread ═══ /************************************************************************ * In this example, the main program creates two threads, bonjour and au_revoir. The thread bonjour is forcibly terminated by a call to _endthread, while the au_revoir thread ends itself with an implicit call to _endthread. Note: To run this example, you must compile it using the /Gm+ compile-time option. * ************************************************************************/ #define INCL_DOS #include #include #include #include void bonjour(void *arg) { int i = 0; while ( i++ < 5 ) printf("Bonjour!\n"); _endthread(); /* This thread ends itself explicitly */ puts("thread should terminate before printing this"); } void au_revoir(void *arg) { int i = 0; while ( i++ < 5 ) /* This thread makes an implicit */ printf("Au revoir!\n"); /* call to _endthread */ } int main(void) { unsigned long tid1; unsigned long tid2; tid1 = _beginthread(bonjour, NULL, 8192, NULL); tid2 = _beginthread(au_revoir, NULL, 8192, NULL); if ( (tid1 == -1) || (tid2 == -1) ) { printf("Unable to start threads.\n"); exit(-1); } DosWaitThread( &tid2, DCWW_WAIT ); /* wait until threads 1 and 2 */ DosWaitThread( &tid1, DCWW_WAIT ); /* have been completed */ return 0; /* Possible output could be: Bonjour! Au revoir! Bonjour! Au revoir! Bonjour! Au revoir! Bonjour! Au revoir! Bonjour! Au revoir! */ } ═══ Related Information ═══ o _beginthread - Create New Thread o /Gm+ option. o stdlib.h o process.h ═══ 6.56. __eof - Determine End of File ═══ ═══ Format ═══ #include int __eof (int handle); ═══ Description ═══ Language Level: Extension The __eof function determines whether the file pointer has reached the end-of-file for the file associated with handle. You cannot use __eof on a nonseekable file; it will fail. The __eof function returns the value 1 if the current position is the end of the file or 0 if it is not. A return value of -1 shows an error, and the system sets errno to the following values: Value Meaning EBADF File handle is not valid. EOS2ERR The call to the operating system was not successful. Example of __eof ═══ Example of __eof ═══ /************************************************************************ * This example creates the file sample.dat and then checks if the file pointer is at the end of that file using the __eof function: * ************************************************************************/ #include #include #include int main(void) { int fh, returnValue; fh = _creat("sample.dat", S_IREAD | S_IWRITE); if ( -1 == fh) { perror("Error creating sample.dat"); return 1; } if ( -1 == (returnValue = __eof(fh))) { perror("eof function error"); return 1; } if (returnValue == 1) printf("File pointer is at end-of-file position.\n"); else printf("File pointer is not at end-of-file position.\n"); _close(fh); return 0; /**************** The expected output is: ***************************** File pointer is at end-of-file position. */ } ═══ Related Information ═══ o _chsize - Alter Length of File o _creat - Create New File o _filelength - Determine File Length o _sopen - Open Shared File o _open - Open File o io.h ═══ 6.57. erf - Calculate Error Functions ═══ ═══ Format ═══ #include /* SAA extensions to ANSI */ double erf(double x); double erfc(double x); ═══ Description ═══ Language Level: SAA The erf function calculates the error function. The erfc function returns the value of 1.0 - erf(x);. The erfc function is used in place of erf for large values of x. Example of erf - erfc ═══ Example of erf - erfc ═══ /************************************************************************ * This example uses erf to compute the error function of two numbers. * ************************************************************************/ #include #include double smallx, largex, value; int main(void) { smallx = 0.1; largex = 10.0; value = erf(smallx); /* value = 0.112463 */ printf("Error value for 0.1: %lf\n", value); value = erfc(largex); /* value = 2.088488e-45 */ printf("Error value for 10.0: %le\n", value); } /***************** Output should be similar to: ***************** Error value for 0.1: 0.112463 Error value for 10.0: 2.088488e-45 */ ═══ Related Information ═══ o Bessel Functions o math.h o gamma - Gamma Function ═══ 6.58. _execl - _execvp - Load and Run Child Process ═══ ═══ Format ═══ #include int _execl(char *pathname, char *arg0, char *arg1,..., char *argn, NULL); int _execle(char *pathname, char *arg0, char *arg1,..., char *argn, NULL, char *envp[ ]); int _execlp(char *pathname, char *arg0, char *arg1,..., char *argn, NULL); int _execlpe(char *pathname, char *arg0, char *arg1,..., char *argn, NULL, char *envp[ ]); int _execv(char *pathname, char *argv[ ]); int _execve(char *pathname, char *argv[ ],char *envp[ ]); int _execvp(char *pathname, char *argv[ ]); int _execvpe(char *pathname, char *argv[ ], char *envp[ ]); ═══ Description ═══ Language Level: Extension The _exec functions load and run new child processes. The parent process is ended after the child process has started. Sufficient storage must be available for loading and running the child process. All of the _exec functions are versions of the same routine; the letters at the end determine the specific variation: Letter Variation p Uses PATH environment variable to find the file to be run l Passes a list of command line arguments separately v Passes to the child process an array of pointers to command-line arguments e Passes to the child process an array of pointers to environment strings. The pathname argument specifies the file to run as the child process. The pathname can specify a full path from the root, a partial path from the current working directory, or a file name. If pathname does not have a file name extension or does not end with a period, the _exec functions will add the .EXE extension and search for the file. If pathname has an extension, the _exec function uses only that extension. If pathname ends with a period, the _exec functions search for pathname with no extension. The _execlp, _execlpe, _execvp, and _execvpe functions search for the pathname in the directories that the PATH environment variable specifies. You pass arguments to the new process by giving one or more pointers to character strings as arguments in the _exec call. These character strings form the argument list for the child process. The compiler can pass the argument pointers as separate arguments (_execl, _execle, _execlp, and _execlpe) or as an array of pointers (_execv, _execve, _execvp, and _execvpe). You should pass at least one argument, either arg0 or argv[0], to the child process. If you do not, an argument will be returned that points to the same file as the path name argument you specified. This argument may not be exactly identical to the path name argument you specified. A different value does not produce an error. Use the _execl, _execle, _execlp, and _execlpe functions for the cases where you know the number of arguments in advance. The arg0 argument is usually a pointer to pathname. The arg1 through argn arguments are pointers to the character strings forming the new argument list. There must be a NULL pointer following argn to mark the end of the argument list. Use the _execv, _execve, _execvp, and _execvpe functions when the number of arguments to the new process is variable. Pass pointers to the arguments of these functions as an array, argv[ ]. The argv[0] argument is usually a pointer to pathname. The argv[1] through argv[n] arguments are pointers to the character strings forming the new argument list. If argv[n] is the last parameter, then argv[n+1] must be NULL. Files that are open when you make an _exec call remain open in the new process. In the _execl, _execlp, _execv, and _execvp calls, the child process receives the environment of the parent. The _execle, _execlpe, _execve, and _execvpe functions let you change the environment for the child process by passing a list of environment settings through the envp argument. The envp argument is an array of character pointers, each element of which points to a string ending with a null character that defines an environment variable. Such a string usually has the following form: NAME=value where NAME is the name of an environment variable, and value is the string value to which the _exec function sets that variable. Note: Do not enclose the value in double quotation marks. The final element of the envp array should be NULL. When envp itself is NULL, the child process receives the environment settings of the parent process. The _exec functions do not preserve signal settings in child processes created by calls to _exec functions. Calls to _exec functions reset the signal settings to the default in the child process. The _exec functions do not normally return control to the calling process. They are equivalent to the corresponding _spawn functions with P_OVERLAY as the value of modeflag. If an error occurs, the _exec functions return -1 and set errno to one of the following values: Value Meaning EACCESS The specified file has a locking or sharing violation. EMFILE There are too many open files. The system must open the specified file to tell whether it is an executable file. ENOENT The file or pathname was not found or was specified incorrectly. ENOEXEC The specified file cannot run or has an incorrect executable file format. ENOMEM One of the following conditions exists: o Not enough storage is available to run the child process. o Not enough storage is available for the argument or environment strings. Example of _execl - execvp ═══ Example of _execl - execvp ═══ /************************************************************************ * This example calls four of the eight _exec routines. When invoked without arguments, the program first runs the code for case PARENT. It then calls _execle() to load and run a copy of itself. The instructions for the child are blocked to run only if argv[0] and one parameter were passed (case CHILD). In its turn, the child runs its own child as a copy of the same program. This sequence is continued until four generations of child processes have run. Each of the processes prints a message identifying itself. * ************************************************************************/ #include #include #include #define PARENT 1 #define CHILD 2 char *args[3]; int main(int argc, char **argv, char **envp) { switch(argc) { case PARENT: /* No argument: run a child */ { printf("Parent process began.\n"); _execle(argv[0],argv[0],"1",NULL,envp); abort(); /* Not executed because parent was overlaid. */ } case CHILD: /* One argument: run a child's child */ { printf("Child process %s began.\n", argv[1]); if('1'==*argv[1]) /* generation one */ { _execl(argv[0],argv[0],"2",NULL); abort(); /* Not executed because child was overlaid */ } if('2'==*argv[1]) /* generation two */ { args[0]=argv[0]; args[1]="3"; args[2]=NULL; _execv(argv[0],args); abort(); /* Not executed because child was overlaid */ } if('3'==*argv[1]) /* generation three */ { args[0]=argv[0]; args[1]="4"; args[2]=NULL; _execve(argv[0],args,_environ); abort(); /* Not executed because child was overlaid */ } if('4'==*argv[1]) /* generation four */ printf("Child process %s", argv[1]); } } printf(" ended.\n"); _exit(0); return 0; /***************** The output should be similar to: ******************** Parent process began. Child process 1 began. Child process 2 began. Child process 3 began. Child process 4 began. Child process 4 ended. */ } ═══ Related Information ═══ o abort - Stop a Program o _cwait - Wait for Child Process o exit - End Program o _exit - End Process o _spawnl -_spawnvpe -Start and Run Child Processes o system - Invoke the Command Processor o _wait - Wait for Child Process o envp Parameter to main o process.h ═══ 6.59. exit - End Program ═══ ═══ Format ═══ #include /* also defined in */ void exit(int status); ═══ Description ═══ Language Level: ANSI, SAA, Extension The exit function returns control to the host environment from the program. It first calls all functions registered with the atexit function, in reverse order; that is, the last one registered is the first one called. It flushes all buffers and closes all open files before ending the program. The argument status can have a value from 0 to 255 inclusive or be one of the macros EXIT_SUCCESS or EXIT_FAILURE. A status value of EXIT_SUCCESS or 0 indicates a normal exit; otherwise, another status value is returned. All files opened with tmpfile are deleted. The exit function returns both control and the value of status to the operating system. Example of exit ═══ Example of exit ═══ /*********************************************************************** * This example ends the program after flushing buffers and closing any open files if it cannot open the file myfile. * ***********************************************************************/ #include #include FILE *stream; int main(void) { . . . if ((stream = fopen("myfile.dat", "r")) == NULL) { perror("Could not open data file"); exit(EXIT_FAILURE); } } ═══ Related Information ═══ o abort - Stop a Program o atexit - Record Program Termination Function o _onexit - Record Termination Function o _exit - End Process o signal Install Interrupt Handlers o stdlib.h o tmpfile - Create Temporary File ═══ 6.60. _exit - End Process ═══ ═══ Format ═══ #include /* Declared in both */ #include void _exit(int status); ═══ Description ═══ Language Level: Extension The _exit function ends the calling process without calling functions registered by _onexit or atexit. It also does not flush stream buffers or delete temporary files. You supply the status value as a parameter; the value 0 typically means a normal exit. Although _exit does not return a value, the value is available to the waiting parent process, if there is one, after the child process ends. If no parent process waits for the exiting process, the status value is lost. The status value is available through the operating system batch command IF ERRORLEVEL. Example of _exit ═══ Example of _exit ═══ /************************************************************************ * This example calls _exit to end the process. Because _exit does not flush the buffer first, the output from the second printf statement will not appear. * ************************************************************************/ #include #include /* You can also use */ char buf[51]; int main(void) { /* Make sure the standard output stream is line-buffered */ /* even if the output is redirected to a file. */ if (setvbuf( stdout, buf, _IOLBF, 50 ) != 0) printf("The buffering was not set correctly.\n"); printf( "This will print out but ...\n" ); printf( "this will not!" ); _exit( 1 ); return 0; /****************** The output should be similar to: ****************** This will print out but ... */ } ═══ Related Information ═══ o abort - Stop a Program o atexit - Record Program Termination Function o _execl - _execvp - Load and Run Child Process o exit - End Program o _onexit - Record Termination Function o process.h o stdlib.h ═══ 6.61. exp - Exponential Function ═══ ═══ Format ═══ #include double exp(double x); ═══ Description ═══ Language Level: ANSI, SAA The exp function calculates the exponential function of a floating-point argument x (e**x, where e equals 2.17128128...). If an overflow occurs, the function returns HUGE_VAL. If an underflow occurs, it returns 0. Both overflow and underflow set errno to ERANGE. Example of exp ═══ Example of exp ═══ /*********************************************************************** * This example calculates y as the exponential function of x: * ***********************************************************************/ #include #include int main(void) { double x, y; x = 5.0; y = exp(x); printf("exp( %lf ) = %lf\n", x, y); } /***************** Output should be similar to: ***************** exp( 5.000000 ) = 148.413159 */ ═══ Related Information ═══ o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o math.h ═══ 6.62. fabs - Calculate Floating-Point Absolute Value ═══ ═══ Format ═══ #include double fabs(double x); ═══ Description ═══ Language Level: ANSI, SAA The fabs function returns the absolute value of a floating-point argument. There is no error return value. Example of fabs ═══ Example of fabs ═══ /************************************************************************ * This example calculates y as the absolute value of x: * ************************************************************************/ #include #include int main(void) { double x, y; x = -5.6798; y = fabs(x); printf("fabs( %lf ) = %lf\n", x, y); } /******************* Output should be similar to: *************** fabs( -5.679800 ) = 5.679800 */ ═══ Related Information ═══ o abs - Calculate Integer Absolute Value o _cabs - Calculate Absolute Value of Complex Number o labs - Calculate long Absolute Value o math.h ═══ 6.63. _facos - Calculate Arccosine ═══ ═══ Format ═══ #include double _facos(double x); ═══ Description ═══ Language Level: Extension The _facos function calculates the arccosine of x. This function causes the compiler to emit the appropriate 80387 instructions for the calculation of the arccosine. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _facos. o You cannot parenthesize a _facos function call, because parentheses specify a call to the backing code for the function. This function returns the arccosine of a variable x. Example of _facos ═══ Example of _facos ═══ /************************************************************************ * This example prompts for a value for x. It prints an error message if x is greater than 1 or less than -1. Otherwise, it assigns the arccosine of x to y. * ************************************************************************/ #include #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x, y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for acos\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for acos\n", x ); else { y = _facos( x ); printf( "The cossine of %lf is %lf.\n", x, y ); } } ═══ Related Information ═══ o acos - Calculate Arccosine o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine ═══ 6.64. _fasin - Calculate Arcsine ═══ ═══ Format ═══ #include double _fasin(double x); ═══ Description ═══ Language Level: Extension The _fasin function calculates the arcsine of x. This function causes the compiler to emit the appropriate 80387 instructions for the calculation of arcsine. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fasin. o You cannot parenthesize a _fasin function call, because parentheses specify a call to the backing code for the function. This function returns the arcsine of a variable x. Example of _fasin ═══ Example of _fasin ═══ /************************************************************************ * This example prompts for a value of x. It prints an error message if x is greater than 1 or less than -1. Otherwise, it assigns the arcsine of x to y. * ************************************************************************/ #include #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x, y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for _fasin\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for _fasin\n", x ); else { y = _fasin( x ); printf( "The arcsine of %lf is %lf.\n", x, y ); } } ═══ Related Information ═══ o asin - Calculate Arcsine o _fcossin - Calculate Cosine and Sine o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine ═══ 6.65. fclose - Close Stream ═══ ═══ Format ═══ #include int fclose(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fclose function closes a stream pointed to by stream. This function flushes all buffers associated with the stream before closing it. When it closes the stream, the function releases any buffers that the system reserved. The fclose function returns 0 if it successfully closes the stream, or EOF if any errors were detected. Note: Once a stream has been closed with fclose, it must be opened again before it can be used. Example of fclose ═══ Example of fclose ═══ /************************************************************************ * This example opens a file myfile for reading as a stream; then it closes this file. * ************************************************************************/ #include int main(void) { FILE *stream; stream = fopen("myfile.dat", "r"); if (fclose(stream)) /* Close the stream. */ perror("fclose error"); } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _fcloseall - Close All Open Streams o fflush - Write Buffer to File o fopen - Open Files o freopen - Redirect Open Files o stdio.h ═══ 6.66. _fcloseall - Close All Open Streams ═══ ═══ Format ═══ #include int _fcloseall(void); ═══ Description ═══ Language Level: Extension The _fcloseall function closes all open streams, except stdin, stdout, and stderr. It also closes and deletes any temporary files created by tmpfile. The function flushes all buffers associated with the streams before closing them. When it closes streams, it releases the buffers that the system reserved, but does not release user-allocated buffers. The _fcloseall function returns the total number of streams closed, or EOF if an error occurs. Example of _fcloseall ═══ Example of _fcloseall ═══ /************************************************************************ * This example opens a file john for reading as a data stream, and then closes the file. It closes all other streams except stdin, stdout, and stderr. * ************************************************************************/ #include int main(void) { FILE *stream; int numclosed; stream = fopen("john", "w"); numclosed = _fcloseall(); printf("Number of files closed = %d\n", numclosed); return 0; /* The expected output is: Number of files closed = 1 */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o fclose - Close Stream o fflush - Write Buffer to File o fopen - Open Files o freopen - Redirect Open Files o tmpfile - Create Temporary File o stdio.h ═══ 6.67. _fcos - Calculate Cosine ═══ ═══ Format ═══ #include double _fcos( double x); ═══ Description ═══ Language Level: Extension The _fcos function calculates the cosine of x, where x is expressed in radians. The value of x must be less than 2**63. This function causes the compiler to emit the FSINCOS 80387 instruction and return only the cosine. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fcos. o You cannot parenthesize a _fcos function call, because parentheses specify a call to the backing code for the function in the library. This function returns the cosine of a variable x expressed in radians. Example of _fcos ═══ Example of _fcos ═══ /************************************************************************ * This example calculates y to be the cosine of x. * ************************************************************************/ #include #include #include int main(void) { double x, y; x = 7.2; y = _fcos(x); printf("The cosine of %lf is %lf.\n", x, y); } ═══ Related Information ═══ o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _facos - Calculate Arccosine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine ═══ 6.68. _fcossin - Calculate Cosine and Sine ═══ ═══ Format ═══ #include double _fcossin(double x, double *y); ═══ Description ═══ Language Level: Extension The _fcossin function calculates the cosine of x, and stores the sine of x in *y. This is faster than separately calculating the sine and cosine. Use this function instead of _fsincos when you will be using the cosine first, and then the sine. This function causes the compiler to emit the FSINCOS 80387 instruction. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fcossin. o You cannot parenthesize a _fcossin function call, because parentheses specify a call to the backing code for the function in the library. This function returns the cosine of a variable x. Example of _fcossin ═══ Example of _fcossin ═══ /************************************************************************ * This example calculates the cosine of x and stores the sine of x in y. * ************************************************************************/ #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x,y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for _facos\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for _facos\n", x ); else { z = _fcossin( x, *y); printf("The cosine of %d is %lf\n", x, z); printf("The sine of %d is %lf\n", x, *y); } } ═══ Related Information ═══ o acos - Calculate Arccosine o asin - Calculate Arcsine o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _facos - Calculate Arccosine o _fasin - Calculate Arcsine o _fcos - Calculate Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine ═══ 6.69. _fcvt - Convert Floating-Point to String ═══ ═══ Format ═══ #include char *_fcvt(double value, int ndec, int *decptr, int *signptr); ═══ Description ═══ Language Level: Extension The _fcvt function converts a floating-point number to a character string. The variable value is the floating-point number to be converted. The _fcvt function stores the digits of value as a string and adds a null character (\0). The ndec variable specifies the number of digits to be stored after the decimal point. If the number of digits after the decimal point in value exceeds ndec, _fcvt rounds the correct digit according to the FORTRAN F format. If there are fewer than ndec digits of precision, _fcvt pads the string with zeros. A FORTRAN F number has the following format: ┌───────┐ ┌─────────┐ ──┬─────┬──digit─┴───.───┬───────┬┴────── ├──+──┤ └─digit─┘ └──-──┘ The _fcvt function stores only digits in the string. You can obtain the position of the decimal point and the sign of value after the call from decptr and signptr. The decptr variable points to an integer value giving the position of the decimal point with respect to the beginning of the string. A 0 or negative integer value shows that the decimal point lies to the left of the first digit. The signptr variable points to an integer showing the sign of value. The _fcvt function sets the integer to 0 if value is positive and to a nonzero number if value is negative. The _fcvt function also converts NaN and infinity values to the strings NAN and INFINITY, respectively. For more information on NaN and infinity values, see Infinity and NaN Support. Warning: For each thread, the _ecvt, _fcvt, and _gcvt functions use a single, dynamically allocated buffer for the conversion. Any subsequent call that the same thread makes to these functions destroys the result of the previous call. The _fcvt function returns a pointer to the string of digits. A failure to allocate memory results in a NULL return value and sets errno to ENOMEM. Because of the limited precision of the double type, no more than 16 decimal digits are significant in any conversion. Example of _fcvt ═══ Example of _fcvt ═══ /************************************************************************ * This example reads in two floating-point numbers, computes their product, and prints out only the billions digit of its character representation. At most, 16 decimal digits of significance can be expected. The output given assumes the user enters the values 2000000 and 3000. * ************************************************************************/ #include #include #include int main(void) { float x, y; double z int w, b, decimal, sign; char *buffer; printf("Enter two floating-point numbers:\n"); if ( scanf("%e %e", &x, 0x) != 2 ) { printf("input error...\n"); exit(-1); } z = x*y; printf("Their product is %g\n", z); w = log10( fabs(z) ) + 1.; buffer = _fcvt(z, w, &decimal, signed); b = decimal - 10; if (b < 0) printf("Their product does not exceed one billion.\n"); else if (b > 15) printf("The billions digit of their product is insignificant.\"); else printf("The billions digit of their product is %c.\n", buffer[b]); return 0; /***** The expected output on input of 2000000 3000 is ************** Enter two floating point numbers: 2000000 3000 Their product is 6e+09 the billions digit of their product is 6. */ } ═══ Related Information ═══ o _ecvt - Convert Floating-Point to Character o _gcvt - Convert Floating-Point to String o Infinity and NaN Support o stdlib.h ═══ 6.70. _fdopen - Associates Input Or Output With File ═══ ═══ Format ═══ #include FILE *_fdopen(int handle, char *type); ═══ Description ═══ Language Level: Extension The _fdopen function associates an input or output stream with the file identified by handle. The type variable is a character string specifying the type of access requested for the stream. Mode Description r Create a stream to read a text file. The file pointer is set to the beginning of the file. w Create a stream to write to a text file. The file pointer is set to the beginning of the file. a Create a stream to write, in append mode, at the end of the text file. The file pointer is set to the end of the file. r+ Create a stream for reading and writing a text file. The file pointer is set to the beginning of the file. w+ Create a stream for reading and writing a text file. The file pointer is set to the beginning of the file. a+ Create a stream for reading or writing, in append mode, at the end of the text file. The file pointer is set to the end of the file. rb Create a stream to read a binary file. The file pointer is set to the beginning of the file. wb Create a stream to write to a binary file. The file pointer is set to the beginning of the file. ab Create a stream to write to a binary file in append mode. The file pointer is set to the end of the file. r+b or rb+ Create a stream for reading and writing a binary file. The file pointer is set to the beginning of the file. w+b or wb+ As in previous mode. a+b or ab+ Create a stream for reading and writing to a binary file in append mode. The file pointer is set to the end of the file. Warning: Use the w, w+, wb, wb+, and w+b modes with care; they can destroy existing files. The specified type must be compatible with the access mode you used to open the file. If the file was opened with the O_APPEND FLAG, the stream mode must be r, a, a+, rb, ab, a+b, or ab+. When you open a file with a, a+, ab, a+b, or ab+ as the value of type, all write operations take place at the end of the file. Although you can reposition the file pointer using fseek or rewind, the file pointer always moves back to the end of the file before the system carries out any write operation. This action prevents you from writing over existing data. When you specify any of the types containing +, you can read from and write to the file, and the file is said to be open for update. However, when switching from reading to writing or from writing to reading, you must include an intervening fseek, fsetpos, or rewind operation. You can specify the current file position with fseek. In accessing text files, carriage-return line-feed (CR-LF) combinations are translated into a single line feed (LF) on input; LF characters are translated to CR-LF combinations on output. Accesses to binary files suppress all of these translations. (See the Programming Guide for differences between text and binary streams.) If _fdopen returns NULL, use the _close function to close the file. If _fdopen is successful, you must use fclose to close the stream and file. The _fdopen function returns a pointer to a file structure that can be used to access the open file. A NULL pointer return value indicates an error. Example of _fdopen ═══ Example of _fdopen ═══ /************************************************************************ * This example opens the file sample.dat and associates a stream with the file using _fdopen. It then reads from the stream into the buffer. * ************************************************************************/ #include #include #include #include #include int main(void) { long length; int fh; char buffer[20]; FILE *fp; memset(buffer,'\0',20); /* Initialize buffer */ printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { perror("Unable to open sample.dat"); return 1; } if (NULL == (fp = _fdopen(fh,"r"))) { perror("fdopen failed"); _close(fh); return 1; } if ( 7 != fread(buffer,1,7,fp)) { perror("fread failed"); fclose(fp); return 1; } printf("Successfully read from the stream the following:\n%s\n ",buffer); fclose(fp); return 0; /******************* The expected output is: ************************** Creating sample.dat. Successfully read from the stream the following: Sample */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _creat - Create New File o fclose - Close Stream o fopen - Open Files o fseek - Reposition File Position o fsetpos - Set File Position o _open - Open File o rewind - Adjust Current File Position o _sopen - Open Shared File o stdio.h ═══ 6.71. feof - Test End-of-File Indicator ═══ ═══ Format ═══ #include int feof(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The feof function indicates whether the end-of-file flag is set for the given stream. The end-of-file flag is set by several functions to indicate the end of the file. The end-of-file flag is cleared by calling rewind, fsetpos, fseek, or clearerr for this stream. The feof function returns a nonzero value if and only if the EOF flag is set; otherwise, 0 is returned. Example of feof ═══ Example of feof ═══ /************************************************************************ * This example scans the input stream until it reads an end-of-file character. * ************************************************************************/ #include int main(void) { char string[100]; FILE *stream; stream = fopen("myfile.dat", "r"); . . . /* scan an input stream until an end-of-file character is read */ while (!feof(stream)) if (fscanf(stream, "%s", string)) /* process the string */; } ═══ Related Information ═══ o clearerr - Reset Error Indicators o ferror - Test for Read/Write Errors o fseek - Reposition File Position o fsetpos - Set File Position o perror - Print Error Message o rewind - Adjust Current File Position o stdio.h ═══ 6.72. ferror - Test for Read/Write Errors ═══ ═══ Format ═══ #include int ferror(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The ferror function tests for an error in reading from or writing to the given stream. If an error occurs, the error indicator for the stream remains set until you close stream, call rewind, or call clearerr. The ferror function returns a nonzero value to indicate an error on the given stream. A return value of 0 means no error has occurred. Note: Some compilers are able to continue reading past EOF. Others require a call to another function such as clearerr to read beyond EOF. See the Programming Guide for more information. Example of ferror ═══ Example of ferror ═══ /************************************************************************ * This example puts data out to a stream and then checks that a write error has not occurred. * ************************************************************************/ #include int main(void) { FILE *stream; char *string = "Important information"; stream = fopen("myfile.dat","w"); fprintf(stream, "%s\n", string); if (ferror(stream)) { printf("write error\n"); clearerr(stream); } if (fclose(stream)) perror("fclose error"); } ═══ Related Information ═══ o clearerr - Reset Error Indicators o feof - Test End-of-File Indicator o fopen - Open Files o perror - Print Error Message o stdio.h o strerror - Set Pointer to Runtime Error Message o _strerror - Set Pointer to System Error String ═══ 6.73. fflush - Write Buffer to File ═══ ═══ Format ═══ #include int fflush(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fflush function causes the system to empty the buffer associated with the specified output stream, if possible. If the stream is open for input, fflush undoes the effect of any ungetc function. The stream remains open after the call. If stream is NULL, the system flushes all open streams. The fflush function returns the value 0 if it successfully flushes the buffer. The fflush function returns EOF if an error occurs. Note: The system automatically flushes buffers when you close the stream, or when a program ends normally without closing the stream. Example of fflush ═══ Example of fflush ═══ /************************************************************************ * This example flushes a stream buffer. * ************************************************************************/ #include int main(void) { FILE *stream; stream = fopen("myfile.dat", "w"); . . . fflush(stream); } ═══ Related Information ═══ o fclose - Close Stream o _flushall - Write Buffers to Files o setbuf - Control Buffering o ungetc - Push Character onto Input Stream o stdio.h ═══ 6.74. fgetc - Read a Character ═══ ═══ Format ═══ #include int fgetc(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fgetc function reads a single unsigned character from the input stream at the current position and increases the associated file pointer, if any, so that it points to the next character. The fgetc function returns the character read as an integer. An EOF return value indicates an error or an end-of-file condition. Use feof or ferror to determine whether the EOF value indicates an error or the end of the file. The fgetc function is identical to getc but is guaranteed to be a function. Example of fgetc ═══ Example of fgetc ═══ /************************************************************************ * This example gathers a line of input from a stream. * ************************************************************************/ #include #define MAX_LEN 80 int main(void) { FILE *stream; char buffer[MAX_LEN + 1]; int i, ch; stream = fopen("myfile.dat","r"); for (i = 0; (i < (sizeof(buffer)-1) && ((ch = fgetc(stream)) != EOF) && (ch != '\n')); i++) buffer[i] = ch; buffer[i] = '\0'; if (fclose(stream)) perror("fclose error"); } ═══ Related Information ═══ o _fgetchar - Read Single Character from stdin o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fputc - Write a Character o getc - Read a Character o _getch - _getche - Read Character from Keyboard o stdio.h ═══ 6.75. _fgetchar - Read Single Character from stdin ═══ ═══ Format ═══ #include int _fgetchar(void); ═══ Description ═══ Language Level: Extension The _fgetchar function reads a single character from the stdin stream. It is equivalent to a call to the SAA function fgetc: fgetc(c, stdin); For portability, replace _fgetchar with its SAA equivalent. The _fgetchar function returns the character read. A return value of EOF indicates an error or end-of-file position. Use feof or ferror to tell whether the return value indicates an error or an end-of-file position. Example of _fgetchar ═══ Example of _fgetchar ═══ /************************************************************************ * This example gathers a line of input from stdin using _fgetchar: * ************************************************************************/ #include int main(void) { char buffer[81]; int i, ch; printf("Please input a line of characters...\n"); for (i=0; (i<80) && ((ch = _fgetchar()) != EOF) && (ch!='\n'); i++) buffer[i] = ch; buffer[i] = '\0'; printf("The input line was : %s\n", buffer); return 0; /*********** If the input was "A line of characters.", then ********* ************** the output should be similar to: ******************* Please input a line of characters... A line of characters. The input line was : A line of characters. */ } ═══ Related Information ═══ o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fgetc - Read a Character o _fputchar - Write Character o getc - Read a Character o _getch - _getche - Read Character from Keyboard o stdio.h ═══ 6.76. fgetpos - Get File Position ═══ ═══ Format ═══ #include int fgetpos(FILE *stream, fpos_t *pos); ═══ Description ═══ Language Level: ANSI, SAA The fgetpos function stores the current position of the file pointer associated with stream into the object pointed to by pos. The value pointed to by pos can be used later in a call to fsetpos to reposition the stream. If successful, the fgetpos function returns 0. On error, fgetpos returns nonzero and sets errno to a nonzero value. Example of fgetpos ═══ Example of fgetpos ═══ /************************************************************************ * This example opens the file myfile for reading. The current file pointer position is stored into the variable pos. * ************************************************************************/ #include FILE *stream; int main(void) { int retcode; fpos_t pos; stream = fopen("myfile.dat", "rb"); /* The value returned by fgetpos can be used by fsetpos */ /* to set the file pointer if 'retcode' is 0 */ if ((retcode = fgetpos(stream, &pos)) == 0) printf("Current position of file pointer found\n"); fclose(stream); } ═══ Related Information ═══ o fseek - Reposition File Position o fsetpos - Set File Position o ftell - Get Current Position o stdio.h ═══ 6.77. fgets - Read a String ═══ ═══ Format ═══ #include char *fgets (char *string, int n, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fgets function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n-1, whichever comes first. The fgets function stores the result in string and adds a null character (\0) to the end of the string. The string includes the new-line character, if read. If n is equal to 1, the string is empty. The fgets function returns a pointer to the string buffer if successful. A NULL return value indicates an error or an end-of-file condition. Use feof or ferror to determine whether the NULL value indicates an error or the end of the file. In either case, the value of the string is unchanged. Example of fgets ═══ Example of fgets ═══ /************************************************************************ * This example gets a line of input from a data stream. The example reads no more than MAX_LEN - 1 characters, or up to a new-line character, from the stream. * ************************************************************************/ #include #define MAX_LEN 100 int main(void) { FILE *stream; char line[MAX_LEN], *result; stream = fopen("myfile.dat","rb"); if ((result = fgets(line,MAX_LEN,stream)) != NULL) printf("The string is %s\n", result); if (fclose(stream)) perror("fclose error"); } ═══ Related Information ═══ o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fputs - Print Strings o gets - Read a Line o puts - Write a String o stdio.h ═══ 6.78. _filelength - Determine File Length ═══ ═══ Format ═══ #include long _filelength(int handle); ═══ Description ═══ Language Level: Extension The _filelength function returns the length, in bytes, of the file associated with handle. The length of the file will be correct even if you have the handle opened and have appended data to the file. A return value of -1L indicates an error, and errno is set to one of the following values: Value Meaning EBADF The file handle is incorrect or the mode specified does not match the mode you opened the file with. EOS2ERR The call to the operating system was not successful. Example of _filelength ═══ Example of _filelength ═══ /************************************************************************ * This example opens a file and tries to determine the current length of the file using _filelength. * ************************************************************************/ #include #include #include #include int main(void) { long length; int fh; printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { printf("Unable to open sample.dat.\n"); return 1; } if (-1 == (length = _filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return 1; } printf("Current length of sample.dat is %d.\n",length); _close(fh); return 0; /**************** The expected output is: ***************************** Creating sample.dat. Current length of sample.dat is 17. */ } ═══ Related Information ═══ o _chsize - Alter Length of File o __eof - Determine End of File o io.h ═══ 6.79. _fileno - Determine File Handle ═══ ═══ Format ═══ #include int _fileno(FILE *stream); ═══ Description ═══ Language Level: Extension The _fileno function determines the file handle currently associated with stream. The _fileno function returns the file handle. If the function fails, the return value is -1 and the errno variable may be set to one of the following values: Value Meaning ENULLFCB The input stream is NULL. EBADTYPE The input stream file is not a stream file. The result is undefined if stream does not specify an open file. Example of _fileno ═══ Example of _fileno ═══ /************************************************************************ * This example determines the file handle of the stderr data stream: * ************************************************************************/ #include int main(void) { int result; result = 0xFFFF & _fileno(stderr); printf("The file handle associated with stderr is %d.\n", result); return 0; /******************* The output should be similar to: ***************** The file handle associated with stderr is 2. */ } ═══ Related Information ═══ o _dup -Associate Second Handle with Open File o _dup2 -Associate Second Handle with Open File o fopen - Open Files o freopen - Redirect Open Files o _isatty - Test Handle for Character Device o _open - Open File o stdio.h ═══ 6.80. floor - Integer <= Argument ═══ ═══ Format ═══ #include double floor(double x); ═══ Description ═══ Language Level: ANSI, SAA The floor function calculates the largest integer that is less than or equal to x. The floor function returns the floating-point result as a double value. The result of the floor function cannot have a range error. Example of floor ═══ Example of floor ═══ /************************************************************************ * This example assigns y value of the largest integer less than or equal to 2.8 and z the value of the largest integer less than or equal to -2.8. * ************************************************************************/ #include #include int main(void) { double y, z; y = floor(2.8); z = floor(-2.8); printf("floor( 2.8 ) = %lf\n", y); printf("floor( -2.8 ) = %lf\n", z); } /******************* Output should be similar to: *************** floor( 2.8 ) = 2.000000 floor( -2.8 ) = -3.000000 */ ═══ Related Information ═══ o ceil - Integer >= Argument o fmod - Floating-Point Remainder o math.h ═══ 6.81. _flushall - Write Buffers to Files ═══ ═══ Format ═══ #include int _flushall(void); ═══ Description ═══ Language Level: Extension The _flushall function causes the system to write to file the contents of all buffers associated with open output streams (including stdin, stdout, and stderr). It clears all buffers associated with open input streams of their current contents. The next read operation, if there is one, reads new data from the input files into the buffers. All streams remain open after the call. For portability, use the SAA function fflush instead of _flushall. The _flushall function returns the number of open streams of input and output. If an error occurs, _flushall returns EOF. Example of _flushall ═══ Example of _flushall ═══ /************************************************************************ * In this example, _flushall completes any pending input or output on all streams by flushing all buffers: * ************************************************************************/ #include int main(void) { int i,numflushed; char buffer1[5] = {1,2,3,4}; char buffer2[5] = {5,6,7,8}; char *file1 = "file1.dat"; char *file2 = "file2.dat"; FILE *stream1, *stream2; stream1 = fopen(file1,"a+"); stream2 = fopen(file2,"a+"); for(i = 0; i <= sizeof(buffer1); i++) { fputc(buffer1[i], stream1); fputc(buffer2[i], stream2); }; numflushed = _flushall(); /* all streams flushed */ printf("Number of files flushed = %d\n", numflushed); fclose(stream1); fclose(stream2); return 0; /******************* The output should be similar to: ***************** Number of files flushed = 5 */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o fclose - Close Stream o fflush - Write Buffer to File o stdio.h ═══ 6.82. fmod - Floating-Point Remainder ═══ ═══ Format ═══ #include double fmod(double x, double y); ═══ Description ═══ Language Level: ANSI, SAA The fmod function calculates the floating-point remainder of x/y. The absolute value of the result is always less than the absolute value of y. The result will have the same sign as x. If y is zero or if x/y causes an overflow, the function returns 0. Example of fmod ═══ Example of fmod ═══ /************************************************************************ * This example computes z as the remainder of x/y; here x/y is -3 with a remainder of -1: * ************************************************************************/ #include int main(void) { double x, y, z; x = -10.0; y = 3.0; z = fmod(x,y); /* z = -1.0 */ printf("fmod( %lf, %lf) = %lf\n", x, y, z); } /******************* Output should be similar to: *************** fmod( -10.000000, 3.000000) = -1.000000 */ ═══ Related Information ═══ o ceil - Integer >= Argument o fabs - Calculate Floating-Point Absolute Value o floor - Integer <= Argument o math.h ═══ 6.83. fopen - Open Files ═══ ═══ Format ═══ #include FILE *fopen(const char *filename, const char *mode); ═══ Description ═══ Language Level: ANSI, SAA The fopen function opens the file specified by filename. The mode variable is a character string specifying the type of access requested for the file. The mode variable contains one positional parameter followed by optional keyword parameters. The possible values for the positional parameters are: Mode Description r Open a text file for reading. The file must exist. w Create a text file for writing. If the given file exists, its contents are destroyed. a Open a text file in append mode for writing at the end of the file. fopen creates the file if it does not exist. r+ Open a text file for both reading and writing. The file must exist. w+ Create a text file for both reading and writing. If the given file exists, its contents are destroyed. a+ Open a text file in append mode for reading or updating at the end of the file. fopen creates the file if it does not exist. rb Open a binary file for reading. The file must exist. wb Create an empty binary file for writing. If the file exists, its contents are destroyed. ab Open a binary file in append mode for writing at the end of the file. fopen creates the file if it does not exist. r+b or rb+ Open a binary file for both reading and writing. The file must exist. w+b or wb+ Create an empty binary file for both reading and writing. If the file exists, its contents will be destroyed. a+b or ab+ Open a binary file in append mode for writing at the end of the file. fopen creates the file if it does not exist. Warning: Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files of the same name will be lost. Text files contain printable characters and control characters organized into lines. Each line ends with a new-line character, except for the last line, which does not require one. The system may insert or convert control characters in an output text stream. Note: Data output to a text stream may not compare as equal to the same data on input. Binary files contain a series of characters. For binary files, the system does not translate control characters on input or output. When you open a file with a, a+, ab, a+b or ab+ mode, all write operations take place at the end of the file. Although you can reposition the file pointer using fseek or rewind, the write functions move the file pointer back to the end of the file before they carry out any operation. This action prevents you from overwriting existing data. When you specify the update mode (using + in the second or third position), you can both read from and write to the file. However, when switching between reading and writing, you must include an intervening positioning function such as fseek, fsetpos, rewind, or fflush. Output may immediately follow input if the end-of-file was detected. The keyword parameters are: blksize=value Specifies the maximum length, in bytes, of a physical block of records. For fixed-length records, the maximum size is 32760 bytes. For variable-length records, the maximum is 32756. The default buffer size is 4096 bytes. lrecl=value Specifies the length, in bytes, for fixed-length records and the maximum length for variable-length records. For fixed-length records, the maximum length is 32760 bytes. For variable-length records, the maximum is 32756. If the value of LRECL is larger than the value of BLKSIZE, the LRECL value is ignored recfm=value value can be: F fixed-length, unblocked records V variable-length, unblocked records The default for the C/C++ Tools compiler is fixed-length record format. type=value value can be: memory This parameter identifies this file as a memory file that is accessible only from C programs. This is the default. If you want to use a memory file, you must compile with the /Sv option. The C/C++ Tools compiler does not support record I/O. The fopen function generally fails if parameters are mismatched. The file attributes can be altered only if the open mode specified with the fopen function is one of the write modes (w, w+, wb, or wb+). The system deletes the existing file and creates a new file with the attributes specified in fopen. The fopen function returns a pointer to a file structure that can be used to access the open file. A NULL pointer return value indicates an error. Example of fopen ═══ Example of fopen ═══ /************************************************************************ * This example attempts to open a file for reading: * ************************************************************************/ #include int main(void) { FILE *stream; if ((stream = fopen("myfile.dat", "r")) == NULL) printf("Could not open data file\n"); /* The following call opens a fixed record length file */ /* for reading and writing. */ stream = fopen("myfile.dat", "rb+, lrecl=80, \ blksize=240, recfm=f"); } ═══ Related Information ═══ o _creat - Create New File o fclose - Close Stream o fflush - Write Buffer to File o fread - Read Items o freopen - Redirect Open Files o _open - Open File o _sopen - Open Shared File o fseek - Reposition File Position o fsetpos - Set File Position o fwrite - Write Items o rewind - Adjust Current File Position o stdio.h ═══ 6.84. _fpatan - Calculate Arctangent ═══ ═══ Format ═══ #include double _fpatan(double x); ═══ Description ═══ Language Level: Extension The _fpatan function calculates the arctangent of x, which is a value in radians between -у/2 and у/2. This function causes the compiler to emit the appropriate 80387 instruction for the calculation of arctangent. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fpatan. o You cannot parenthesize a _fpatan function call, because parentheses specify a call to the backing code for the function. This function returns the arctangent of x. Example of _fpatan ═══ Example of _fpatan ═══ /************************************************************************ * This example calculates the arctangent of x. * ************************************************************************/ #include #include #include int main(void) { double a,c; c = 0.45; a = _fpatan(c); printf("The arctangent of %lf is %lf.\n", c, a); } ═══ Related Information ═══ o atan - atan2 - Calculate Arctangent o _fptan - Calculate Tangent o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent ═══ 6.85. _fpreset - Reset Floating-Point Unit ═══ ═══ Format ═══ #include void _fpreset(void); ═══ Description ═══ Language Level: Extension The _fpreset function resets the floating-point unit to the default state that the math library requires to function correctly. This function is often used within signal handlers. For more information on signal handlers, see the Programming Guide. If a program traps floating-point error signals (SIGFPE) with signal, the program can safely recover from floating-point errors by calling longjmp. The _fpreset function resets the floating-point unit of the current thread only. It does not affect any other threads that may be processing. There is no return value. Example of _fpreset ═══ Example of _fpreset ═══ /************************************************************************ * This example establishes the function fphandler as a floating-point error handler. The main program produces a floating-point error, which causes control to be passed to fphandler. The fphandler function calls _fpreset to reset the floating-point unit, and then returns to main. * ************************************************************************/ #include #include #include #include jmp_buf mark; void fphandler(int sig) { printf("Floating point signal = %d\n", sig); _fpreset(); /* Reinitialize floating-point package */ longjmp(mark, -1); } int main(void) { double a = 1.0, b = 0.0, c; if (signal(SIGFPE, fphandler) == SIG_ERR) exit(-1); if (setjmp(mark) == 0) { c = a / b; /* generate floating-point error */ printf("Should never get here\n"); } printf("Recovered from floating-point error\n"); return 0; /* The expected output is: Floating point signal = 3 Recovered from floating-point error */ } ═══ Related Information ═══ o _clear87 - Clear Floating-Point Status Word o _control87 - Set Floating-Point Status Word o longjmp - Restore Stack Environment o signal Install Interrupt Handlers o _status87 - Get Floating-Point Status Word o float.h ═══ 6.86. fprintf - Write Formatted Data ═══ ═══ Format ═══ #include int fprintf(FILE *stream, const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, Extension The fprintf function formats and writes a series of characters and values to the output stream. The fprintf function converts each entry in argument-list, if any, and writes to the stream according to the corresponding format specification in the format-string. The format-string has the same form and function as the format-string argument for the printf function. In extended mode, fprintf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. The fprintf function returns the number of characters printed or a negative value if an output error occurs. Example of fprintf ═══ Example of fprintf ═══ /************************************************************************ * This example sends a line of asterisks for each integer in the array count to the file myfile. The number of asterisks printed on each line corresponds to an integer in the array. * ************************************************************************/ #include int count [10] = {1, 5, 8, 3, 0, 3, 5, 6, 8, 10}; int main(void) { int i,j; FILE *stream; stream = fopen("myfile.dat", "w"); /* Open the stream for writing */ for (i=0; i < sizeof(count) / sizeof(count[0]); i++) { for (j = 0; j < count[i]; j++) fprintf(stream,"*"); /* Print asterisk */ fprintf(stream,"\n"); /* Move to the next line */ } fclose (stream); } /******************* Output should be similar to: *************** * ***** ******** *** *** ***** ****** ******** ********** */ ═══ Related Information ═══ o _cprintf - Print Characters to Screen o fscanf - Read Formatted Data o printf - Formatted Print o sprintf - Formatted Print to Buffer o vfprintf - Print Argument Data o vprintf - Print Argument Data o vsprintf - Print Argument Data o Infinity and NaN Support o stdio.h ═══ 6.87. _fptan - Calculate Tangent ═══ ═══ Format ═══ #include double _fptan(double x); ═══ Description ═══ Language Level: Extension The _fptan function calculates the tangent of x, where x is expressed in radians. The value of x must be less than 2**63. This function causes the compiler to emit the appropriate 80387 instruction for the calculation of tangent. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fptan. o You cannot parenthesize a _fptan function call, because parentheses specify a call to the backing code for the function in the library. This function returns the tangent of a variable x expressed in radians. Example of _fptan ═══ Example of _fptan ═══ /************************************************************************ * This example calculates the tangent of pi/4. * ************************************************************************/ #include #include #include int main(void) { double pi, x; pi = 3.1415926; x = _fptan(pi/4.0); printf("The tangent of %lf is %lf\n", pi/4, x); } ═══ Related Information ═══ o atan - atan2 - Calculate Arctangent o _fpatan - Calculate Arctangent o tan - Calculate Tangent o tanh - Calculate Hyperbolic Tangent ═══ 6.88. fputc - Write a Character ═══ ═══ Format ═══ #include int fputc(int c, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fputc function converts c to an unsigned char and then writes c to the output stream at the current position and advances the file position appropriately. If the stream is opened with one of the append modes, the character is appended to the end of the stream. The fputc function returns the character written. A return value of EOF indicates an error. The fputc function is identical to putc but is guaranteed to be a function. Example of fputc ═══ Example of fputc ═══ /************************************************************************ * This example writes the contents of buffer to a file called myfile. Note: Because the output occurs as a side effect within the second expression of the for statement, the statement body is null. * ************************************************************************/ #include #define NUM_ALPHA 26 int main(void) { FILE * stream; int i; int ch; char buffer[NUM_ALPHA + 1] = "abcdefghijklmnopqrstuvwxyz"; if (( stream = fopen("myfile.dat", "w"))!= NULL ) { /* Put buffer into file */ for ( i = 0; ( i < sizeof(buffer) ) && ((ch = fputc( buffer[i], stream)) != EOF ); ++i ); fclose( stream ); } else perror( "Error opening myfile" ); } ═══ Related Information ═══ o fgetc - Read a Character o _fputchar - Write Character o putc - putchar - Write a Character o _putch - Write Character to Screen o stdio.h ═══ 6.89. _fputchar - Write Character ═══ ═══ Format ═══ #include int _fputchar(int c); ═══ Description ═══ Language Level: Extension The _fputchar function writes the single character c to the stdout stream at the current position. It is equivalent to a call to the SAA function fputc: fputc(c, stdout); For portability, replace _fputchar with the SAA equivalent. The function returns the character written. A return value of EOF indicates that a write error has occurred. Use ferror and feof to tell whether this is an error condition or the end of the file. Example of _fputchar ═══ Example of _fputchar ═══ /************************************************************************ * This example writes the contents of buffer to stdout: * ************************************************************************/ #include int main(void) { char buffer[80]; int i, ch = 1; for (i=0; i<80; i++) buffer[i] = 'c'; for (i=0; (i<80) && (ch!=EOF); i++) ch = _fputchar(buffer[i]); printf("\n"); return 0; /************************ The output should be similar to: ************* ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc */ } ═══ Related Information ═══ o _fgetchar - Read Single Character from stdin o fputc - Write a Character o putc - putchar - Write a Character o _putch - Write Character to Screen o stdio.h ═══ 6.90. fputs - Print Strings ═══ ═══ Format ═══ #include int fputs(const char *string, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fputs function copies string to the output stream at the current position. It does not copy the null character (\0) at the end of the string. If an error occurs, the fputs function returns EOF; otherwise, it returns a non-negative value. Example of fputs ═══ Example of fputs ═══ /************************************************************************ * This example writes a string to a stream. * ************************************************************************/ #include #define NUM_ALPHA 26 int main(void) { FILE * stream; int num; /* Do not forget that the '\0' char occupies one character */ static char buffer[NUM_ALPHA + 1] = "abcdefghijklmnopqrstuvwxyz"; if ((stream = fopen("myfile.dat", "w")) != NULL ) { /* Put buffer into file */ if ( (num = fputs( buffer, stream )) != EOF ) { /* Note that fputs() does not copy the \0 character */ printf( "Total number of characters written to file = %i\n", num ); fclose( stream ); } else /* fputs failed */ perror( "fputs failed" ); } else perror( "Error opening myfile" ); } ═══ Related Information ═══ o _cputs - Write String to Screen o fgets - Read a String o gets - Read a Line o puts - Write a String o stdio.h ═══ 6.91. fread - Read Items ═══ ═══ Format ═══ #include size_t fread(void *buffer, size_t size, size_t count, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fread function reads up to count items of size length from the input stream and stores them in the given buffer. The position in the file increases by the number of bytes read. The fread function returns the number of full items successfully read, which can be less than count if an error occurs or if the end-of-file is met before reaching count. If size or count is 0, fread returns zero and the contents of the array and the state of the stream remain unchanged. The ferror and feof functions are used to distinguish between a read error and an end-of-file. Example of fread ═══ Example of fread ═══ /************************************************************************ * This example attempts to read NUM_ALPHA characters from the file myfile. If there are any errors with either fread or fopen, a message is printed. * ************************************************************************/ #include #define NUM_ALPHA 26 int main(void) { FILE * stream; int num; /* number of characters read from stream */ /* Do not forget that the '\0' char occupies one character too! */ char buffer[NUM_ALPHA + 1]; if (( stream = fopen("myfile.dat", "r"))!= NULL ) { num = fread( buffer, sizeof( char ), NUM_ALPHA, stream ); if ( num ) { /* fread success */ printf( "Number of characters has been read = %i\n", num ); printf( "buffer = %s\n", buffer ); fclose( stream ); } else { /* fread failed */ if ( ferror(stream) ) /* possibility 1 */ perror( "Error reading myfile" ); else if ( feof(stream)) /* possibility 2 */ perror( "EOF found" ); } } else perror( "Error opening myfile" ); } ═══ Related Information ═══ o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fopen - Open Files o fwrite - Write Items o _read - Read Into Buffer o stdio.h ═══ 6.92. free - Release Storage Blocks ═══ ═══ Format ═══ #include /* also defined in */ void free(void *ptr); ═══ Description ═══ Language Level: ANSI, SAA, Extension The free function frees a block of storage. The ptr variable points to a block previously reserved with a call to calloc, malloc, or realloc. The number of bytes freed is the number of bytes specified when you reserved (or reallocated, in the case of realloc) the block of storage. If ptr is NULL, free simply returns. There is no return value. Note: Attempting to free a block of storage not allocated with calloc, malloc, or realloc (or previously freed storage) can affect the subsequent reserving of storage and lead to undefined results. Example of free ═══ Example of free ═══ /************************************************************************ * This example uses calloc to allocate storage for x array elements and then calls free to free them. * ************************************************************************/ #include #include int main(void) { long * array; /* start of the array */ long * index; /* index variable */ int i; /* index variable */ int num; /* number of entries of the array */ printf( "Enter the size of the array\n" ); scanf( "%i", &num ); /* allocate num entries */ if ( (index = array = calloc( num, sizeof( long ))) != NULL ) { . . /* do something with the array */ . free( array ); /* deallocates array */ } else { /* Out of storage */ perror( "Error: out of storage" ); abort(); } } ═══ Related Information ═══ o _alloca - Temporarily Reserve Storage Block o calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o malloc - Reserve Storage Block o realloc - Change Reserved Storage Block Size o malloc.h o _tfree - Free Tiled Storage Block o stdlib.h ═══ 6.93. _freemod - Free User DLL ═══ ═══ Format ═══ #include int _freemod(unsigned long module_handle); ═══ Description ═══ Language Level: Extension The _freemod function frees all references to a user-created dynamic-link library (DLL) for the calling process. It is the counterpart of the _loadmod function, which loads a DLL for the process. The module_handle is the module handle of the DLL, which was returned by _loadmod. If successful, the _freemod function returns 0. If not, _freemod returns -1 and sets errno to EOS2ERR. Example of _freemod ═══ Example of _freemod ═══ /************************************************************************ * This example loads the DLL mark with _loadmod, and uses the OS/2 function DosQueryProcAddr to get the address of the function dor from within the DLL. It then calls that function, which multiplies two integers passed to it. When the function and DLL are no longer needed, the program frees the DLL module. The macro INCL_DOS and the types PFN and APIRET are required for the OS/2 call, and are defined by including the header file. Note: To run this program, you must first create mark.dll. Copy the code for the PLUS function into a file called mark.c, and the code for the .DEF file into mark.def. Eliminate the comments from these two files. Compile with the command: icc /Ge- mark.c mark.def You can then run the example: * ************************************************************************/ #define INCL_DOS #include #include #include /* This is the code for MARK.DEF LIBRARY MARK PROTMODE EXPORTS PLUS */ /* This is the code for PLUS function in the DLL #pragma linkage( PLUS, system ) int PLUS( int a, int b ) { return a + b; } */ int main(void) { int x = 4, y = 7; unsigned long handle; char * modname = "MARK" ; /* DLL name */ char * fname = "PLUS" ; /* function name */ PFN faddr; /* pointer to function */ APIRET rc; /* return code */ /* from DosQueryProcAddr */ /* dynamically load the 'mark' DLL */ if (_loadmod(modname, &handle) ) { printf("Error loading module %s\n", modname ); exit (-1); } /* get function address from DLL */ rc = DosQueryProcAddr( handle, 0, fname, &faddr ); if (rc == 0) printf("Calling the function from the %s DLL to add %d and %d\n", modname,x,y); printf("The result of the function call is %d\n", faddr(x,y)); else { printf("Error locating address of function %s\n", fname); _freemod( handle ); exit(-1); } if( _freemod( handle )) { printf("Error in freeing the %s DLL module\n", modname); exit(-1); } printf("Reference to the %s DLL module has been freed\n", modname); return 0; /************** The expected output is ******************** Calling the function from the DLL to add 4 and 7 The result of the function call is 11 Reference to the MARK DLL module has been freed */ } ═══ Related Information ═══ o _loadmod - Load User DLL o stdlib.h ═══ 6.94. freopen - Redirect Open Files ═══ ═══ Format ═══ #include FILE *freopen(const char *filename, const char *mode, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The freopen function closes the file currently associated with stream and reassigns stream to the file specified by filename. The freopen function opens the new file associated with stream with the given mode, which is a character string specifying the type of access requested for the file. You can also use the freopen function to redirect the standard stream files stdin, stdout, and stderr to files that you specify. If filename is an empty string, freopen closes and reopens the stream to the new open mode, rather than reassigning it to a new file or device. You can use freopen with no file name specified to change the mode of a standard stream from text to binary without redirecting the stream, for example: fp = freopen("", "rb", stdin); You can use the same method to change the mode from binary back to text. Note: This method is included in the SAA C definition, but not in the ANSI C standard. See fopen. for a description of the mode parameter. The freopen function returns the value of stream to the newly opened file. If an error occurs, freopen closes the original file and returns a NULL pointer value. Example of freopen ═══ Example of freopen ═══ /************************************************************************ * This example closes the stream1 data stream and reassigns its stream pointer: * ************************************************************************/ #include int main(void) { FILE *stream, *stream1, *stream2; stream = fopen("myfile.dat","r"); stream1 = stream; stream2 = freopen("", "w+", stream1); } /************************************************************************ * Note that stream1 and stream2 will have the same value, but they will not necessarily have the same value as stream. * ************************************************************************/ ═══ Related Information ═══ o _close - Closes File Associated with Handle o fclose - Close Stream o _fcloseall - Close All Open Streams o fopen - Open Files o _open - Open File o _sopen - Open Shared File o stdio.h ═══ 6.95. frexp - Separate Floating-Point Value ═══ ═══ Format ═══ #include double frexp(double x, int *expptr); ═══ Description ═══ Language Level: ANSI, SAA The frexp function breaks down the floating-point value x into a term m for the mantissa and another term n for the exponent, such that the absolute value of m is greater than or equal to 0.5 and less than 1.0 or equal to 0, and x = m * (2**n). The frexp function stores the integer exponent n at the location to which expptr points. The frexp function returns the mantissa term m. If x is 0, the function returns 0 for both the mantissa and exponent. The mantissa has the same sign as the argument x. The result of the frexp function cannot have a range error. Example of frexp ═══ Example of frexp ═══ /************************************************************************ * This example decomposes the floating-point value of x, 16.4, into its mantissa 0.5125, and its exponent 5. It stores the mantissa in y and the exponent in n. * ************************************************************************/ #include #include int main(void) { double x, m; int n; x = 16.4; m = frexp(x, &n); printf("The mantissa is %lf and the exponent is %d\n", m, n); } /******************* Output should be similar to: *************** The mantissa is 0.512500 and the exponent is 5 */ ═══ Related Information ═══ o ldexp - Multiply by a Power of Two o modf - Separate Floating-Point Value o math.h ═══ 6.96. fscanf - Read Formatted Data ═══ ═══ Format ═══ #include int fscanf (FILE *stream, const char *format-string, argument-list); ═══ Desciption ═══ Language Level: ANSI, SAA, Extension The fscanf function reads data from the current position of the specified stream into the locations given by the entries in argument-list, if any. Each entry in argument-list must be a pointer to a variable with a type that corresponds to a type specifier in format-string. The format-string controls the interpretation of the input fields and has the same form and function as the format-string argument for the scanf function. See scanf for a description of format-string. In extended mode, the fscanf function also reads in the strings "INFINITY", "INF", and "NAN" (in upper or lowercase) and converts them to the corresponding floating-point value. The sign of the value is determined by the format specification. See Infinity and NaN Support for more information on infinity and NaN values. The fscanf function returns the number of fields that it successfully converted and assigned. The return value does not include fields that fscanf read but did not assign. The return value is EOF if an input failure occurs before any conversion, or the number of input items assigned if successful. Example of fscanf ═══ Example of fscanf ═══ /************************************************************************ * This example opens the file myfile for reading and then scans this file for a string, a long integer value, a character, and a floating-point value. * ************************************************************************/ #include #define MAX_LEN 80 int main(void) { FILE *stream; long l; float fp; char s[MAX_LEN + 1]; char c; stream = fopen("myfile.dat", "r"); /* Put in various data. */ fscanf(stream, "%s", &s[0]); fscanf(stream, "%ld", &l); fscanf(stream, "%c", &c); fscanf(stream, "%f", &fp); printf("string = %s\n", s); printf("long double = %ld\n", l); printf("char = %c\n", c); printf("float = %f\n", fp); } /*************** If myfile contains ************************ ****************abcdefghijklmnopqrstuvwxyz 343.2, *********** ********************** expected output is: ********************* string = abcdefghijklmnopqrstuvwxyz long double = 343 char = . float = 2.000000 */ ═══ Related Information ═══ o _cscanf - Read Data from Keyboard o fprintf - Write Formatted Data o scanf - Read Data o sscanf - Read Data o Infinity and NaN Support o stdio.h ═══ 6.97. fseek - Reposition File Position ═══ ═══ Format ═══ #include int fseek(FILE *stream, long int offset, int origin); ═══ Description ═══ Language Level: ANSI, SAA The fseek function changes the current file position associated with stream to a new location within the file. The next operation on the stream takes place at the new location. On a stream open for update, the next operation can be either a reading or a writing operation. The origin must be one of the following constants defined in : Origin Definition SEEK_SET Beginning of file SEEK_CUR Current position of file pointer SEEK_END End of file For a binary stream, you can also change the position beyond the end of the file. An attempt to position before the beginning of the file causes an error. If successful, the fseek function clears the end-of-file indicator, even when origin is SEEK_END, and undoes the effect of any preceding ungetc function on the same stream. The fseek function returns the value 0 if it successfully moves the pointer. A nonzero return value indicates an error. On devices that cannot seek, such as terminals and printers, the return value is nonzero. Note: For streams opened in text mode, fseek has limited use because some system translations (such as those between carriage return/line feed and new line) can produce unexpected results. The only fseek operations that can be relied upon to work on streams opened in text mode are seeking with an offset of zero relative to any of the origin values or seeking from the beginning of the file with an offset value returned from a call to ftell. See the Programming Guide for more information. Example of fseek ═══ Example of fseek ═══ /************************************************************************ * This example opens a file myfile for reading. After performing input operations (not shown), it moves the file pointer to the beginning of the file. * ************************************************************************/ #include int main(void) { FILE *stream; int result; stream = fopen("myfile.dat", "r"); . . . result = fseek(stream, 0L, SEEK_SET); /* moves the pointer to the */ /* beginning of the file */ } ═══ Related Information ═══ o fgetpos - Get File Position o fsetpos - Set File Position o ftell - Get Current Position o rewind - Adjust Current File Position o ungetc - Push Character onto Input Stream o stdio.h ═══ 6.98. fsetpos - Set File Position ═══ ═══ Format ═══ #include int fsetpos(FILE *stream, const fpos_t *pos); ═══ Description ═══ Language Level: ANSI, SAA The fsetpos function moves any file position associated with stream to a new location within the file according to the value pointed to by pos. The value of pos was obtained by a previous call to the fgetpos library function. If fsetpos successfully changes the current position of the file, it returns the value 0. If successful, the fsetpos function clears the end-of-file indicator, and undoes the effect of any previous ungetc function on the same stream. A nonzero return value indicates an error. After the fsetpos call, the next operation on a stream in update mode may be input or output. Example of fsetpos ═══ Example of fsetpos ═══ /************************************************************************ * This example opens a file myfile for reading. After performing input operations (not shown), it moves the file pointer to the beginning of the file and rereads the first byte. * *************************************************************************/ #include FILE *stream; int main(void) { int retcode; fpos_t pos, pos1, pos2, pos3; char ptr[20]; /* existing file 'myfile.dat' has 20 byte records */ /* Open file, get position of file pointer, and read first record */ stream = fopen("myfile.dat", "rb"); fgetpos(stream,&pos); pos1 = pos; if (!fread(ptr,sizeof(ptr),1,stream)) perror("fread error"); /* Perform a number of read operations - the value of 'pos' changes */ . . . /* Re-set pointer to start of file and re-read first record */ fsetpos(stream,&pos1); if (!fread(ptr,sizeof(ptr),1,stream)) perror("fread error"); fclose(stream); } ═══ Related Information ═══ o fgetpos - Get File Position o fseek - Reposition File Position o ftell - Get Current Position o rewind - Adjust Current File Position o ungetc - Push Character onto Input Stream o stdio.h ═══ 6.99. _fsin - Calculate Sine ═══ ═══ Format ═══ #include double _fsin( double x); ═══ Description ═══ Language Level: Extension The _fsin function calculates the sine of x, where x is expressed in radians. The value of x must be less than 2**63. This function causes the compiler to emit the appropriate 80387 instruction for the calculation of sine. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fsin. o You cannot parenthesize a _fsin function call, because parentheses specify a call to the backing code for the function in the library. This function returns the sine of a variable x expressed in radians. Example of _fsin ═══ Example of _fsin ═══ /************************************************************************ * This example calculates y as the sine of у/2. * ************************************************************************/ #include #include #include int main(void) { double pi, x, y; pi = 3.1415926535; x = pi/2; y = _fsin(x); printf("The sine of %lf is %lf\n", x, y); ) ═══ Related Information ═══ o _fasin - Calculate Arcsine o _fcossin - Calculate Cosine and Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine ═══ 6.100. _fsincos - Calculate Sine and Cosine ═══ ═══ Format ═══ #include double _fsincos(double x, double *y); ═══ Description ═══ Language Level: Extension The _fsincos function calculates the sine of x, and stores the cosine in *y. This operation is faster than separately calculating the sine and cosine. Use _fsincos instead of _fcossin when you will be using the sine first, and then the cosine. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fsincos. o You cannot parenthesize a _fsincos function call because parentheses specify a call to the backing code for the function. This function returns the sine of x. Example of _fsincos ═══ Example of _fsincos ═══ /************************************************************************ * This example calculates the sine of x and stores the cosine of x in y. * ************************************************************************/ #include #include #include #define MAX 1.0 #define MIN -1.0 int main(void) { double x,y; printf( "Enter x\n" ); scanf( "%lf", &x ); /* Output error if not in range */ if ( x > MAX ) printf( "Error: %lf too large for sine\n", x ); else if ( x < MIN ) printf( "Error: %lf too small for sine\n", x ); else { z = _fsincos( x, *y); printf("The sine of %d is %lf\n", x, z); printf("The cosine of %d is %lf\n", x, *y); } } ═══ Related Information ═══ o acos - Calculate Arccosine o asin - Calculate Arcsine o cos - Calculate Cosine o cosh - Calculate Hyperbolic Cosine o _facos - Calculate Arccosine o _fasin - Calculate Arcsine o _fcos - Calculate Cosine o _fcossin - Calculate Cosine and Sine o _fsin - Calculate Sine o sin - Calculate Sine o sinh - Calculate Hyperbolic Sine ═══ 6.101. _fsqrt - Calculate Square Root ═══ ═══ Format ═══ #include double _fsqrt(double x); ═══ Description ═══ Language Level: Extension The _fsqrt function computes the square root of x using the FSQRT 80387 instruction. Note that this function does not set errno as the sqrt function does. If you pass a negative value to this function, an exception is generated. This function returns the value of the square root of x. Example of _fsqrt ═══ Example of _fsqrt ═══ /************************************************************************ * This example calculates the square root of 4. * ************************************************************************/ #include #include int main(void) { double x, y; x = 4; y = _fsqrt( x ); printf("The square root of %d is %d.\n", x, y); } ═══ Related Information ═══ o sqrt - Calculate Square Root ═══ 6.102. _fstat - Information about Open File ═══ ═══ Format ═══ #include #include int _fstat(int handle, struct stat *buffer); ═══ Description ═══ Language Level: Extension The _fstat function obtains information about the open file associated with the given handle and stores it in the structure to which buffer points. The include file defines the stat structure. The stat structure contains the following fields: Field Value st_mode Bit mask for file mode information. The _fstat function sets the S_IFCHR bit if handle refers to a device. The S_IFDIR bit is set if pathname specifies a directory. It sets the S_IFREG bit if handle refers to an ordinary file. It sets user read/write bits according to the permission mode of the file. The other bits have undefined values. F E D C B A 9 8 7 6 5 4 3 2 1 0 │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘       S_IFREG──────┘ │ │ │ │ └──────execute/search permission, (regular file) │ │ │ │ owner (S_IEXEC) S_IFDIR────────┘ │ │ └────────write permission, owner S_IFCHR──────────┘ └──────────read permission, owner st_dev Drive number of the disk containing the file. st_rdev Drive number of the disk containing the file (same as st_dev). st_nlink Always 1. st_size Size of the file in bytes. st_atime Time of last modification of file. st_mtime Same as st_atime if not provided by the file system. st_ctime Same as st_atime if not provided by the file system. There are three additional fields in the fstat structure for portability to other operating systems; they have no meaning under the OS/2 operating system. Note: If the given handle refers to a device, the size and time fields in the fstat structure are not meaningful. The _fstat function returns the value 0 if it obtains the file status information. A return value of -1 indicates an error; in this case, _fstat sets errno to EBADF, showing an incorrect file handle. Example of _fstat ═══ Example of _fstat ═══ /************************************************************************ * This example uses _fstat to report the size of a file named data. * ************************************************************************/ #include #include #include #include int main(void) { struct stat buf; FILE *fp; int fh, result; char *buffer = "A line to output"; fp = fopen("data", "w+"); fprintf(fp, "%s", buffer); fflush(fp); fclose(fp); fp = fopen("data", "r"); if (_fstat(_fileno(fp), &buf) == 0) { printf("file size is %ld\n", buf.st_size); printf("time modified is %s\n", ctime(&buf.st_atime)); } else printf("Bad file handle\n"); fclose(fp); return 0; /************** The output should be similar to: ********************** file size is 16 time modified is Tue March 30 16:08:14 1993 */ } ═══ Related Information ═══ o _stat - Get Information about File or Directory o sys\stat.h o sys\types.h ═══ 6.103. ftell - Get Current Position ═══ ═══ Format ═══ #include long int ftell(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The ftell function returns a value indicating the current position of the file associated with stream. For a fixed-length binary file, the value returned by ftell is an offset relative to the beginning of the stream. On error, ftell returns -1L and sets errno to a nonzero value. Example of ftell ═══ Example of ftell ═══ /************************************************************************ * This example opens the file myfile for reading. It reads enough characters to fill half of the buffer and prints out the position in the stream and the buffer. * ************************************************************************/ #include #define NUM_ALPHA 26 #define NUM_CHAR 6 int main(void) { FILE * stream; int i; char ch; char buffer[NUM_ALPHA]; long position; if (( stream = fopen("myfile.dat", "r")) != NULL ) { /* read into buffer */ for ( i = 0; ( i < NUM_ALPHA/2 ) && ((buffer[i] = fgetc(stream)) != EOF ); ++i ) if (i==NUM_CHAR-1) /* We want to be able to position the */ /* file pointer to the character in */ /* position NUM_CHAR */ position = ftell(stream); buffer[i] = '\0'; fseek (stream, position, SEEK_SET); ch = fgetc (stream); /* get the character at position NUM_CHAR */ fclose( stream ); } else perror( "Error opening myfile" ); } ═══ Related Information ═══ o fseek - Reposition File Position o fgetpos - Get File Position o fopen - Open Files o fsetpos - Set File Position o stdio.h ═══ 6.104. _ftime - Store Current Time ═══ ═══ Format ═══ #include #include void _ftime(struct timeb *timeptr); ═══ Description ═══ Language Level: Extension The _ftime function gets the current time and stores it in the structure to which timeptr points. The include file contains the definition of the timeb structure. It contains four fields: time, millitm, timezone, and dstflag. The time field gives the time in seconds since 00:00:00 Coordinated Universal Time, January 1, 1970. The millitm field gives the fraction of a second, in milliseconds. The timezone field gives the difference in minutes between Coordinated Universal Time and local time, going from east to west. The _ftime function sets the value of timezone from the value of the global variable _timezone. The dstflag is nonzero if daylight saving time is currently in effect for the local time zone. For an explanation of how daylight saving time is determined, see _tzset - Assign Values to Locale Information. There is no return value. Example of _ftime ═══ Example of _ftime ═══ /************************************************************************ * This example polls the system clock, converts the current time to a character string, prints the string, and saves the time data in the structure timebuffer: * ************************************************************************/ #include #include #include #include int main(void) { struct timeb timebuffer; _ftime(&timebuffer); printf("the time is %s\n", ctime(&(timebuffer.time))); return 0; /************** The output should be similar to: ********************** the time is Tue March 30 16:08:17 1993 */ } ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o time - Determine Current Time o _tzset - Assign Values to Locale Information o sys\timeb.h o sys\types.h ═══ 6.105. _fullpath - Get Full Path Name of Partial Path ═══ ═══ Format ═══ #include char *_fullpath(char *pathbuf, char *partialpath, size_t n); ═══ Description ═══ Language Level: Extension The _fullpath function gets the full path name of the given partial path name partialpath, and stores it in pathbuf. The integer argument n specifies the maximum length for the path name. An error occurs if the length of the path name, including the terminating null character, exceeds n characters. If the pathbuf argument is NULL, _fullpath uses malloc to allocate a buffer of size _MAX_PATH bytes to store the path name. The _fullpath function returns a pointer to pathbuf. If an error occurs, _fullpath returns NULL and sets errno to one of the following values: Value Meaning ENOMEM Unable to allocate storage for the buffer. ERANGE The path name is longer than n characters. EOS2ERR A system error occurred. Check _doserrno for the specific OS/2 error code. Example of _fullpath ═══ Example of _fullpath ═══ /************************************************************************ * This example uses _fullpath to get and store the full path name of the current directory. * ************************************************************************/ #include #include #include int main(void) { char *retBuffer; retBuffer = _fullpath(NULL, ".", 0); if ( retBuffer == NULL ) printf("An error has occurred, errno is set to %d.\n", errno); else printf("Full path name of current directory is %s.\n", retBuffer); return 0; /* If path of current directory is D:\BIN, the expected output is: Full path name of current directory is D:\BIN. */ } ═══ Related Information ═══ o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _makepath - Create Path o malloc - Reserve Storage Block o _splitpath - Decompose Path Name o stdlib.h ═══ 6.106. fwrite - Write Items ═══ ═══ Format ═══ #include size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The fwrite function writes up to count items of size length from buffer to the output stream. The fwrite function returns the number of full items successfully written, which can be less than count if an error occurs. Example of fwrite ═══ Example of fwrite ═══ /************************************************************************ * This example writes NUM long integers to a stream in binary format. * ************************************************************************/ #include #define NUM 100 int main(void) { FILE *stream; long list[NUM]; int numwritten; stream = fopen("myfile.dat", "w+b"); . . /* assign values to list[] */ . numwritten = fwrite(list, sizeof(long), NUM, stream); } ═══ Related Information ═══ o fopen - Open Files o fread - Read Items o _read - Read Into Buffer o stdio.h o _write - Writes from Buffer to File ═══ 6.107. _fyl2x - Calculate y * log2(x) ═══ ═══ Format ═══ #include double _fyl2x(double x, double y); ═══ Description ═══ Language Level: Extension The _fyl2x function computes the base-2 logarithm of x and multiplies it by y (y * log2(x)). The variable x cannot be negative. This instruction is designed with a built-in multiplication to optimize the calculation of logarithms with arbitrary positive base: log b (x) = (log2(b)**-1) * log2(x) Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fyl2x. o You cannot parenthesize a _fyl2x function call, because parentheses specify a call to the backing code for the function in the library. This function returns the result of the formula y * log2(x) Example of _fyl2x ═══ Example of _fyl2x ═══ /************************************************************************ * This example calculates (y * log2(x)), after prompting the user for values of x and y. * ************************************************************************/ #include #include #include int main(void) { double x,y,z; printf("Enter a value for x, then a value for y: \n",); scanf("%d, %d", &x, 0x); z = _fyl2x(x,y); printf("%d * log2(%d) is %d.\n", x,y,z); } ═══ Related Information ═══ o _fyl2xp1 - Calculate y * log2(x + 1) o _f2xm1 - Calculate (2**x) - 1 o builtin.h ═══ 6.108. _fyl2xp1 - Calculate y * log2(x + 1) ═══ ═══ Format ═══ #include double _fyl2xp1(double x, double y); ═══ Description ═══ Language Level: Extension The _fyl2x function computes the base-2 logarithm of x+1 and multiplies it by y (y * log2(x+1)). The variable x must be in the range -(1-(sqrt(2)/2)) to (sqrt(2) - 1). This function provides improved accuracy over the _fyl2x function when computing logarithms of numbers very close to 1. When x is small, you can retain more significant digits by providing x to the _fyl2xp1 function than by providing x+1 as an argument to the _fyl2x function. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _fyl2xp1. o You cannot parenthesize a _fyl2xp1 function call, because parentheses specify a call to the backing code for the function in the library. This function returns the result of the formula y * log2(x+1). Example of _fyl2xp1 ═══ Example of _fyl2xp1 ═══ /************************************************************************ * This example calculates (y * log2(x + 1)), after prompting the user for values of x and y. * ************************************************************************/ #include #include #include int main(void) { double x,y,z; printf("Enter a value for x, then a value for y: \n",); scanf("%d, %d", &x, 0x); z = _fyl2xp1(x,y); printf("%d * log2(%d + 1) is %d.\n", x,y,z); } ═══ Related Information ═══ o _fyl2x - Calculate y * log2(x) o _f2xm1 - Calculate (2**x) - 1 o builtin.h ═══ 6.109. _f2xm1 - Calculate (2**x) - 1 ═══ ═══ Format ═══ #include double _f2xm1(double x); ═══ Description ═══ Language Level: Extension The _f2xm1 function calculates 2 raised to the power of x, minus 1 ((2**x)-1). The variable x must be in the range -1 to 1. This instruction is designed to produce very accurate results when x is close to 0. Large errors may occur for operands with magnitudes close to 1. You can exponentiate values other than 2 by using the formula x**y = 2**(y * log2(x)). Because it is a built-in function and has no backing code in the library: o You cannot take the address of _f2xm1. o You cannot parenthesize a _f2xm1 function call, because parentheses specify a call to the backing code for the function in the library. This function returns the value of the formula (2**x)-1. Example of _f2xm1 ═══ Example of _f2xm1 ═══ /************************************************************************ * This example calculates (2**x)-1 after prompting the user for a value for x. * ************************************************************************/ #include #include #include int main(void) { double x,y; printf("Enter a value for x: \n",); scanf("%d", &x); y = _f2xm1(x); printf("2**x - 1 is %d.\n", y); } ═══ Related Information ═══ o _fyl2x - Calculate y * log2(x) o _fyl2xp1 - Calculate y * log2(x + 1) o builtin.h ═══ 6.110. gamma - Gamma Function ═══ ═══ Format ═══ #include /* SAA extension to ANSI */ double gamma(double x); ═══ Description ═══ Language Level: SAA The gamma function computes ln( |G(x)| ). The argument x must be a positive real value. If x is a negative value, errno is set to EDOM. If the result causes an overflow, the function returns HUGE_VAL and sets errno to ERANGE. The C/C++ Tools compiler allows x to be a negative integer. Example of gamma ═══ Example of gamma ═══ /************************************************************************ * This example uses gamma to calculate ln(|G(x)|), where x = 42. * ************************************************************************/ #include #include int main(void) { double x=42, g_at_x; g_at_x = exp(gamma(x)); /* g_at_x = 3.345253e+49 */ printf ("The value of G(%4.2lf) is %7.2e\n", x, g_at_x); } /************************ Output should be similar to: ********** The value of G(42.00) is 3.35e+49 */ ═══ Related Information ═══ o Bessel Functions o erf - Calculate Error Functions o math.h ═══ 6.111. _gcvt - Convert Floating-Point to String ═══ ═══ Format ═══ #include char *_gcvt(double value, int ndec, char *buffer); ═══ Description ═══ Language Level: Extension The _gcvt function converts a floating-point value to a character string pointed to by buffer. The buffer should be large enough to hold the converted value and a null character (\0), that _gcvt automatically adds to the end of the string. There is no provision for overflow. The _gcvt function tries to produce ndec significant digits in FORTRAN F format. Failing that, it produces ndec significant digits in FORTRAN E format. Trailing zeros might be suppressed in the conversion if they are significant. A FORTRAN F number has the following format: ┌───────┐ ┌─────────┐ ──┬─────┬──digit─┴───.───┬───────┬┴────── ├──+──┤ └─digit─┘ └──-──┘ A FORTRAN E number has the following format: ┌───────┐ ┌──────────┐ ─┬─────┬─digits──.──digits─┴─E──┬─────┬─digits─┬────────┬┴─ ├──+──┤ ├──+──┤ └─digits─┘ └──-──┘ └──-──┘ The _gcvt function also converts NaN and infinity values to the strings NAN and INFINITY, respectively. For more information on NaN and infinity values, see Infinity and NaN Support. Warning: For each thread, the _ecvt, _fcvt and _gcvt functions use a single, dynamically allocated buffer for the conversion. Any subsequent call that the same thread makes to these functions destroys the result of the previous call. The _gcvt function returns a pointer to the string of digits. A failure to allocate memory returns an empty string and sets errno to ENOMEM. Example of _gcvt ═══ Example of _gcvt ═══ /************************************************************************ * This example converts the value -3.1415e3 to a character string and places it in the character array buffer1. It then converts the macro value _INF to a character string and places it in buffer2. * ************************************************************************/ #include #include #include /* for the definition of _INF */ int main(void) { char buffer1[10], buffer2[10]; _gcvt(-3.1415e3, 7, buffer1); printf("The first result is %s \n", buffer1); _gcvt(_INF, 5, buffer2); printf("The second result is %s \n", buffer2); return 0; /* The expected output is: The first result is -3141.5 The second result is INFINITY */ } ═══ Related Information ═══ o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o Infinity and NaN Support o stdlib.h ═══ 6.112. getc - Read a Character ═══ ═══ Format ═══ #include int getc(FILE *stream); int getchar(void); ═══ Description ═══ Language Level: ANSI, SAA The getc function reads a single character from the current stream position and advances the stream position to the next character. The getchar function is identical to getc(stdin). The difference between the getc and the fgetc functions is that the getc function can be implemented so that its arguments can be evaluated multiple times. The stream argument to getc should not be an expression with side effects. The getc and getchar functions return the character read. A return value of EOF indicates an error or end-of-file condition. Use ferror or feof to determine whether an error or an end-of-file condition occurred. Example of getc - getchar ═══ Example of getc - getchar ═══ /************************************************************************ * This example gets a line of input from the stdin stream. You can also use getc(stdin) instead of getchar() in the for statement to get a line of input from stdin. * ************************************************************************/ #include #define LINE 80 int main(void) { char buffer[LINE+1]; int i; int ch; printf( "Please enter string\n" ); /* Keep reading until either: 1. the length of LINE is exceeded or 2. the input character is EOF or 3. the input character is a new-line character */ for ( i = 0; ( i < LINE ) && (( ch = getchar()) != EOF) && ( ch !='\n' ); ++i ) buffer[i] = ch; buffer[i] = '\0'; /* a string should always end with '\0' ! */ printf( "The string is %s\n", buffer ); } /************************ Output should be similar to: ********** Please enter string hello world The string is hello world */ ═══ Related Information ═══ o fgetc - Read a Character o _fgetchar - Read Single Character from stdin o _getch - _getche - Read Character from Keyboard o putc - putchar - Write a Character o ungetc - Push Character onto Input Stream o gets - Read a Line o stdio.h ═══ 6.113. _getch - _getche - Read Character from Keyboard ═══ ═══ Format ═══ #include int _getch(void); int _getche(void); ═══ Description ═══ Language Level: Extension The _getch function reads a single character from the keyboard, without echoing. The _getche function reads a single character from the keyboard and displays the character read. Neither function can be used to read Ctrl-Break. When a program is reading a function key or cursor-moving key, the _getch and _getche functions must be called twice. The first call returns 0 or E0H, and the second call returns the particular extended key code. Example of _getch - _getche ═══ Example of _getch - _getche ═══ /************************************************************************ * This example gets characters from the keyboard until it finds the character 'x'. * ************************************************************************/ #include #include int main(void) { int ch; _cprintf("\nType in some letters."); printf("\n"); _cprintf("If you type in an 'x', the program ends.\n"); printf("\n"); for(;;) { ch = _getch(); if (ch == 'x') { _ungetch(ch); break; } _putch(ch); } ch=_getch(); printf("\n"); _cprintf("\nThe last character was '%c'.", ch); return 0; /************** The output should be similar to: ********************** Type in some letters. If you type in an 'x', the program ends. One Two Three Four Five Si The last character was 'x'. */ } ═══ Related Information ═══ o _cgets - Read String of Characters from Keyboard o fgetc - Read a Character o getc - Read a Character o _putch - Write Character to Screen o _ungetch - Push Character Back to Keyboard o conio.h ═══ 6.114. _getcwd - Get Path Name of Current Directory ═══ ═══ Format ═══ #include char *_getcwd(char *pathbuf, int n); ═══ Description ═══ Language Level: Extension The _getcwd function gets the full path name of the current working directory and stores it in the buffer pointed to by pathbuf. The integer argument n specifies the maximum length for the path name. An error occurs if the length of the path name, including the terminating null character, exceeds n characters. If the pathbuf argument is NULL, _getcwd uses malloc to reserve a buffer of at least n bytes to store the path name. If the current working directory string is more than n bytes, a large enough buffer will be allocated to contain the string. You can later free this buffer using the _getcwd return value as the argument to free. The _getcwd function returns pathbuf. If an error occurs, _getcwd returns NULL and sets errno to one of the following values: Value Meaning ENOMEM Not enough storage space available to reserve n bytes (when pathbuf argument is NULL). ERANGE The path name is longer than n characters. EOS2ERR An OS/2 call failed. Use _doserrno to obtain more information about the return code. Example of _getcwd ═══ Example of _getcwd ═══ /************************************************************************ * This example stores the name of the current working directory (up to _MAX_PATH characters) in a buffer. The value of _MAX_PATH is defined in . * ************************************************************************/ #include #include #include int main(void) { char buffer[_MAX_PATH]; if (_getcwd(buffer, _MAX_PATH) == NULL) perror("getcwd error"); printf("The current directory is %s\n", buffer); return 0; /**************** The output should be similar to: ******************** The current directory is E:\C_OS2\MIG_XMPS */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _fullpath - Get Full Path Name of Partial Path o _getdcwd - Get Full Path Name of Current Directory o _getdrive - Get Current Working Drive o malloc - Reserve Storage Block o direct.h ═══ 6.115. _getdcwd - Get Full Path Name of Current Directory ═══ ═══ Format ═══ #include char *_getdcwd(int drive, char *pathbuf, int n); ═══ Description ═══ Language Level: Extension The _getdcwd function gets the full path name for the current directory of the specified drive, and stores it in the location pointed to by pathbuf. The drive argument is an integer value representing the drive (A: is 1, B: is 2, and so on). The integer argument n specifies the maximum length for the path name. An error occurs if the length of the path name, including the terminating null character, exceeds n characters. If the pathbuf argument is NULL, _getdcwd uses malloc to reserve a buffer of at least n bytes to store the path name. If the current working directory string is more than n bytes, a large enough buffer will be allocated to contain the string. You can later free this buffer using the _getdcwd return value as the argument to free. An alternative to this function is the DosQueryCurrentDir and DosQueryCurrentDisk API calls. The _getdcwd function returns pathbuf. If an error occurs, _getdcwd returns NULL and sets errno to one of the following values: Value Meaning ENOMEM Not enough storage space available to reserve n bytes (when pathbuf argument is NULL). ERANGE The path name is longer than n characters. EOS2ERR An OS/2 call failed. Use _doserrno to obtain more information about the return code. Example of _getcwd ═══ Example of _getcwd ═══ /************************************************************************ * This example uses _getdcwd to obtain the current working directory of drive C. * ************************************************************************/ #include #include #include int main(void) { char *retBuffer; retBuffer = _getdcwd(3,NULL,0); if ( retBuffer == NULL ) printf("An error has occurred, errno is set to %d.\n", errno); else printf("Current working directory of drive C is %s.\n", retBuffer); return 0; /*************** The output should be similar to: ********************* Current working directory of drive C is C:\. */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _chdrive - Change Current Working Drive o _fullpath - Get Full Path Name of Partial Path o _getcwd - Get Path Name of Current Directory o _getdrive - Get Current Working Drive o malloc - Reserve Storage Block o direct.h ═══ 6.116. _getdrive - Get Current Working Drive ═══ ═══ Format ═══ #include int _getdrive(void); ═══ Description ═══ Language Level: Extension Gets the drive number for the current working drive. The _getdrive function returns an integer corresponding to alphabetical position of the letter representing the current working drive. For example, A: is 1, B: is 2, J: is 10, and so on. An alternative to this function is the DosQueryCurrentDisk API call. Example of _getdrive ═══ Example of _getdrive ═══ /************************************************************************ * This example gets and prints the current working drive number. * ************************************************************************/ #include #include int main(void) { printf("Current working drive is %d.\n", _getdrive() ); return 0; /******** If the current working drive is E:, then ************** *************** the output should be similar to: ********************** Current working drive is 5. */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _chdrive - Change Current Working Drive o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o direct.h ═══ 6.117. getenv - Search for Environment Variables ═══ ═══ Format ═══ #include char *getenv(const char *varname); ═══ Description ═══ Language Level: ANSI, SAA The getenv function searches the list of environment variables for an entry corresponding to varname. The getenv function returns a pointer to the environment table entry containing the current string value of varname. The return value is NULL if the given variable is not currently defined or if the system does not support environment variables. You should copy the string that is returned because it may be written over by a subsequent call to getenv. Example of getenv ═══ Example of getenv ═══ /************************************************************************ * In this example, pathvar points to the value of the PATH environment variable: * ************************************************************************/ #include int main(void) { char *pathvar; pathvar = getenv("PATH"); } ═══ Related Information ═══ o _putenv - Modify Environment Variables o envp Parameter to main o stdlib.h ═══ 6.118. _getpid - Get Process Identifier ═══ ═══ Format ═══ #include int _getpid(void); ═══ Description ═══ Language Level: Extension The _getpid function gets the process identifier that uniquely identifies the calling process. The _getpid function returns the process identifier as an integer value. There is no error return value. Example of _getpid ═══ Example of _getpid ═══ /************************************************************************ * This example prints the process identifier: * ************************************************************************/ #include #include #include #include int main(void) { printf("Process identifier is %d\n", _getpid()); return 0; /**************** The output should be similar to: ******************** Process identifier is 242 */ } ═══ Related Information ═══ o _cwait - Wait for Child Process o _execl - _execvp - Load and Run Child Process o _spawnl -_spawnvpe -Start and Run Child Processes o _wait - Wait for Child Process o process.h ═══ 6.119. gets - Read a Line ═══ ═══ Format ═══ #include char *gets(char *buffer); ═══ Description ═══ Language Level: ANSI, SAA The gets function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to and including the first new-line character (\n) or EOF. The gets function then replaces the new-line character, if read, with a null character (\0), before returning the line. If successful, the gets function returns its argument. A NULL pointer return value indicates an error or an end-of-file condition with no characters read. Use ferror or feof to determine which of these conditions occurred. If there is an error, the value stored in buffer is undefined. If an end-of-file condition occurs, buffer is not changed. Example of gets ═══ Example of gets ═══ /************************************************************************ * This example gets a line of input from stdin. * ************************************************************************/ #include #define MAX_LINE 100 int main(void) { char line[MAX_LINE]; char *result; if ((result = gets(line)) != NULL) { if (ferror(stdin)) perror("Error"); } } ═══ Related Information ═══ o _cgets - Read String of Characters from Keyboard o fgets - Read a String o feof - Test End-of-File Indicator o ferror - Test for Read/Write Errors o fputs - Print Strings o getc - Read a Character o puts - Write a String o stdio.h ═══ 6.120. _getTIBvalue - Get TIB Value ═══ ═══ Format ═══ #include unsigned long _getTIBvalue(const unsigned int offset); ═══ Description ═══ Language Level: Extension The _getTIBvalue function retrieves an unsigned long value from the thread information block (TIB) at the offset specified. The selector value for the TIB belonging to the current thread of execution is stored in the FS segment register. You should use the offsetof macro to calculate offset. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _getTIBvalue. o You cannot parenthesize a _getTIBvalue function call, because parentheses specify a call to the backing code for the function. This function returns an unsigned long value. There is no error return value and this function does not set errno. If offset is too large, it will cause an access violation when running the program. Example of _getTIBvalue ═══ Example of _getTIBvalue ═══ /************************************************************************ * This example prints out all the values in the TIB structure. * ************************************************************************/ #define INCL_DOSPROCESS #include #include #include int main( void ) { printf( "Values in Thread Information Block are:\n\n" ); printf( "Exception chain pointer: %lx\n", _getTIBvalue( offsetof( TIB, tib_pexchain ) ) ); printf( "Base stack address: %lx\n", _getTIBvalue( offsetof( TIB, tib_pstack ) ) ); printf( "End of stack address: %lx\n", _getTIBvalue( offsetof( TIB, tib_pstacklimit ) ) ); printf( "System specific TIB pointer: %p\n", _getTIBvalue( offsetof( TIB, tib_ptib2 ) ) ); printf( "Version number: %lu\n", _getTIBvalue( offsetof( TIB, tib_version ) ) ); printf( "Ordinal number: %lu\n", _getTIBvalue( offsetof( TIB, tib_ordinal ) ) ); return 0; } ═══ Related Information ═══ o _threadstore - Access Thread-Specific Storage o builtin.h ═══ 6.121. gmtime - Convert Time ═══ ═══ Format ═══ #include struct tm *gmtime(const time_t *time); ═══ Description ═══ Language Level: ANSI, SAA The gmtime function converts a time value to a struct tm. The value time is usually obtained from a call to time. The gmtime function breaks down the time value and stores it in a tm structure, defined in time.h. The structure pointed to by the return value reflects Coordinated Universal Time, not local time. The fields of the tm structure include: Field Value Stored tm_sec Seconds (0-61) tm_min Minutes (0-59) tm_hour Hours (0-23) tm_mday Day of month (1-31) tm_mon Month (0-11; January = 0) tm_year Year (current year minus 1900) tm_wday Day of week (0-6; Sunday = 0) tm_yday Day of year (0-365; January 1 = 0) tm_isdst Zero if Daylight Saving Time is not in effect; positive if Daylight Saving Time is in effect; negative if the information is not available. The gmtime function returns a pointer to the structure result. The gmtime function returns NULL if Coordinated Universal Time is not available. Note: 1. The range (0-61) for tm_sec allows for as many as two leap seconds. 2. The gmtime and localtime functions may use a common, statically allocated buffer for the conversion. Each call to one of these functions may alter the result of the previous call. 3. The time and date functions begin at 00:00:00 Coordinated Universal Time, January 1, 1970. Example of gmtime ═══ Example of gmtime ═══ /************************************************************************ * This example uses the gmtime function to adjust a time_t representation to a Coordinated Universal Time character string and then converts it to a printable string using asctime. * ************************************************************************/ #include #include int main(void) { time_t ltime; time(<ime); printf ("Coordinated Universal Time is %s\n", asctime(gmtime(<ime))); } /************************ Output should be similar to: ********** Coordinated Universal Time is Wed Aug 18 21:01:44 1993 */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o time - Determine Current Time o time.h ═══ 6.122. _heap_check - Validate Run-Time Storage Heap ═══ ═══ Format ═══ #define __DEBUG_ALLOC__ #include /* also defined in */ void *_heap_check(void); ═══ Description ═══ The _heap_check function checks all memory blocks allocated or freed by the debug memory management functions to make sure that overwriting has not occurred outside the bounds of allocated blocks and that free memory blocks have not been overwritten. The _heap_check function is automatically called whenever a debug function is called. You can also explicitly call _heap_check. Note: You should place calls to the _heap_check function throughout your code, especially in areas that may cause memory problems. There is no return value. For an explanation of how to interpret the output from _heap_check, see Sample _heap_check Output. Example of _heap_check ═══ Example of _heap_check ═══ /************************************************************************ * This example allocates 5000 bytes of storage, and then attempts to write to storage that was not allocated. The call to _heap_check detects the error, generates several messages, and stops the program. * ************************************************************************/ #ifndef __DEBUG_ALLOC__ /* this macro could also be defined */ #define __DEBUG_ALLOC__ /* from the command line */ #endif #include #include int main(void) { char *ptr; if (( ptr = malloc(5000) ) == NULL) { printf("Could not allocate memory block.\n"); return EXIT_FAILURE; } *(ptr - 1) = 'a'; /* overwrites storage that was not allocated */ _heap_check(); printf("_heap_check did not detect that a memory block was overwritten.\n"); return EXIT_FAILURE; /* Possible output is: Memory was overwritten before the allocated memory block that starts at address 0x00150010. The first eight bytes of the memory block (in hex) are: 0000000000000000. This memory block was (re)allocated at line number 11 in THPCHK.C. */ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _debug_free - Release Storage Blocks o _debug_heapmin - Release Unused Memory in the Heap o _debug_malloc - Reserve Storage Blocks o _debug_realloc - Change Reserved Storage Block Size o _dump_allocated - Get Information about Allocated Storage o Using the Debug Memory Management Functions o malloc.h o stdlib.h ═══ 6.123. _heapmin - Release Unused Memory in the Heap ═══ ═══ Format ═══ #include /* also defined in */ int _heapmin(void); ═══ Description ═══ Language Level: Extension The _heapmin function returns all unused memory from the runtime heap to the operating system. If successful, _heapmin returns 0; if not, it returns -1. Example of _heapmin ═══ Example of _heapmin ═══ /************************************************************************ * This example shows how to use the _heapmin function. * ************************************************************************/ #include #include int main(void) { if ( _heapmin() ) printf("_heapmin failed.\n"); else printf("_heapmin was successful.\n"); return 0; /* The expected output is: _heapmin was successful. */ } ═══ Related Information ═══ o _debug_heapmin - Release Unused Memory in the Heap o malloc.h o stdlib.h ═══ 6.124. hypot - Calculate Hypotenuse ═══ ═══ Format ═══ #include /* SAA extension to ANSI */ double hypot(double side1, double side2); ═══ Description ═══ Language Level: SAA The hypot function calculates the length of the hypotenuse of a right-angled triangle based on the lengths of two sides side1 and side2. A call to hypot is equal to: sqrt(side1 * side1 + side2 * side2); The hypot function returns the length of the hypotenuse. If an overflow results, the function sets errno to ERANGE and returns the value HUGE_VAL. Example of hypot ═══ Example of hypot ═══ /************************************************************************ * This example calculates the hypotenuse of a right-angled triangle with sides of 3.0 and 4.0. * ************************************************************************/ #include int main(void) { double x, y, z; x = 3.0; y = 4.0; z = hypot(x,y); printf("The hypotenuse of the triangle with sides %lf and %lf" " is %lf\n", x, y, z); } /******************** Output should be similar to: ************** The hypotenuse of the triangle with sides 3.000000 and 4.000000 is 5.000000 */ ═══ Related Information ═══ o _fsqrt - Calculate Square Root o sqrt - Calculate Square Root o math.h ═══ 6.125. _inp - Read Byte from Input Port ═══ ═══ Format ═══ #include /* Declared in both */ #include int _inp(const unsigned int port); ═══ Description ═══ Language Level: Extension The _inp function reads a byte from the specified input port. The port number must be an unsigned int value in the range 0 to 65 535 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _inp. o You cannot parenthesize an _inp function call, because parentheses specify a call to the backing code for the function. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. The _inp function returns the byte value as an integer that was read from the specified port. There is no error return value and this function does not set errno. Example of _inp ═══ Example of _inp ═══ /************************************************************************ * This example uses the _inp function to read a byte from a specified input port and return the data read. * ************************************************************************/ #include #define LOWER 0 #define UPPER 65535 int Add1(int j); int g; enum fruit {apples=10, bananas, cantalopes}; int arr[]={cantalopes, bananas, apples}; struct { int i; char ch; } st; int main(void) { int i; volatile const int c = 0; i = _inp(0); g = _inp(LOWER + 1); /* put the data read in a global variable */ i = _inp(apples); /* passing enumerated type as the */ /* port number */ /* =================================== */ /* Types of port number passed : */ /* ----------------------------------- */ i = _inp(c); /* - constant */ i = _inp(arr[c]); /* - element of array */ st.i = Add1(c); /* */ i = _inp(st.i); /* - element of structure */ i = _inp(Add1(LOWER)); /* - return value from a function call */ i = _inp(UPPER); /* - #define constant */ i = _inp(256); /* - the exact port number */ /* ----------------------------------- */ return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inpw - Read Unsigned Short from Input Port o _inpd - Read Double Word from Input Port o _outp - Write Byte to Output Port o _outpw - Write Word to Output Port o _outpd - Write Double Word to Output Port ═══ 6.126. _inpd - Read Double Word from Input Port ═══ ═══ Format ═══ #include /* Declared in both */ #include unsigned long _inpd(const unsigned int port); Language Level: Extension ═══ Description ═══ The _inpd function reads a 4-byte (double word) unsigned value from the specified input port. The port number must be an unsigned short value within the range 0 to 65 535 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _inpd. o You cannot parenthesize an _inpd function call, because parentheses specify a call to the backing code for the function. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. The _inpd function returns the unsigned long value that was read from the specified port. There is no error return value and this function does not set errno. Example of _inpd ═══ Example of _inpdx ═══ /************************************************************************ * This example uses the _inpd function to read a double-word value from the specified input port and return the data read. * ************************************************************************/ #include #define LOWER 0 #define UPPER 65535 int Add1(int j); static long g; enum fruit {apples=10, bananas, cantalopes}; int arr[]={cantalopes, bananas, apples}; union { int i; char ch; } un; int main(void) { unsigned long l; volatile const int c = 0; un.i = 65534; g = _inpd(255); /* put the data read in a global variable */ /* =========================== */ /* Types of port number passed:*/ /* --------------------------- */ l = _inpd(c); /* - constant */ l = _inpd(un.i); /* - element of union */ l = _inpd(Add1(cantalopes)); /* - return value from a */ /* function call */ l = _inpd(_inp(arr[Add1(LOWER)])); /* - return value from a */ /* builtin function call */ /* --------------------------- */ return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpw - Read Unsigned Short from Input Port o _outp - Write Byte to Output Port o _outpw - Write Word to Output Port o _outpd - Write Double Word to Output Port ═══ 6.127. _inpw - Read Unsigned Short from Input Port ═══ ═══ Format ═══ #include /* Declared in both */ #include unsigned short _inpw(const unsigned int port); ═══ Description ═══ Language Level: Extension The _inpw function reads an unsigned short value from the specified input port. The port number must be an unsigned short value within the range 0 to 65 535 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _inpw. o You cannot parenthesize an _inpw function call, because parentheses specify a call to the backing code for the function. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. This function returns the unsigned short value that was read from the specified port. There is no error return value and this function does not set errno. Example of _inpw ═══ Example of _inpw ═══ /************************************************************************ * This example uses the _inpw to read an unsigned short value from the specified input port and return the data read. * ************************************************************************/ #include #define LOWER 0 #define UPPER 65535 int Add1(int j); volatile short g; int main(void) { volatile unsigned short s; volatile const int c = 0; int i = 65534; enum fruit {apples, bananas, cantalopes}; int arr[] ={cantalopes, bananas, apples}; g = _inpw(LOWER); /* put the data read in a global variable */ s = _inpw(bananas); /* passing enumerated type */ /* as the port number */ /* =========================== */ /* Types of port number passed:*/ /* --------------------------- */ s = _inpw(c); /* - constant */ s = _inpw(i+1); /* - integer */ s = _inpw(arr[bananas]); /* - element of array */ s = _inpw(_outp(UPPER,cantalopes)); /* - return value from a */ /* builtin function call */ /* --------------------------- */ return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpd - Read Double Word from Input Port o _outp - Write Byte to Output Port o _outpw - Write Word to Output Port o _outpd - Write Double Word to Output Port o builtin.h o conio.h ═══ 6.128. _interrupt - Call Interrupt Procedure ═══ ═══ Format ═══ #include void _interrupt(const unsigned int intnum); Language Level: Extension ═══ Description ═══ The _interrupt function calls the interrupt procedure specified by intnum using the INT machine instruction. The integer intnum must have a value within the range 0 to 255 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _interrupt. o You cannot parenthesize an _interrupt function call, because parentheses specify a call to the backing code for the function. This function has no return value and it does not set errno. Example of _interrupt ═══ Example of _interrupt ═══ /************************************************************************ * This example shows how to call interrupt 3, which is a breakpoint. * ************************************************************************/ #include int main( void ) { /* A breakpoint will occur when running this program */ /* within a debugger. */ _interrupt(3); return 0; } ═══ Related Information ═══ o _disable - Disable Interrupts o _enable - Enable Interrupts ═══ 6.129. isalnum to isxdigit - Test Integer Value ═══ ═══ Format ═══ #include int isalnum(int c); /* Test for upper- or lowercase letters, or decimal digit */ int isalpha(int c); /* Test for alphabetic character */ int iscntrl(int c); /* Test for any control character */ int isdigit(int c); /* Test for decimal digit */ int isgraph(int c); /* Test for printable character excluding space */ int islower(int c); /* Test for lowercase */ int isprint(int c); /* Test for printable character including space */ int ispunct(int c); /* Test for any nonalphanumeric printable character */ /* excluding space */ int isspace(int c); /* Test for whitespace character */ int isupper(int c); /* Test for uppercase */ int isxdigit(int c); /* Test for hexadecimal digit */ ═══ Description ═══ Language Level: ANSI, SAA The functions listed test a given integer value. They return a nonzero value if the integer satisfies the test condition, or a zero value if it does not. c must be representable as an unsigned char. Note: EOF is a valid input value. Example of isalnum to isxdigit ═══ Example of isalnum to isxdigit ═══ /************************************************************************ * This example analyzes all characters between code 0x0 and code UPPER_LIMIT, printing A for alphabetic characters, AN for alphanumerics, U for uppercase, L for lowercase, D for digits, X for hexadecimal digits, S for spaces, PU for punctuation, PR for printable characters, G for graphics characters, and C for control characters. This example prints the code if printable. The output of this example is a 256-line table showing the characters from 0 to 255 that possess the attributes tested. * ************************************************************************/ #include #include #define UPPER_LIMIT 0xFF int main(void) { int ch; for ( ch = 0; ch <= UPPER_LIMIT; ++ch ) { printf("%3d ", ch); printf("%#04x ", ch); printf("%3s ", isalnum(ch) ? "AN" : " "); printf("%2s ", isalpha(ch) ? "A" : " "); printf("%2s", iscntrl(ch) ? "C" : " "); printf("%2s", isdigit(ch) ? "D" : " "); printf("%2s", isgraph(ch) ? "G" : " "); printf("%2s", islower(ch) ? "L" : " "); printf(" %c", isprint(ch) ? ch : ' '); printf("%3s", ispunct(ch) ? "PU" : " "); printf("%2s", isspace(ch) ? "S" : " "); printf("%3s", isprint(ch) ? "PR" : " "); printf("%2s", isupper(ch) ? "U" : " "); printf("%2s", isxdigit(ch) ? "X" : " "); putchar('\n'); } } ═══ Related Information ═══ o _isascii - Test Integer Values o _iscsym - _iscsymf - Test Integer o tolower - toupper - Convert Character Case o _toascii - _tolower - _toupper - Convert Character o ctype.h ═══ 6.130. _isascii - Test Integer Values ═══ ═══ Format ═══ #include int _isascii(int c); Language Level: Extension ═══ Description ═══ The _isascii macro tests if an integer is within the ASCII range. This macro assumes that the system uses the ASCII character set. The _isascii macro returns a nonzero value if the integer is within the ASCII set, and 0 if it is not. Language Level: Extension Example of _isascii ═══ Example of _isascii ═══ /************************************************************************ * This example tests the integers from 0x7c to 0x82, and prints the corresponding ASCII character if the integer is within the ASCII range. * ************************************************************************/ #include #include int main(void) { int ch; for (ch = 0x7c; ch <= 0x82; ch++) { printf("%#04x ", ch); if (isascii(ch)) printf("The ASCII character is %c\n", ch); else printf("Not an ASCII character\n"); } return 0; /**************** The output should be similar to: ******************** 0x7c The ASCII character is | 0x7d The ASCII character is } 0x7e The ASCII character is ~ 0x7f The ASCII character is  0x80 Not an ASCII character 0x81 Not an ASCII character 0x82 Not an ASCII character */ } ═══ Related Information ═══ o isalnum to isxdigit - Test Integer Value o _iscsym - _iscsymf - Test Integer o _toascii - _tolower - _toupper - Convert Character o tolower - toupper - Convert Character Case o ctype.h ═══ 6.131. _isatty - Test Handle for Character Device ═══ ═══ Format ═══ #include int _isatty(int handle); ═══ Description ═══ Language Level: Extension The _isatty function determines whether the given handle is associated with a character device (a keyboard, display, printer or serial port). The _isatty function returns a nonzero value if the device is a character device. Otherwise, the return value is 0. Example of _isatty ═══ Example of _isatty ═══ /************************************************************************ * This example opens the console and tries to determine if it is a character device: * ************************************************************************/ #include #include #include #include int main(void) { int fh, result; if (-1 == (fh = _open("CON", O_RDWR,(S_IREAD | S_IWRITE)))) { perror("Error opening console\n"); return 1; } result = _isatty(fh) ; if (0 != result) printf("CON is a character device.\n"); else printf("CON is not a character device.\n"); _close (fh); return 0; /******************** The expected output is: ************************* CON is a character device. */ } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpd - Read Double Word from Input Port o _inpw - Read Unsigned Short from Input Port o _outp - Write Byte to Output Port o _outpd - Write Double Word to Output Port o _outpw - Write Word to Output Port o io.h ═══ 6.132. _iscsym - _iscsymf - Test Integer ═══ ═══ Format ═══ #include int _iscsym(int c); int _iscsymf(int c); ═══ Description ═══ Language Level: Extension These macros test if an integer is within a particular ASCII set. The macros assume that the system uses the ASCII character set. The _iscsymf macro tests if a character is alphabetic or an underscore (_). The _iscsym macro tests if a character is alphabetic, a digit, or an underscore. The _iscsym and _iscsymf macros return a nonzero value if the integer is within the ASCII set for which it tests, and 0 otherwise. Example of _iscsym - _iscsymf ═══ Example of _iscsym - _iscsymf ═══ /************************************************************************ * This example uses _iscsym and _iscsymf to test the characters a, _, and 1. If the character falls within the ASCII set tested for, the macro returns TRUE. Otherwise, it returns FALSE. * ************************************************************************/ #include #include int main(void) { int ch[3] = {'a', '_', '1'}; int i; for (i = 0; i < 3; i++) { printf("_iscsym('%c') returns %s\n", ch[i], _iscsym(ch[i]) ? "TRUE" : "FALSE"); printf("_iscsymf('%c') returns %s\n\n", ch[i], _iscsymf(ch[i]) ? "TRUE" : "FALSE"); } return 0; /****************** The output should be similar to: ****************** _iscsym('a') returns TRUE _iscsymf('a') returns TRUE _iscsym('_') returns TRUE _iscsymf('_') returns TRUE _iscsym('1') returns TRUE _iscsymf('1') returns FALSE */ } ═══ Related Information ═══ o isalnum to isxdigit - Test Integer Value o _isascii - Test Integer Values o tolower - toupper - Convert Character Case o _toascii - _tolower - _toupper - Convert Character o ctype.h ═══ 6.133. _itoa - Convert Integer to String ═══ ═══ Format ═══ #include char *_itoa(int value, char * string, int radix); ═══ Description ═══ Language Level: Extension The _itoa function converts the digits of the given value to a character string that ends with a null character and stores the result in string. The radix argument specifies the base of value; it must be in the range 2 to 36. If radix equals 10 and value is negative, the first character of the stored string is the minus sign (-). Note: The space reserved for string must be large enough to hold the returned string. The function can return up to 33 bytes including the null character (\0). The _itoa function returns a pointer to string. There is no error return value. Example of _itoa ═══ Example of _itoa ═══ /************************************************************************ * This example converts the integer value -255 to a decimal, a binary, and a hex number, storing its character representation in the array buffer. * ************************************************************************/ #include #include int main(void) { char buffer[35]; char *p; p = _itoa(-255, buffer, 10); printf("The result of _itoa(-255) with radix of 10 is %s\n", p); p = _itoa(-255, buffer, 2); printf("The result of _itoa(-255) with radix of 2\n is %s\n", p); p = _itoa(-255, buffer, 16); printf("The result of _itoa(-255) with radix of 16 is %s\n", p); return 0; /* The expected output is: The result of _itoa(-255) with radix of 10 is -255 The result of _itoa(-255) with radix of 2 is 11111111111111111111111100000001 The result of _itoa(-255) with radix of 16 is ffffff01 */ } ═══ Related Information ═══ o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o _ltoa - Convert Long Integer to String o _ultoa - Convert Unsigned Long Integer to String o stdlib.h ═══ 6.134. _kbhit - Test for Keystroke ═══ ═══ Format ═══ include int _kbhit(void); ═══ Description ═══ Language Level: Extension The _kbhit function tests if a key has been pressed on the keyboard. If the result is nonzero, a keystroke is waiting in the buffer. You can get the keystroke using the _getch or _getche function. If you call _getch or _getche without first calling _kbhit, the program waits for a key to be pressed. The _kbhit function returns a nonzero value if a key has been pressed. Otherwise, it returns 0. Example of _kbhit ═══ Example of _kbhit ═══ /************************************************************************ * This example uses _kbhit to test for the pressing of a key on the keyboard and to print a statement with the result of the test. * ************************************************************************/ #include #include int main(void) { int ch; printf("Type in some letters.\n"); printf("If you type in an 'x', the program ends.\n"); for (;;) { while (_kbhit() == 0) { /* Processing without waiting for a key to be pressed */ } ch = _getch(); printf("You have pressed the '%c' key.\n",ch); if (ch == 'x') break; } return 0; /******************* Possible output: ******************************** Type in some letters. If you type in an 'x', the program ends. You have pressed the 'f' key. You have pressed the 'e' key. You have pressed the 'l' key. You have pressed the 'i' key. You have pressed the 'x' key. *********************** Program ends ********************************/ } ═══ Related Information ═══ o _getch - _getche - Read Character from Keyboard o conio.h ═══ 6.135. labs - Calculate long Absolute Value ═══ ═══ Format ═══ #include long int labs(long int n); ═══ Description ═══ Language Level: ANSI, SAA The labs function produces the absolute value of its long integer argument n. The result may be undefined when the argument is equal to LONG_MIN, the smallest available long integer (-2 147 483 647). The value LONG_MIN is defined in the include file. There is no return value. Example of labs ═══ Example of labs ═══ /************************************************************************ * This example computes y as the absolute value of the long integer -41567. * ************************************************************************/ #include #include int main(void) { long x, y; x = -41567L; y = labs(x); printf("The absolute value of %ld is %ld\n", x, y); } /******************** Output should be similar to: ************** The absolute value of -41567 is 41567 */ ═══ Related Information ═══ o abs - Calculate Integer Absolute Value o _cabs - Calculate Absolute Value of Complex Number o fabs - Calculate Floating-Point Absolute Value o limits.h ═══ 6.136. ldexp - Multiply by a Power of Two ═══ ═══ Format ═══ #include double ldexp(double x, int exp); ═══ Description ═══ Language Level: ANSI, SAA The ldexp function calculates the value of x * (2**exp). If an overflow results, the function returns +HUGE_VAL for a large result or -HUGE_VAL for a small result, and sets errno to ERANGE. Example of ldexp ═══ Example of ldexp ═══ /************************************************************************ * This example computes y as 1.5 times 2 to the fifth power (1.5 * (2**5)): * ************************************************************************/ #include int main(void) { double x, y; int p; x = 1.5; p = 5; y = ldexp(x,p); printf("%lf times 2 to the power of %d is %lf\n", x, p, y); } /******************** Output should be similar to: ************** 1.500000 times 2 to the power of 5 is 48.000000 */ ═══ Related Information ═══ o frexp - Separate Floating-Point Value o modf - Separate Floating-Point Value o math.h ═══ 6.137. ldiv - Long Division ═══ ═══ Format ═══ #include ldiv_t ldiv(long int numerator, long int denominator); ═══ Description ═══ Language Level: ANSI, SAA The ldiv function calculates the quotient and remainder of the division of numerator by denominator. The ldiv function returns a structure of type ldiv_t, containing both the quotient long int quot and the remainder long int rem. If the value cannot be represented, the return value is undefined. If denominator is 0, an exception is raised. Example of ldiv ═══ Example of ldiv ═══ /************************************************************************ * This example uses the ldiv function to calculate the quotients and remainders for a set of two dividends and two divisors. * ************************************************************************/ #include #include int main(void) { long int num[2] = {45,-45}; long int den[2] = {7,-7}; ldiv_t ans; /* ldiv_t is a struct type containing two long ints: 'quot' stores quotient; 'rem' stores remainder */ short i,j; printf("Results of long division:\n"); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) { ans = ldiv(num[i], den[j]); printf("Dividend: %6ld Divisor: %6ld", num[i], den[j]); printf(" Quotient: %6ld Remainder: %6ld\n", ans.quot, ans.rem); } } /******************** Expected output: ************************** Results of long division: Dividend: 45 Divisor: 7 Quotient: 6 Remainder: 3 Dividend: 45 Divisor: -7 Quotient: -6 Remainder: 3 Dividend: -45 Divisor: 7 Quotient: -6 Remainder: -3 Dividend: -45 Divisor: -7 Quotient: 6 Remainder: -3 */ ═══ Related Information ═══ o div - Calculate Quotient and Remainder o stdlib.h ═══ 6.138. _lfind - _lsearch - Find Key in Array ═══ ═══ Format ═══ #include char *_lfind(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*)(const void *key, const void *compare)); char *_lsearch(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*)(const void *key, const void *compare)); ═══ Description ═══ Language Level: Extension The _lfind and _lsearch functions perform a linear search for the value search_key in an array of num elements, each of width bytes in size. Unlike bsearch, _lsearch and _lfind do not require that you sort the array first. The argument base points to the base of the array to be searched. If _lsearch does not find the search_key, it adds the search_key to the end of the array and increments num by one. If _lfind does not find the search_key, it does not add the search_key to the array. The argument compare is a pointer to a function that you supply. This function compares the specified key with an array element and returns a value specifying their relationship. Both _lsearch and _lfind call the compare function one or more times during the search, passing pointers to two array elements on each call. The compare argument is returned as one of the following values: Value Meaning Nonzero key and element are different. 0 key and element are identical. If the search_key is found, both _lsearch and _lfind return a pointer to that element of the array to which base points. If the search_key is not found, _lsearch returns a pointer to a newly added item at the end of the array, while _lfind returns NULL. Example of _lfind ═══ Example of _lfind ═══ /************************************************************************ * This example uses the _lfind function to search for the keyword PATH in the command-line arguments. * ************************************************************************/ #include #include #include #define CNT 2 /* Must declare 'compare' as a function */ int compare(const void *, const void *); int main(void) { char **result; char *key = "PATH"; unsigned int num = CNT; char *string[CNT] = { "PATH = d:\\david\\heather\\ed\\simon", "LIB = PATH\\abc" }; /* The following statement finds the argument that starts with "PATH" */ if ((result = (char **)_lfind((char *)&key, (char *)string, &num, sizeof(char *), compare)) != NULL) printf("%s found\n", *result); else printf("PATH not found \n"); return 0; } /* The following is a sample 'compare' function */ int compare(const void *arg1, const void *arg2) { return(strncmp(*(char **)arg1, *(char **)arg2, strlen(*(char **)arg1))); } /***************** The output should be similar to: ******************* PATH = d:\david\heather\ed\simon found */ ═══ Related Information ═══ o bsearch - Search Arrays o qsort - Sort Array o search.h ═══ 6.139. _loadmod - Load User DLL ═══ ═══ Format ═══ #include int _loadmod(char *module_name, unsigned long *module_handle); ═══ Description ═══ Language Level: Extension The _loadmod function loads a user-created dynamic link library (DLL) for the calling process. The module_name is the name of the DLL to be loaded, and the module_handle is the file handle associated with the DLL. If the operation is successful, _loadmod returns the handle of the loaded DLL to the calling process. The process can use this handle with the OS/2 API DosQueryProcAddr to get the address of the required function from within the DLL. Once the reference is established, the calling process can then call the specific function. The return value of _loadmod is 0 if the DLL was successfully loaded. If unsuccessful, _loadmod returns -1, and sets errno to one of the following values: Value Meaning EMODNAME The specified module_name is not valid. EOS2ERR A system error occurred. Check _doserrno for the specific OS/2 error code. Example of _loadmod ═══ Example of _loadmod ═══ /************************************************************************ * In this example, _loadmod loads the DLL mark and gets the address of the function PLUS within the DLL. It then calls that function, which adds two integers passed to it. The types PFN and APIRET, are required to use the OS/2 DosQueryProcAddr API, and are defined by including the header file. Note: To run this program, you must first create mark.dll. Copy the code for the PLUS function into a file called mark.c, and the code for the .DEF file into mark.def. Eliminate the comments from these two files. Compile with the command: icc /Ge- mark.c mark.def You can then run the example: * ************************************************************************/ #define INCL_DOS #include #include #include /* This is the code for MARK.DEF LIBRARY MARK PROTMODE EXPORTS PLUS */ /* This is the code for PLUS function in the DLL #pragma linkage( PLUS, system ) int PLUS( int a, int b ) { return a + b; } */ int main(void) { int x = 4, y = 7; unsigned long handle; char * modname = "MARK" ; /* DLL name */ char * fname = "PLUS" ; /* function name */ PFN faddr; /* pointer to function */ APIRET rc; /* return code */ /* from DosQueryProcAddr */ /* dynamically load the 'mark' DLL */ if (_loadmod(modname, &handle) ) { printf("Error loading module %s\n", modname ); exit (-1); } /* get function address from DLL */ rc = DosQueryProcAddr( handle, 0, fname, &faddr ); if (rc == 0) printf("Calling the function from the %s DLL to add %d and %d\n", modname,x,y); printf("The result of the function call is %d\n", faddr(x,y)); else { printf("Error locating address of function %s\n", fname); _freemod( handle ); exit(-1); } if( _freemod( handle )) { printf("Error in freeing the %s DLL module\n", modname); exit(-1); } printf("Reference to the %s DLL module has been freed\n", modname); return 0; /************** The expected output is ******************** Calling the function from the DLL to add 4 and 7 The result of the function call is 11 Reference to the MARK DLL module has been freed */ } ═══ Related Information ═══ o _freemod - Free User DLL o stdlib.h ═══ 6.140. localeconv - Query Locale Conventions ═══ ═══ Format ═══ #include struct lconv *localeconv(void); ═══ Description ═══ Language Level: ANSI, SAA The localeconv function sets the components of a structure having type struct lconv to values appropriate for the current locale. The structure may be overwritten by another call to localeconv or by calling setlocale and passing LC_ALL, LC_MONETARY, or LC_NUMERIC. The structure contains the following elements (defaults shown are for the C locale): ELEMENT PURPOSE OF ELEMENT DEFAULT "char *decimal_point" Decimal-point character used to format "." nonmonetary quantities. "char *thousands_sep" Character used to separate groups of "" digits to the left of the decimal-point character in formatted nonmonetary quan- tities. "char *grouping" String indicating the size of each group "" of digits in formatted nonmonetary quan- tities. The value of each character in the string determines the number of digits in a group. A value of "CHAR_MAX" indicates that there are no further groupings. "0" indicates that the previous element is to be used for the remainder of the digits. "char International currency symbol for the "" *int_curr_symbol" current locale. The first three charac- ters contain the alphabetic interna- tional currency symbol. The fourth character (usually a space) is the char- acter used to separate the international currency symbol from the monetary quan- tity. "char Local currency symbol of the current "" *currency_symbol" locale. "char Separator for digits in formatted mone- "" *mon_thousands_sep" tary quantities. "char *mon_grouping" String indicating the size of each group "" of digits in formatted monetary quanti- ties. The value of each character in the string determines the number of digits in a group. A value of "CHAR_MAX" indicates that there are no further groupings. "0" indicates that the previous element is to be used for the remainder of the digits. "char *positive_sign" String indicating the positive sign used "" in monetary quantities. "char *negative_sign" String indicating the negative sign used "" in monetary quantities. "char int_frac_digits" The number of displayed digits to the "UCHAR_MAX" right of the decimal place for interna- tionally formatted monetary quantities. "char frac_digits" Number of digits to the right of the "UCHAR_MAX" decimal place in monetary quantities. "char p_cs_precedes" 1 if the "currency_symbol" precedes the "UCHAR_MAX" value for a nonnegative formatted mone- tary quantity; "0" if it does not. "char p_sep_by_space" 1 if the "currency_symbol" is separated "UCHAR_MAX" by a space from the value of a nonnega- tive formatted monetary quantity; "0" if it does not. "char n_cs_precedes" 1 if the "currency_symbol" precedes the "UCHAR_MAX" value for a negative formatted monetary quantity; "0" if it does not. "char n_sep_by_space" 1 if the "currency_symbol" is separated "UCHAR_MAX" by a space from the value of a negative formatted monetary quantity; "0" if it does not. "char p_sign_posn" Value indicating the position of the "UCHAR_MAX" "positive_sign" for a nonnegative for- matted monetary quantity. "char n_sign_posn" Value indicating the position of the "UCHAR_MAX" "negative_sign" for a negative formatted monetary quantity. The n_sign_posn and p_sign_posn elements can have the following values: Value Meaning 0 The quantity and currency_symbol are enclosed in parentheses. 1 The sign precedes the quantity and currency_symbol. 2 The sign follows the quantity and currency_symbol. 3 The sign precedes the currency_symbol. 4 The sign follows the currency_symbol. The localeconv function returns a pointer to the structure. Example of localeconv ═══ Example of localeconv ═══ /************************************************************************ * This example prints out the default decimal point for your locale and then the decimal point for the LC_C_FRANCE locale. * ************************************************************************/ #include #include int main(void) { char * string; struct lconv * mylocale; mylocale = localeconv(); /* Default decimal point */ printf( "Default decimal point is a %s\n", mylocale->decimal_point ); string = setlocale(LC_ALL, LC_C_FRANCE ); mylocale = localeconv(); /* A comma is set to be the decimal point when the locale is LC_C_FRANCE */ printf( "France's decimal point is a %s\n", mylocale->decimal_point ); } /******************** Output should be similar to: ************** Default decimal point is a . France's decimal point is a , */ ═══ Related Information ═══ o setlocale - Set Locale o locale.h ═══ 6.141. localtime - Convert Time ═══ ═══ Format ═══ #include struct tm *localtime(const time_t *timeval); ═══ Description ═══ Language Level: ANSI, SAA The localtime function converts a time value stored as a time_t value to a structure. The time value is usually obtained by a call to the time function. The localtime function breaks down the timeval value, corrects for the local time zone and Daylight Saving Time, if appropriate, and stores the corrected time in a structure of type tm. See gmtime for a description of the fields in a tm structure. The localtime function returns a pointer to the structure result. There is no error return value. Note: 1. The gmtime and localtime functions may use a common, statically allocated buffer for the conversion. Each call to one of these functions may alter the result of the previous call. 2. The time and date functions begin at 00:00:00 Coordinated Universal Time, January 1, 1970. Example of localtime ═══ Example of localtime ═══ /************************************************************************ * This example queries the system clock and displays the local time. * ************************************************************************/ #include #include int main(void) { struct tm *newtime; time_t ltime; time(<ime); newtime = localtime(<ime); printf("The date and time is %s", asctime(newtime)); } /************** If the local time is 3:00 p.m. May 31, 1993, ********** ************************* output should be: ********************* The date and time is Mon May 31 15:00:00 1993 */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o mktime - Convert Local Time o time - Determine Current Time o time.h ═══ 6.142. log - Calculate Natural Logarithm ═══ ═══ Format ═══ #include double log(double x); ═══ Description ═══ Language Level: ANSI, SAA The log function calculates the natural logarithm (base e) of x. The log function returns the computed value. If x is negative, it will set errno to EDOM and may return the value -HUGE_VAL. If x is zero, log returns the value -HUGE_VAL, and may set errno to ERANGE. Example of log ═══ Example of log ═══ /************************************************************************ * This example calculates the natural logarithm of 1000.0. * ************************************************************************/ #include #include int main(void) { double x = 1000.0, y; y = log(x); printf("The natural logarithm of %lf is %lf\n", x, y); } /******************** Output should be similar to: ************** The natural logarithm of 1000.000000 is 6.907755 */ ═══ Related Information ═══ o exp - Exponential Function o log10 - Calculate Base 10 Logarithm o pow - Compute Power o math.h ═══ 6.143. log10 - Calculate Base 10 Logarithm ═══ ═══ Format ═══ #include double log10(double x); ═══ Description ═══ Language Level: ANSI, SAA The log10 function calculates the base 10 logarithm of x. The log10 function returns the computed value. If x is negative, it will set errno to EDOM and may return the value -HUGE_VAL. If x is zero, log10 returns the value -HUGE_VAL, and may set errno to ERANGE. Example of log10 ═══ Example of log10 ═══ /************************************************************************ * This example calculates the base 10 logarithm of 1000.0. * ************************************************************************/ #include #include int main(void) { double x = 1000.0, y; y = log10(x); printf("The base 10 logarithm of %lf is %lf\n", x, y); } /******************** Output should be similar to: ************** The base 10 logarithm of 1000.000000 is 3.000000 */ ═══ Relative Information ═══ o exp - Exponential Function o log - Calculate Natural Logarithm o pow - Compute Power o math.h ═══ 6.144. longjmp - Restore Stack Environment ═══ ═══ Format ═══ #include void longjmp(jmp_buf env, int value); ═══ Description ═══ Language Level: ANSI, SAA The longjmp function restores a stack environment previously saved in env by setjmp. The setjmp macro and longjmp function provide a way to perform a nonlocal goto. They are often used in signal handlers. A call to setjmp causes the current stack environment to be saved in env. A subsequent call to longjmp restores the saved environment and returns control to a point in the program corresponding to the setjmp call. Execution resumes as if the setjmp call had just returned the given value. All variables (except register variables) that are accessible to the function that receives control contain the values they had when longjmp was called. The values of register variables are unpredictable. Nonvolatile auto variables that are changed between calls to setjmp and longjmp are also unpredictable. Note: Ensure that the function that calls setjmp does not return before you call the corresponding longjmp function. Calling longjmp after the function calling setjmp returns causes unpredictable program behavior. The value argument passed to longjmp must be nonzero. If you give a zero argument for value, longjmp substitutes a 1 in its place. The longjmp function does not use the normal function call and return mechanisms; it has no return value. Example of longjmp ═══ Example of longjmp ═══ /************************************************************************ * This example provides for saving the stack environment at the statement: if(setjmp(mark) != 0) ... When the system first performs the if statement, it saves the environment in mark and sets the condition to FALSE because setjmp returns a 0 when it saves the environment. The program prints the message: setjmp has been called The subsequent call to function p tests for a local error condition, which can cause it to perform the longjmp function. Then, control returns to the original setjmp function using the environment saved in mark. This time the condition is TRUE because -1 is the return value from the longjmp function. The example then performs the statements in the block and prints: longjmp has been called It then performs the recover function and leaves the program. * ************************************************************************/ #include #include jmp_buf mark; void p(void); void recover(void); int main(void) { if (setjmp(mark) != 0) { printf("longjmp has been called\n"); recover(); exit(1); } printf("setjmp has been called\n"); . . . p(); . . . } void p(void) { int error = 0; . . . error = 9; . . . if (error != 0) longjmp(mark, -1); . . . } void recover(void) { . . . } ═══ Related Information ═══ o setjmp - Preserve Environment o goto o volatile and const Qualifiers o auto Storage Class Specifier o setjmp.h ═══ 6.145. _lrotl - _lrotr - Rotate Bits ═══ ═══ Format ═══ #include unsigned long _lrotl(unsigned long value, int shift); unsigned long _lrotr(unsigned long value, int shift); ═══ Description ═══ Language Level: Extension These functions rotate value by shift bits. The _lrotl function rotates to the left, and _lrotr to the right. Both functions return the rotated value. There is no error return value. Example of _lrotl - _lrotr ═══ Example of _lrotl - _lrotr ═══ /************************************************************************ * This example uses _lrotl and _lrotr with different shift values to rotate the long integer value 0x01234567: * ************************************************************************/ #include #include int main(void) { unsigned long val = 0X01234567; printf("The value of 0x%8.8lx rotated 4 bits to the left is 0x%8.8lx\n", val, _lrotl(val, 4)); printf("The value of 0x%8.8lx rotated 16 bits to the right is 0x%8.8lx\n", val, _lrotr(val, 16)); return 0; /************* The output should be similar to: *********************** The value of 0x01234567 rotated 4 bits to the left is 0x12345670 The value of 0x01234567 rotated 16 bits to the right is 0x45670123 */ } ═══ Related Information ═══ o _rotl - _rotr - Bit Rotation o stdlib.h ═══ 6.146. _lseek - Move File Pointer ═══ ═══ Format ═══ #include #include long _lseek(int handle, long offset, int origin); ═══ Description ═══ Language Level: Extension The _lseek function moves any file pointer associated with handle to a new location that is offset bytes from the origin. The next operation on the file takes place at the new location. Origin must be one of the following constants, defined in : Origin Definition SEEK_SET Beginning of file SEEK_CUR Current position of file pointer SEEK_END End of file. The _lseek function can reposition the pointer anywhere in a file. The pointer can also be positioned beyond the end of the file; the data between the eof and the new file position is undefined. (See _chsize - Alter Length of File for more information on extending the length of the file.) However, an attempt to position the pointer before the beginning of the file causes an error. The _lseek function returns the offset, in bytes, of the new position from the beginning of the file. A return value of -1L indicates an error, and errno is set to one of the following values: Value Meaning EBADF The file handle is incorrect. EINVAL The value for origin is incorrect, or the position specified by offset is before the beginning of the file. EOS2ERR The call to the operating system was not successful. On devices incapable of seeking (such as keyboards and printers), the return value is -1, and errno is set to EOS2ERR. Example of _lseek ═══ Example of _lseek ═══ /************************************************************************ * This example opens the file sample.dat and if successful, moves the file pointer to the eighth position in the file. The example then attempts to read bytes from the file, starting at the new pointer position, and reads them into the buffer. * ************************************************************************/ #include #include #include #include #include int main(void) { long length; int fh; char buffer[20]; memset(buffer,'\0',20); /* Initialize the buffer */ printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { perror("Unable to open sample.dat."); _exit(1); } if ( -1 == _lseek(fh,7,SEEK_SET) ) /* place the file pointer at the */ { /* eighth position in the file */ perror("Unable to _lseek"); _close(fh); return 1; } if (8 != _read(fh,buffer,8)) { perror("Unable to read from sample.dat."); _close(fh); return 1; } printf("Successfully read in the following:\n%s\n ",buffer); _close(fh); return 0; /*********** The expected output is: ***************** Creating sample.dat. Successfully read in the following: Program */ } ═══ Related Information ═══ o _chsize - Alter Length of File o fseek - Reposition File Position o _tell - Get Pointer Position o io.h o stdio.h ═══ 6.147. _ltoa - Convert Long Integer to String ═══ ═══ Format ═══ #include char *_ltoa(long value, char *string, int radix); ═══ Description ═══ Language Level: Extension The _ltoa function converts the digits of the given long integer value to a character string that ends with a null character and stores the result in string. The radix argument specifies the base of value; it must be in the range 2 to 36. If radix equals 10 and value is negative, the first character of the stored string is the minus sign (-). Note: The space allocated for string must be large enough to hold the returned string. The function can return up to 33 bytes including the null character (\0). The _ltoa function returns a pointer to string. There is no error return value. Example of _ltoa ═══ Example of _ltoa ═══ /************************************************************************ * This example converts the long integer -255L to a decimal, binary, and hex value, and stores its character representation in the array buffer. * ************************************************************************/ #include #include int main(void) { char buffer[35]; char *p; p = _ltoa(-255L, buffer, 10); printf("The result of _ltoa(-255) with radix of 10 is %s\n", p); p = _ltoa(-255L, buffer, 2); printf("The result of _ltoa(-255) with radix of 2\n is %s\n", p); p = _ltoa(-255L, buffer, 16); printf("The result of _ltoa(-255) with radix of 16 is %s\n", p); return 0; /* The expected output is: The result of _ltoa(-255) with radix of 10 is -255 The result of _ltoa(-255) with radix of 2 is 11111111111111111111111100000001 The result of _ltoa(-255) with radix of 16 is ffffff01 */ } ═══ Related Information ═══ o atol - Convert Character Strings o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o _itoa - Convert Integer to String o _ultoa - Convert Unsigned Long Integer to String o stdlib.h ═══ 6.148. _makepath - Create Path ═══ ═══ Format ═══ #include void _makepath(char *path, char *drive, char *dir, char *fname, char *ext); ═══ Description ═══ Language Level: Extension The _makepath function creates a single path name, composed of a drive letter, directory path, file name, and file name extension. The path argument should point to an empty buffer large enough to hold the complete path name. The constant _MAX_PATH, defined in , specifies the maximum size allowed for path. The other arguments point to the following buffers containing the path name elements: Buffer Description drive Contains a letter (A, B, ...) corresponding to the desired drive and an optional following colon. The _makepath routine inserts the colon automatically in the composite path name if it is missing. If drive is a null character or an empty string, no drive letter or colon appears in the composite path string. dir Contains the path of directories, not including the drive designator or the actual file name. The trailing slash is optional, and either slash (/) or backslash (\) or both can be used in a single dir argument. If a trailing slash or backslash (/ or \) is not specified, it is inserted automatically. If dir is a null character or an empty string, no slash is inserted in the composite path string. fname Contains the base file name without any extensions. ext Contains the actual file name extension, with or without a leading period. The _makepath function inserts the period automatically if it does not appear in ext. If ext is a null character or an empty string, no period is inserted in the composite path string. The size limits on the above four fields are those specified by the constants _MAX_DRIVE, _MAX_DIR, _MAX_FNAME, and _MAX_EXT, which are defined in . The composite path should be no larger than the _MAX_PATH constant also defined in ; otherwise, the operating system does not handle it correctly. Note: No checking is done to see if the syntax of the file name is correct. There is no return value. Example of _makepath ═══ Example of _makepath ═══ /************************************************************************ * This example builds a file name path from the specified components: * ************************************************************************/ #include #include int main(void) { char path_buffer [_MAX_PATH]; char drive [_MAX_DRIVE]; char dir [_MAX_DIR]; char fname [_MAX_FNAME]; char ext [_MAX_EXT]; _makepath (path_buffer, "c", "qc\\bob\\eclibref\\e", "makepath", "c"); printf ("Path created with _makepath: %s\n\n", path_buffer); _splitpath (path_buffer, drive, dir, fname, ext); printf ("Path extracted with _splitpath:\n"); printf ("drive: %s\n", drive); printf ("directory: %s\n", dir); printf ("file name: %s\n", fname); printf ("extension: %s\n", ext); return 0; /************ The output should be similar to: ******** Path created with _makepath: c:qc\bob\eclibref\e\makepath.c Path extracted with _splitpath: drive: c: directory: qc\bob\eclibref\e\ file name: makepath extension: .c */ } ═══ Related Information ═══ o _fullpath - Get Full Path Name of Partial Path o _splitpath - Decompose Path Name o stdlib.h ═══ 6.149. malloc - Reserve Storage Block ═══ ═══ Format ═══ #include /* also defined in */ void *malloc(size_t size); ═══ Description ═══ Language Level: ANSI, SAA, Extension The malloc function reserves a block of storage of size bytes. Unlike the calloc function, malloc does not necessarily give all the bits of each element an initial value of 0. The malloc function returns a pointer to the reserved space. The storage space to which the return value points is guaranteed to be suitably aligned for storage of any type of object. The return value is NULL if there is not enough storage available, or if size was specified as zero. Example of malloc ═══ Example of malloc ═══ /************************************************************************ * This example prompts for the number of array entries you want and then reserves enough space in storage for the entries. If malloc was successful, the example assigns values to the entries and prints out each entry; otherwise, it prints out an error. * ************************************************************************/ #include #include int main(void) { long * array; /* start of the array */ long * index; /* index variable */ int i; /* index variable */ int num; /* number of entries of the array */ printf( "Enter the size of the array\n" ); scanf( "%i", &num ); /* allocate num entries */ if ( (index = array = malloc( num * sizeof( long ))) != NULL ) { for ( i = 0; i < num; ++i ) /* put values in array */ *index++ = i; /* using pointer notation */ for ( i = 0; i < num; ++i ) /* print the array out */ printf( "array[ %i ] = %i\n", i, array[i] ); } else { /* malloc error */ perror( "Out of storage" ); abort(); } } /******************** Output should be similar to: ************** Enter the size of the array array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2 array[ 3 ] = 3 array[ 4 ] = 4 */ ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o _debug_malloc - Reserve Storage Blocks o free - Release Storage Blocks o _msize - Return Number of Bytes Allocated o realloc - Change Reserved Storage Block Size o _tmalloc - Reserve Tiled Storage Block o malloc.h o stdlib.h ═══ 6.150. _matherr - Process Math Library Errors ═══ ═══ Format ═══ #include int _matherr(struct exception *x); ═══ Description ═══ Language Level: Extension You can use the _matherr function to process errors generated by the functions in the math library. The math functions call _matherr whenever they detect an error. The _matherr function supplied with the C/C++ Tools library performs no error handling and returns 0 to the calling function. You can provide a different definition of the _matherr function to carry out special error handling. Be sure to use the /NOE link option, if you are using your own _matherr function. For the C/C++ Tools compiler, you can use the /B option on the icc command line to pass the /NOE option to the linker, as in the following: icc /B"/NOE" yourfile.c When an error occurs in a math routine, _matherr is called with a pointer to the following structure (defined in ) as an argument: struct exception { int type; char *name; double arg1, arg2, retval; }; The type variable specifies the type of math error. It is one of the following values, defined in : Value Meaning DOMAIN Argument domain error OVERFLOW Overflow range error UNDERFLOW Underflow range error TLOSS Total loss of significance PLOSS Partial loss of significance SING Argument singularity. Because PLOSS is used by the C/2 compiler, it is provided to prevent errors during compiling. The C/C++ Tools compiler does not actually generate this value. The name is a pointer to a null-ended string containing the name of the function that caused the error. The arg1 and arg2 variables specify the argument values that caused the error. If only one argument is given, it is stored in arg1. The retval is the default return value; you can change the return value. The return value from _matherr must specify whether or not an error actually occurred. If _matherr returns 0, an error message appears, and errno is set to an appropriate error value. If _matherr returns a nonzero value, no error message appears and errno remains unchanged. Example of _matherr ═══ Example of _matherr ═══ /************************************************************************ * This example is a definition that you can create to handle errors from the log or log10 functions. The arguments to these logarithmic functions must be positive double values. This routine processes a negative value in an argument (a domain error) by returning the log of its absolute value. It suppresses the error message normally displayed when this error occurs. If the error is a zero argument or if some other routine produced the error, the example takes the default actions. * ************************************************************************/ /* */ /* Note: Use "icc /B"/NOE" yourfile.c" to compile */ /* and link this example. */ /* */ #include #include #include int main(void) { int value; printf("Trying to evaluate log10(-1000.00) will create a math exception.\n"); value = log10(-1000.00); printf("The _matherr() exception handler evaluates the expression to\n"); printf("log10(-1000.00) = %d\n", value); return 0; } int _matherr(struct exception *x) { printf("inside _matherr\n"); if (x->type == DOMAIN) { if (strcmp(x->name, "log") == 0) { x->retval = log(-(x->arg1)); return(1); } else if (strcmp(x->name, "log10") == 0) { x->retval = log10(-(x->arg1)); return(1); } } return 0; /* Use default actions */ /******************** The output should be similar to: **************** Trying to evaluate log10(-1000.00) will create a math exception. inside _matherr The _matherr() exception handler evaluates the expression to log10(-1000.00) = 3 */ } ═══ Related Information ═══ o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o math.h ═══ 6.151. max - Return Larger of Two Values ═══ ═══ Format ═══ #include type max(type a, type b); ═══ Description ═══ Language Level: Extension The max macro compares two values and determines the larger of the two. The data type can be any arithmetic data type, signed or unsigned. Both arguments must have the same type for each call to max. Note: Because max is a macro, if the evaluation of the arguments contains side effects (post-increment operators, for example), the results of both the side effects and the macro will be undefined. The max macro returns the larger of the two values. Example of max ═══ Example of max ═══ /************************************************************************ * This example prints the larger of the two values, a and b. * ************************************************************************/ #include #include int main (void) { int a = 10; int b = 21; printf ("The larger of %d and %d is %d\n", a, b, max(a, b)); return 0; /* The expected output is: The larger of 10 and 21 is 21 */ } ═══ Related Information ═══ o min - Return Lesser of Two Values o stdlib.h ═══ 6.152. mblen - Multibyte String Length ═══ ═══ Format ═══ #include int mblen(const char *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA The mblen function determines the length in bytes of the multibyte character pointed to by string. A maximum of n bytes is examined. If string is NULL, the mblen function returns: o Nonzero when DBCS-host code (EBCDIC systems) is used o Zero otherwise. If string is not NULL, the mblen function returns: o Zero if string points to the null character o The number of bytes comprising the multibyte character o -1 if string does not point to a valid multibyte character. Example of mblen ═══ Example of mblen ═══ /************************************************************************ * This example uses mblen and mbtowc to convert a multibyte character into a single wide character. * ************************************************************************/ #include #include int length, temp; char string [6] = "w"; wchar_t arr[6]; int main(void) { /* Set string to point to a multibyte character */ . . . length = mblen(string, MB_CUR_MAX); temp = mbtowc(arr,string,length); printf("wide character string: %ls",arr); } ═══ Related Infromation ═══ o mbtowc - Convert Multibyte Character to wchar_t o mbstowcs - Convert Multibyte Characters to wchar_t Characters o strlen - Determine String Length o wcslen - Calculate Length of wchar_t String o wctomb - Convert wchar_t Character to Multibyte Character o stdlib.h ═══ 6.153. mbstowcs - Convert Multibyte Characters to wchar_t Characters ═══ ═══ Format ═══ #include size_t mbstowcs(wchar_t *pwc, const char *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA The mbstowcs function determines the length of the sequence of the multibyte characters pointed to by string. It then stores the code for the sequence of multibyte characters in the wchar_t object pointed to by pwc. A maximum of n wchar_t characters is examined. The mbstowcs function returns the number of wchar_t characters generated not including any terminating zero codes. If a multibyte character that is not valid is encountered, the function returns (size_t)-1. Example of mbstowcs ═══ Example of mbstowcs ═══ /************************************************************************ * This example uses mblen and mbstowcs to convert a multibyte character string into a wide character string. * ************************************************************************/ #include #include int length, temp; char string [80]; wchar_t arr[80]; int main(void) { /* Set string to point to a multibyte character string. */ . . . length = mblen(string, MB_CUR_MAX); temp = mbstowcs(arr,string,length); printf("wide character string: %ls",arr); } ═══ Related Information ═══ o mblen - Multibyte String Length o mbtowc - Convert Multibyte Character to wchar_t o wcslen - Calculate Length of wchar_t String o wcstombs - Convert wchar_t String to Multibyte Character String o stdlib.h ═══ 6.154. mbtowc - Convert Multibyte Character to wchar_t ═══ ═══ Format ═══ #include int mbtowc(wchar_t *pwc, const char *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA The mbtowc function first determines the length of the multibyte character pointed to by string. It then stores the code for the multibyte character in the wchar_t object pointed to by pwc. A maximum of n bytes is examined. If string is NULL, the mbtowc function returns: o Nonzero when DBCS-host code (EBCDIC systems) is used o 0 otherwise. If string is not NULL, the mbtowc function returns: o 0 if string points to the null character o The number of bytes comprising the converted multibyte character o -1 if string does not point to a valid multibyte character. Example of mbtowc ═══ Example of mbtowc ═══ /************************************************************************ * This example uses mblen and mbtowc to convert a multibyte character into a single wide character. * ************************************************************************/ #include #include int length, temp; char string [6]; wchar_t arr[6]; int main(void) { /* Set string to point to a multibyte character. */ . . . length = mblen(string, MB_CUR_MAX); temp = mbtowc(arr,string,length); printf("wide character string: %ls",arr); } ═══ Related Information ═══ o mblen - Multibyte String Length o mbstowcs - Convert Multibyte Characters to wchar_t Characters o wcslen - Calculate Length of wchar_t String o wctomb - Convert wchar_t Character to Multibyte Character o stdlib.h ═══ 6.155. memccpy - Copy Bytes ═══ ═══ Format ═══ #include /* also defined in */ void *memccpy(void *dest, void *src, int c, unsigned cnt); ═══ Description ═══ Language Level: Extension The memccpy function copies bytes from src to dest up to and including the first occurrence of the character c or until cnt bytes have been copied, whichever comes first. If the character c is copied, memccpy returns a pointer to the byte in dest that immediately follows the character. If c is not copied, memccpy returns NULL. ) Example of memccpy ═══ Example of memccpy ═══ /************************************************************************ * This example copies up to 55 characters, or until it copies the '.' character, from the source to the buffer. * ************************************************************************/ #include #include #include char source[60]; char result[60]; int main(void) { memcpy(source,"This is the string. This part won't be copied.", 55); if (memccpy(result, source, '.', 55) == NULL) { printf("Error in copying source.\n"); exit(1); } else printf("%s\n", result); return 0; /* The expected output is: This is the string. */ } ═══ Related Information ═══ o memchr - Search Buffer o memcmp - Compare Buffers o memcpy - Copy Bytes o memmove - Copy Bytes o memset - Set Bytes to Value o memory.h o string.h ═══ 6.156. memchr - Search Buffer ═══ ═══ Format ═══ #include /* also defined in */ void *memchr(const void *buf, int c, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, Extension The memchr function searches the first count bytes of buf for the first occurrence of c converted to an unsigned character. The search continues until it finds c or examines count bytes. The memchr function returns a pointer to the location of c in buf. It returns NULL if c is not within the first count bytes of buf. Example of memchr ═══ Example of memchr ═══ /************************************************************************ * This example finds the first occurrence of "x" in the string that you provide. If it is found, the string that starts with that character is printed. * ************************************************************************/ #include #include int main(int argc, char ** argv) { char * result; if ( argc != 2 ) printf( "Usage: %s string\n", argv[0] ); else { if ((result = memchr( argv[1], 'x', strlen(argv[1])) ) != NULL) printf( "The string starting with x is %s\n", result ); else printf( "The letter x cannot be found in the string\n" ); } } /******************** Output should be similar to: ************** The string starting with x is xing */ ═══ Related Information ═══ o memccpy - Copy Bytes o memicmp - Compare Bytes o memmove - Copy Bytes o memset - Set Bytes to Value o strchr - Search for Character o memory.h o string.h ═══ 6.157. memcmp - Compare Buffers ═══ ═══ Format ═══ #include /* also defined in */ int memcmp(const void *buf1, const void *buf2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, Extension The memcmp function compares the first count bytes of buf1 and buf2 and returns a value indicating their relationship as follows: Value Meaning Less than 0 buf1 less than buf2 0 buf1 identical to buf2 Greater than 0 buf1 greater than buf2 Example of memcmp ═══ Example of memcmp ═══ /************************************************************************ * This example compares first and second arguments passed to main to determine which, if either, is greater. * ************************************************************************/ #include #include int main(int argc, char ** argv) { int len; int result; if ( argc != 3 ) { printf( "Usage: %s string1 string2\n", argv[0] ); } else { /* Determine the length to be used for comparison */ if (strlen( argv[1] ) < strlen( argv[2] )) len = strlen( argv[1] ); else len = strlen( argv[2] ); result = memcmp( argv[1], argv[2], len ); printf( "When the first %i characters are compared,\n", len ); if ( result == 0 ) printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] ); else if ( result < 0 ) printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] ); else printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] ); } } /**************** If the program is passed the arguments ************** ************* firststring and secondstring, ***** ******************** output should be: ************************* When the first 11 characters are compared, "firststring" is less than "secondstring" */ ═══ Related Information ═══ o memccpy - Copy Bytes o memchr - Search Buffer o memcpy - Copy Bytes o memicmp - Compare Bytes o memmove - Copy Bytes o memset - Set Bytes to Value o strcmp - Compare Strings o memory.h o string.h ═══ 6.158. memcpy - Copy Bytes ═══ ═══ Format ═══ #include /* also defined in */ void *memcpy(void *dest, const void *src, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, Extension The memcpy function copies count bytes of src to dest. For memcpy, the behavior is undefined if copying takes place between objects that overlap. (The memmove function allows copying between objects that may overlap.) The memcpy function returns a pointer to dest. Example of memcpy ═══ Example of memcpy ═══ /************************************************************************ * This example copies the contents of source to target. * ************************************************************************/ #include #include #define MAX_LEN 80 char source[ MAX_LEN ] = "This is the source string"; char target[ MAX_LEN ] = "This is the target string"; int main(void) { printf( "Before memcpy, target is \"%s\"\n", target ); memcpy( target, source, sizeof(source)); printf( "After memcpy, target becomes \"%s\"\n", target ); } /********************* Expected output: ************************ Before memcpy, target is "This is the target string" After memcpy, target becomes "This is the source string" */ ═══ Related Information ═══ o memccpy - Copy Bytes o memchr - Search Buffer o memcmp - Compare Buffers o memicmp - Compare Bytes o memmove - Copy Bytes o strcpy - Copy Strings o memory.h o string.h ═══ 6.159. memicmp - Compare Bytes ═══ ═══ Format ═══ #include /* Also defined in */ int memicmp(void *buf1, void *buf2, unsigned int cnt); ═══ Description ═══ Language Level: Extension The memicmp function compares the first cnt bytes of buf1 and buf2 without regard to the case of letters in the two buffers. The function converts all uppercase characters into lowercase and then performs the comparison. The return value of memicmp indicates the result as follows: Value Meaning Less than 0 buf1 less than buf2 0 buf1 identical to buf2 Greater than 0 buf1 greater than buf2. Example of memicmp ═══ Example of memicmp ═══ /************************************************************************ * This example copies two strings that each contain a substring of 29 characters that are the same except for case. The example then compares the first 29 bytes without regard to case. * ************************************************************************/ #include #include char first[100], second[100]; int main(void) { int result; strcpy(first, "Those Who Will Not Learn From History"); strcpy(second,"THOSE WHO WILL NOT LEARN FROM their mistakes"); printf("Comparing the first 29 characters of two strings.\n"); result = memicmp(first, second, 29); printf("The first 29 characters of String 1 are "); if (result < 0) printf("less than String 2.\n"); else if (result == 0) printf("equal to String 2.\n"); else printf("greater than String 2.\n"); return 0; /* The expected output is: Comparing the first 29 characters of two strings. The first 29 characters of String 1 are equal to String 2 */ } ═══ Related Information ═══ o memchr - Search Buffer o memcmp - Compare Buffers o memcpy - Copy Bytes o memmove - Copy Bytes o memset - Set Bytes to Value o memory.h o string.h ═══ 6.160. memmove - Copy Bytes ═══ ═══ Format ═══ #include /* also defined in */ void *memmove(void *dest, const void *src, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, Extension The memmove function copies count bytes of src to dest. The memmove function allows copying between objects that may overlap as if src is first copied into a temporary array. The memmove function returns a pointer to dest. Example of memmove ═══ Example of memmove ═══ /************************************************************************ * This example copies the word shiny from position target + 2 to position target + 8. * ************************************************************************/ #include #include #define SIZE 21 char target[SIZE] = "a shiny white sphere"; int main( void ) { char * p = target + 8; /* p points at the starting character of the word we want to replace */ char * source = target + 2; /* start of "shiny" */ printf( "Before memmove, target is \"%s\"\n", target ); memmove( p, source, 5 ); printf( "After memmove, target becomes \"%s\"\n", target ); } /********************* Expected output: ************************ Before memmove, target is "a shiny white sphere" After memmove, target becomes "a shiny shiny sphere" */ ═══ Related Information ═══ o memccpy - Copy Bytes o memchr - Search Buffer o memcmp - Compare Buffers o memcpy - Copy Bytes o memicmp - Compare Bytes o memset - Set Bytes to Value o strcpy - Copy Strings o memory.h o string.h ═══ 6.161. memset - Set Bytes to Value ═══ ═══ Format ═══ #include /* also defined in */ void *memset(void *dest, int c, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, Extension The memset function sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character. The memset function returns a pointer to dest. Example of memset ═══ Example of memset ═══ /************************************************************************ * This example sets 10 bytes of the buffer to "A" and the next 10 bytes to "B". * ************************************************************************/ #include #include #define BUF_SIZE 20 int main(void) { char buffer[BUF_SIZE + 1]; char *string; memset(buffer, 0, sizeof(buffer)); string = memset(buffer,'A', 10); printf("\nBuffer contents: %s\n", string); memset(buffer+10, 'B', 10); printf("\nBuffer contents: %s\n", buffer); } /******************* Output should be similar to: *************** Buffer contents: AAAAAAAAAA Buffer contents: AAAAAAAAAABBBBBBBBBB */ ═══ Related Information ═══ o memccpy - Copy Bytes o memcpy - Copy Bytes o memicmp - Compare Bytes o memmove - Copy Bytes o memory.h o strnset - strset - Set Characters in String o string.h ═══ 6.162. min - Return Lesser of Two Values ═══ ═══ Format ═══ #include type min(type a, type b); ═══ Description ═══ Language Level: Extension The min macro compares two values and determines the smaller of the two. The data type can be any arithmetic data type, signed or unsigned. The type must be the same for both arguments to min. Note: Because min is a macro, if the evaluation of the arguments contains side effects (post-increment operators, for example), the results of both the side effects and the macro will be undefined. The min macro returns the smaller of the two values. Example of min ═══ Example of min ═══ /************************************************************************ * This example prints the smaller of the two values, a and b. * ************************************************************************/ #include #include int main(void) { int a = 10; int b = 21; printf ("The smaller of %d and %d is %d\n", a, b, min (a, b)); return 0; /* The expected output is: The smaller of 10 and 21 is 10 */ } ═══ Related Information ═══ o max - Return Larger of Two Values o stdlib.h ═══ 6.163. _mkdir - Create New Directory ═══ ═══ Format ═══ #include int _mkdir(char *pathname); ═══ Description ═══ Language Level: Extension The _mkdir function creates a new directory with the specified pathname. Because only one directory can be created at a time, only the last component of pathname can name a new directory. The _mkdir function returns the value 0 if the directory was created. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS The directory was not created; the given name is the name of an existing file, directory, or device. ENOENT The pathname was not found. Example of _mkdir ═══ Example of _mkdir ═══ /************************************************************************ * This example creates two new directories: one at the root on drive B:, and one in the tmp subdirectory of the current working directory. * ************************************************************************/ #include #include #include int main(void) { char *dir1, *dir2; /* Create the directory "aleng" in the root directory of the C: drive. */ dir1 = "c:\\aleng"; if ((_mkdir(dir1)) == 0) printf("%s directory was created.\n",dir1); else printf("%s directory was not created.\n",dir1); /* Create the subdirectory "simon" in the current directory. */ dir2 = "simon"; if ((_mkdir(dir2)) == 0) printf("%s directory was created.\n",dir2); else printf("%s directory was not created.\n",dir2); /* Remove the directory "aleng" from the root directory of the C: drive. */ printf("Removing directory 'aleng' from the root directory.\n"); if (_rmdir(dir1)) perror(NULL); else printf("%s directory was removed.\n",dir1); /* Remove the subdirectory "simon" from the current directory. */ printf("Removing subdirectory 'simon' from the current directory.\n"); if (_rmdir(dir2)) perror(NULL); else printf("%s directory was removed.\n",dir2); return 0; /*************** The output should be similar to: ******************** c:\aleng directory was created. simon directory was created. Removing directory 'aleng' from the root directory. c:\aleng directory was removed. Removing subdirectory 'simon' from the current directory. simon directory was removed. */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _rmdir - Remove Directory o direct.h ═══ 6.164. mktime - Convert Local Time ═══ ═══ Format ═══ #include time_t mktime(struct tm *time); ═══ Description ═══ Language Level: ANSI, SAA The mktime function converts local time, stored as a structure pointed to by time, into a time_t structure suitable for use with other time functions. The values of some structure elements pointed to by time are not restricted to the ranges shown on gmtime. The values of tm_wday and tm_yday passed to mktime are ignored and are assigned their correct values on return. The mktime function returns the calendar time having type time_t. The value (time_t)(-1) is returned if the calendar time cannot be represented. Note: The time and date functions begin at 00:00:00 Coordinated Universal Time, January 1, 1970. Example of mktime ═══ Example of mktime ═══ /************************************************************************ * This example prints the day of the week that is 40 days and 16 hours from the current date. * ************************************************************************/ #include #include char *wday[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int main(void) { time_t t1, t3; struct tm *t2; t1 = time(NULL); t2 = localtime(&t1); t2 -> tm_mday += 40; t2 -> tm_hour += 16; t3 = mktime(t2); printf("40 days and 16 hours from now, it will be a %s \n", wday[t2 -> tm_wday]); } /******************* Output should be similar to: *************** 40 days and 16 hours from now, it will be a Sunday */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o time - Determine Current Time o time.h ═══ 6.165. modf - Separate Floating-Point Value ═══ ═══ Format ═══ #include double modf(double x, double *intptr); ═══ Description ═══ Language Level: ANSI, SAA The modf function breaks down the floating-point value x into fractional and integral parts. The signed fractional portion of x is returned. The integer portion is stored as a double value pointed to by intptr. Both the fractional and integral parts are given the same sign as x. Example of modf ═══ Example of modf ═══ /************************************************************************ * This example breaks the floating-point number -14.876 into its fractional and integral components. * ************************************************************************/ #include #include int main(void) { double x, y, d; x = -14.876; y = modf(x, &d); printf("x = %lf\n", x); printf("Integral part = %lf\n", d); printf("Fractional part = %lf\n", y); } /**************** Output should be similar to: ****************** x = -14.876000 Integral part = -14.000000 Fractional part = -0.876000 */ ═══ Related Information ═══ o fmod - Floating-Point Remainder o frexp - Separate Floating-Point Value o ldexp - Multiply by a Power of Two o math.h ═══ 6.166. _msize - Return Number of Bytes Allocated ═══ ═══ Format ═══ #include or ##include size_t _msize(void *ptr) ═══ Description ═══ Language Level: Extension The _msize function returns the number of bytes that were allocated to the pointer argument passed. This function requires a pointer that was returned from any of the calloc, malloc, realloc, _tcalloc, _tmalloc, and _trealloc functions. You cannot pass the argument of an object that has been freed. The _msize function returns the number of bytes allocated. If the argument is not a valid pointer returned from the malloc, calloc, and realloc functions, the return value is undefined. If NULL is passed, _msize returns 0. Example of _msize ═══ Example of _msize ═══ /************************************************************************ * This example displays the size of an allocated object from malloc. * ************************************************************************/ #include #include int main(void) { char *myptr; /* allocate an object */ myptr = malloc(5); printf("The size of the allocated object is %u\n",_msize(myptr)); return(0); /************** The output should be: **************************** The size of the allocated object is 5 */ } ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o malloc - Reserve Storage Block o realloc - Change Reserved Storage Block Size o _tcalloc - Reserve Tiled Storage Block o _tmalloc - Reserve Tiled Storage Block o _trealloc - Reallocate Tiled Storage Block o malloc.h o stdlib.h ═══ 6.167. _onexit - Record Termination Function ═══ ═══ Format ═══ #include onexit_t _onexit(onexit_t func); ═══ Description ═══ Language Level: Extension The _onexit function records the address of a function func to call when the program ends normally. Successive calls to _onexit create a stack of functions that run in a last-in, first-out order. The functions passed to _onexit cannot take parameters. You can record up to 32 termination functions with calls to _onexit and atexit. If you exceed 32 functions, _onexit returns the value NULL. Note: For portability, use the ANSI-standard atexit function, which is equivalent to _onexit. If successful, _onexit returns a pointer to the function; otherwise, it returns a NULL value. Example of _onexit ═══ Example of _onexit ═══ /************************************************************************ * This example specifies and defines four distinct functions that run consecutively at the completion of main: * ************************************************************************/ #include #include int fn1(void) { printf("next.\n"); } int fn2(void) { printf("run "); } int fn3(void) { printf("is "); } int fn4(void) { printf("This "); } int main(void) { _onexit(fn1); _onexit(fn2); _onexit(fn3); _onexit(fn4); printf("This is run first.\n"); return 0; /***************** The output should be similar to: ******************* This is run first. This is run next. */ } ═══ Related Information ═══ o abort - Stop a Program o atexit - Record Program Termination Function o exit - End Program o _exit - End Process o stdlib.h ═══ 6.168. _open - Open File ═══ ═══ Format ═══ #include #include #include int _open(char *pathname, int oflag, int pmode); ═══ Description ═══ Language Level: Extension The _open function opens the file specified by pathname and prepares the file for subsequent reading or writing as defined by oflag. The _open function can also prepare the file for reading and writing. The oflag is an integer expression formed by combining one or more of the following constants, defined in . When more than one constant is given, the constants are joined with the bitwise OR operator (|). Oflag Meaning O_APPEND Reposition the file pointer to the end of the file before every write operation. O_CREAT Create and open a new file. This flag has no effect if the file specified by pathname exists. O_EXCL Return an error value if the file specified by pathname exists. This flag applies only when used with O_CREAT. O_RDONLY Open the file for reading only. If this flag is given, neither O_RDWR nor O_WRONLY can be given. O_RDWR Open the file for reading and writing. If this flag is given, neither O_RDONLY nor O_WRONLY can be given. O_TRUNC Open and truncate an existing file to 0 length. The file must have write permission. The contents of the file are destroyed, and O_TRUNC cannot be specified with O_RDONLY. O_WRONLY Open the file for writing only. If this flag is given, neither O_RDONLY nor O_RDWR can be given. O_BINARY Open the file in binary (untranslated) mode. (See fopen.) O_TEXT Open the file in text (translated) mode. (See fopen.) If neither O_BINARY or O_TEXT is specified, the default will be O_TEXT; it is an error to specify both O_BINARY and O_TEXT. You must specify one of the access mode flags, O_RDONLY, O_WRONLY, or O_RDWR. There is no default. Warning: Use O_TRUNC with care; it destroys the complete contents of an existing file. The pmode argument is an integer expression containing one or both of the constants S_IWRITE and S_IREAD, defined in . The pmode is required only when O_CREAT is specified. If the file exists, pmode is ignored. Otherwise, pmode specifies the permission settings for the file. These are set when the new file is closed for the first time. The meaning of the pmode argument is as follows: Value Meaning S_IWRITE Writing permitted S_IREAD Reading permitted S_IREAD | S_IWRITE Reading and writing permitted. If write permission is not given, the file is read-only. Under the OS/2 operating system, all files are readable; you cannot give write-only permission. The modes S_IWRITE and S_IREAD | S_IWRITE are equivalent. The _open function applies the current file permission mask to pmode before setting the permissions. (See _umask - Sets File Mask of Current Process). The _open function returns a file handle for the opened file. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS The given pathname is a directory; or the file is read-only but an open for writing was attempted; or a sharing violation occurred. EEXIST The O_CREAT and O_EXCL flags are specified, but the named file already exists. EMFILE No more file handles are available. EINVAL An incorrect argument was passed. ENOENT The file or pathname were not found. EOS2ERR The call to the operating system was not successful. Example of _open ═══ Example of _open ═══ /************************************************************************ * This example tries to open the file edopen.dat by creating it as a new file, truncating it if it exists and opening it so it can be read and written to. The _open command issued also grants permission to read from and write to the file. * ************************************************************************/ #include #include #include #include int main(void) { int fh; if ( -1 == (fh = _open("edopen.dat", O_CREAT | O_TRUNC | O_RDWR, S_IREAD | S_IWRITE))) { perror("Unable to open edopen.dat"); return 1; } printf("File was successfully opened.\n"); if (-1 == _close(fh)) { perror("close error"); return 1; } return 0; /* The expected ouptut is: File was successfully opened. */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _creat - Create New File o _fdopen - Associates Input Or Output With File o fopen - Open Files o _sopen - Open Shared File o _umask - Sets File Mask of Current Process o fcntl.h o io.h o sys\stat.h ═══ 6.169. _outp - Write Byte to Output Port ═══ ═══ Format ═══ #include /* Declared in both */ #include int _outp( const unsigned int port, const int value ); ═══ Description ═══ Language Level: Extension The _outp function writes a byte value to the specified port. The port number must be an unsigned int value within the range 0 to 65 535 inclusive. The byte value must be within the range 0 to 255 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _outp. o You cannot parenthesize an _outp function call, because parentheses specify a call to the backing code for the function. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. The _outp function returns the integer value that was output to the specified port. There is no error return value and this function does not set errno. Example of _outp ═══ Example of _outp ═══ /************************************************************************ * This example uses the _outp function to write a byte to a specified output port and return the data written. * ************************************************************************/ #include #define LOWER 0 #define UPPER1 255 #define UPPER2 65535 int Add1(int j); static int g; enum fruit {apples=10, bananas, cantalopes}; enum fruit f = cantalopes; int arr[]={cantalopes, bananas, apples}; struct { int i; char ch; } st; int main(void) { static int i; volatile const int c = 0; st.i = c - bananas; g = _outp(LOWER,apples); i = _outp(255, 0); /* ============================= */ /* Types of port number passed : */ /* ----------------------------- */ i = _outp(UPPER2,UPPER1); /* - #define constant */ i = _outp(st.i, bananas); /* - element of structure */ i = _outp(f,arr[1]); /* - enumerated variable */ i = _outp(_inp(arr[2]),apples); /* - return value from a */ /* builtin function call */ /* ----------------------------- */ i = _outp(_outp(apples,Add1(LOWER)),6); return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpw - Read Unsigned Short from Input Port o _inpd - Read Double Word from Input Port o _outpw - Write Word to Output Port o _outpd - Write Double Word to Output Port ═══ 6.170. _outpd - Write Double Word to Output Port ═══ ═══ Format ═══ #include /* Declared in both */ #include unsigned long _outpd( const unsigned int port, const unsigned long value ); ═══ Description ═══ Language Level: Extension The _outpd function writes an unsigned long value to the specified port. The port number must be a value within the range 0 to 65 535 inclusive. The unsigned long value must be within the range 0 to 4 294 967 295 inclusive. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _outpd. o You cannot parenthesize an _outpd function call, because parentheses specify a call to the backing code for the function in the library, and _outpd has no backing code. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. The _outpd function returns the unsigned long value that was output to the specified port. There is no error return value and this function does not set errno. Example of _outpd ═══ Example of _outpd ═══ /************************************************************************ * This example uses the _outpd function to write a doubleword value to a specified output port and return the data written. * ************************************************************************/ #include #define LOWER 0 #define UPPER1 65535 #define UPPER2 4294967295 int Add1(int j); volatile int g; enum fruit {apples=10, bananas, cantalopes}; enum fruit f = cantalopes; int arr[]={cantalopes, bananas, apples}; union { volatile int i; volatile char ch; } un; int main(void) { unsigned long l; volatile const short c = 0; un.i = bananas * f; g = _outpd(0,LOWER); /* ============================= */ /* Types of port number passed : */ /* ----------------------------- */ l = _outpd(UPPER1, UPPER2); /* - #define constant */ l = _outpd(un.i ,f); /* - element of union */ l = _outpd(Add1(c), apples); /* - return value from a */ /* function call */ /* ----------------------------- */ l = _outpd(_outpw(255,Add1(LOWER)),6); return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpw - Read Unsigned Short from Input Port o _inpd - Read Double Word from Input Port o _outp - Write Byte to Output Port o _outpw - Write Word to Output Port ═══ 6.171. _outpw - Write Word to Output Port ═══ ═══ Format ═══ #include /* Declared in both */ #include unsigned short _outpw( const unsigned int port, const unsigned short word ); ═══ Description ═══ Language Level: Extension The _outpw function writes an unsigned short word to the specified port. The port number must be an unsigned int value within the range 0 to 65 535 inclusive. The unsigned short word must be in the range 0 to 65 535. Because it is a built-in function and has no backing code in the library: o You cannot take the address of _outpw. o You cannot parenthesize a _outpw function call, because parentheses specify a call to the backing code for the function. You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. This function returns the unsigned short value that was output to the specified port. There is no error return value and this function does not set errno. Example of _outpw ═══ Example of _outpw ═══ /************************************************************************ * This example uses the _outpw function to write an unsigned short value to a specified output port and return the data written. * ************************************************************************/ #include #define LOWER 0 #define UPPER 65535 int Add1(int j); unsigned int g; int main(void) { enum fruit {apples=10, bananas, cantalopes}; enum fruit f = cantalopes; int arr[]={cantalopes, bananas, apples}; unsigned short s; static int i = 0; volatile const int c = 255; g = _outpw(cantalopes, i); /* ============================= */ /* Types of port number passed : */ /* ----------------------------- */ s = _outpw(UPPER, LOWER); /* - #define constant */ s = _outpw(c, Add1(255)); /* - constant */ s = _outpw(_inpw(arr[2]),apples); /* - return value from a */ /* builtin function call */ /* ----------------------------- */ s = _outpw(_outpw(bananas ,UPPER),6); return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ o _inp - Read Byte from Input Port o _inpw - Read Unsigned Short from Input Port o _inpd - Read Double Word from Input Port o _outp - Write Byte to Output Port o _outpd - Write Double Word to Output Port ═══ 6.172. __parmdwords - Get Number of dwords in Parameter List ═══ ═══ Format ═══ #include /* also defined in */ unsigned char __parmdwords(void); ═══ Description ═══ Language Level: Extension The __parmdwords function returns the hidden parameter passed in the AL register for _System linkage calls. The hidden parameter contains the size of the parameter list that is passed to the function containing the call to __parmdwords. The size is in doublewords (dwords), and can be between 0 and 255. If the parameter list is larger than 255 dwords, the hidden parameter contains the 8 least significant bits of the value. This function allows the implementer of a function to increase the number of parameters the function takes without changing the name of the function. The new version of the function can call __parmdwords to check the size of the parameter list and determine whether the call was written for the earlier version of the function or for the extended version. Warning: The __parmdwords function has several limitations: 1. Because it is a built-in function and has no backing code in the library: o You cannot take the address of __parmdwords. o You cannot parenthesize a __parmdwords function call because parentheses specify a call to the backing code for the function. 2. The __parmdwords function can only be used for functions with the _System linkage type. If you use it with other linkage types, an error message is generated, and your program will not compile correctly. The __parmdwords function returns the size of the parameter list passed to the function in units of dwords. Example of __parmdwords ═══ Example of __parmdwords ═══ /************************************************************************ * This example shows two versions of an API that prints out messages. The second version uses __parmdwords to determine whether the call was intended for the original or the updated version. * ************************************************************************/ #include #include #pragma linkage(ErrorHandler, system) int ErrorHandler(int MessageNum, int Severity); /* Extended version of API */ /* Old version API prototype -- int ErrorHandler(int MessageNum); */ #define MESSAGE1 1 #define MESSAGE2 2 #define INFORMATIONAL 3 #define WARNING 2 #define ERROR 1 #define FATAL 0 int ErrorHandler(int MessageNum, int Severity) { int rc = 0; switch ((int)__parmdwords()) { case 2: /* Extended version with Severity parameter */ switch (Severity) { case FATAL: printf("Fatal Error:"); break; case ERROR: printf("Error:"); break; case WARNING: printf("Warning:"); break; case INFORMATIONAL: printf("Informational:"); break; default: rc = 1; printf("Bad Severity Number"); } /* intentional fall through */ case 1: /* Old version of API without Severity parameter */ switch (MessageNum) { case MESSAGE1: printf("Some immensely profound message\n"); break; case MESSAGE2: printf("Some other immensely profound message\n"); break; default: printf("Very trivial message, why not try MESSAGE1 or MESSAGE2?\n"); rc = 1; } } return rc; } /* Old version of main: int main(void) { return ErrorHandler(MESSAGE1); } */ /* The expected output from the old version is: Some immensely profound message */ /* New version of main: */ int main(void) { return ErrorHandler(MESSAGE1, FATAL); /* The expected output is: Fatal Error:Some immensely profound message */ } ═══ Related Information ═══ o "Calling Conventions" in the Programming Guide o stdlib.h ═══ 6.173. perror - Print Error Message ═══ ═══ Format ═══ #include void perror(const char *string); ═══ Description ═══ Language Level: ANSI, SAA The perror function prints an error message to stderr. If string is not NULL and string does not point to a null character, the string pointed to by string is printed to the standard error stream, followed by a colon and a space. The message associated with the value in errno is then printed followed by a new-line character. To produce accurate results, you should ensure that perror is called immediately after a library function returns with an error; otherwise, subsequent calls may alter the errno value. The perror function returns no value. Example of perror ═══ Example of perror ═══ /************************************************************************ * This example tries to open a stream. If the fopen function fails, the example prints a message and ends the program. * ************************************************************************/ #include #include int main(void) { FILE *fh; if ((fh = fopen("myfile.dat","r")) == NULL) { perror("Could not open data file"); abort(); } } ═══ Related Information ═══ o clearerr - Reset Error Indicators o ferror - Test for Read/Write Errors o strerror - Set Pointer to Runtime Error Message o _strerror - Set Pointer to System Error String o Runtime Return Codes and Messages o stdio.h ═══ 6.174. pow - Compute Power ═══ ═══ Format ═══ #include double pow(double x, double y); ═══ Description ═══ Language Level: ANSI, SAA The pow function returns the value of x**y (x to the power of y). If y is 0, pow returns the value 1. If x is 0 and y is negative, pow sets errno to EDOM and returns 0. If both x and y are 0, or if x is negative and y is not an integer, pow sets errno to EDOM, and returns 0. If an overflow results, pow sets errno to ERANGE and Example of pow ═══ Example of pow ═══ /************************************************************************ * This example calculates the value of 2**3. * ************************************************************************/ #include #include int main(void) { double x, y, z; x = 2.0; y = 3.0; z = pow(x,y); printf("%lf to the power of %lf is %lf\n", x, y, z); } /***************** Output should be similar to: ***************** 2.000000 to the power of 3.000000 is 8.000000 */ ═══ Related Information ═══ o exp - Exponential Function o _fsqrt - Calculate Square Root o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o sqrt - Calculate Square Root o math.h ═══ 6.175. printf - Formatted Print ═══ ═══ Format ═══ #include int printf(const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, Extension The printf function formats and prints a series of characters and values to the standard output stream stdout. The format-string consists of ordinary characters, escape sequences, and format specifications. The ordinary characters are copied in order of their appearance to stdout. Format specifications, beginning with a percent sign (%), determine the output format for any argument-list following the format-string. The format-string is a multibyte character string beginning and ending in its initial shift state. The format-string is read left to right. When the first format specification is found, the value of the first argument after the format-string is converted and output according to the format specification. The second format specification causes the second argument after the format-string to be converted and output, and so on through the end of the format-string. If there are more arguments than there are format specifications, the extra arguments are evaluated and ignored. The results are undefined if there are not enough arguments for all the format specifications. A format specification has the following form: ──%──┬─────────┬──┬─────────┬──┬────────────────┬──┬─────┬──type── │ │ │ │ │ │ │ │ └──flags──┘ └──width──┘ └──.──precision──┘ ├──h──┤ │ │ ├──L──┤ │ │ └──l──┘ Each field of the format specification is a single character or number signifying a particular format option. The type character, which appears after the last optional format field, determines whether the associated argument is interpreted as a character, a string, a number, or pointer. The simplest format specification contains only the percent sign and a type character (for example, %s). The following optional fields control other aspects of the formatting: Field Description flags Justification of output and printing of signs, blanks, decimal points, octal, and hexadecimal prefixes, and the semantics for wchar_t precision unit. width Minimum number of characters (bytes) output. precision Maximum number of characters (bytes) printed for all or part of the output field, or minimum number of digits printed for integer values. h,l,L Size of argument expected. If a percent sign (%) is followed by a character that has no meaning as a format field, the character is simply copied to stdout. For example, to print a percent sign character, use %%. In extended mode, printf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. The printf function returns the number of characters (bytes) printed. Example of printf ═══ Related Information ═══ o fprintf - Write Formatted Data o fscanf - Read Formatted Data o scanf - Read Data o sprintf - Formatted Print to Buffer o sscanf - Read Data o Infinity and NaN Support o stdio.h ═══ 6.175.1. Format Specification - Types ═══ The type characters and their meanings are given in the following table: ┌───────┬────────────┬─────────────────────────────────────────────────────────┐ │ CHAR- │ ARGUMENT │ OUTPUT FORMAT │ │ ACTER │ │ │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ d, i │ Integer │ Signed decimal integer. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ u │ Integer │ Unsigned decimal integer. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ o │ Integer │ Unsigned octal integer. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ x │ Integer │ Unsigned hexadecimal integer, using abcdef. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ X │ Integer │ Unsigned hexadecimal integer, using ABCDEF. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ f │ Double │ Signed value having the form [-]dddd.dddd, where dddd │ │ │ │ is one or more decimal digits. The number of digits │ │ │ │ before the decimal point depends on the magnitude of │ │ │ │ the number. The number of digits after the decimal │ │ │ │ point is equal to the requested precision. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ e │ Double │ Signed value having the form [-]d.dddd"e"[sign]ddd, │ │ │ │ where d is a single-decimal digit, dddd is one or more │ │ │ │ decimal digits, ddd is 2 or 3 decimal digits, and sign │ │ │ │ is + or -. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ E │ Double │ Identical to the "e" format except that "E" introduces │ │ │ │ the exponent instead of "e". │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ g │ Double │ Signed value printed in "f" or "e" format. The "e" │ │ │ │ format is used only when the exponent of the value is │ │ │ │ less than -4 or greater than precision. Trailing zeros │ │ │ │ are truncated, and the decimal point appears only if │ │ │ │ one or more digits follow it. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ G │ Double │ Identical to the "g" format except that "E" introduces │ │ │ │ the exponent (where appropriate) instead of "e". │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ c │ Character │ Single character. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ s │ String │ Characters printed up to the first null character │ │ │ │ (\"0") or until precision is reached. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ n │ Pointer to │ Number of characters successfully written so far to the │ │ │ integer │ stream or buffer; this value is stored in the integer │ │ │ │ whose address is given as the argument. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ p │ Pointer │ Pointer to void converted to a sequence of printable │ │ │ │ characters. │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ "lc" │ Wide char- │ Multibyte character. │ │ │ acter │ │ ├───────┼────────────┼─────────────────────────────────────────────────────────┤ │ "ls" │ Wide │ Multibyte characters printed up to the first "wchar_t" │ │ │ string │ null character ("L\0") or until precision is reached. │ └───────┴────────────┴─────────────────────────────────────────────────────────┘ ═══ 6.175.2. Format Specification - Flags ═══ The flag characters and their meanings are as follows (notice that more than one flag can appear in a format specification): ┌───────────┬───────────────────────────────────────────┬──────────────────────┐ │ FLAG │ MEANING │ DEFAULT │ ├───────────┼───────────────────────────────────────────┼──────────────────────┤ │ - │ Left-justify the result within the field │ Right-justify. │ │ │ width. │ │ ├───────────┼───────────────────────────────────────────┼──────────────────────┤ │ + │ Prefix the output value with a sign (+ or │ Sign appears only │ │ │ -) if the output value is of a signed │ for negative signed │ │ │ type. │ values (-). │ ├───────────┼───────────────────────────────────────────┼──────────────────────┤ │ blank(' ')│ Prefix the output value with a blank if │ No blank. │ │ │ the output value is signed and positive. │ │ │ │ The "+" flag overrides the blank flag if │ │ │ │ both appear, and a positive signed value │ │ │ │ will be output with a sign. │ │ ├───────────┼───────────────────────────────────────────┼──────────────────────┤ │ # │ When used with the "o", "x", or "X" │ No prefix. │ │ │ formats, the "#" flag prefixes any │ │ │ │ nonzero output value with "0", "0"x, or │ │ │ │ "0"X, respectively. │ │ │ ├───────────────────────────────────────────┼──────────────────────┤ │ │ When used with the "f", "e", or "E" │ Decimal point │ │ │ formats, the "#" flag forces the output │ appears only if │ │ │ value to contain a decimal point in all │ digits follow it. │ │ │ cases. │ │ │ ├───────────────────────────────────────────┼──────────────────────┤ │ │ When used with the "g" or "G" formats, │ Decimal point │ │ │ the "#" flag forces the output value to │ appears only if │ │ │ contain a decimal point in all cases and │ digits follow it; │ │ │ prevents the truncation of trailing │ trailing zeros are │ │ │ zeros. │ truncated. │ │ ├───────────────────────────────────────────┼──────────────────────┤ │ │ When used with the "ls" format, the "#" │ Precision indicates │ │ │ flag causes precision to be measured in │ the maximum number │ │ │ "wchar_t" characters. │ of bytes to be │ │ │ │ output. │ ├───────────┼───────────────────────────────────────────┼──────────────────────┤ │ "0" │ When used with the "d", "i", "o", "u", │ Space padding. │ │ │ "x", "X", "e", "E", "f", "g", or "G" │ │ │ │ formats, the "0" flag causes leading │ │ │ │ "0"'s to pad the output to the field │ │ │ │ width. The "0" flag is ignored if preci- │ │ │ │ sion is specified for an integer or if │ │ │ │ the "-" flag is specified. │ │ └───────────┴───────────────────────────────────────────┴──────────────────────┘ The # flag should not be used with c, lc, d, i, u, s, or p types. ═══ 6.175.3. Format Specification - Width ═══ Width is a nonnegative decimal integer controlling the minimum number of characters printed. If the number of characters in the output value is less than the specified width, blanks are added on the left or the right (depending on whether the - flag is specified) until the minimum width is reached. Width never causes a value to be truncated; if the number of characters in the output value is greater than the specified width, or width is not given, all characters of the value are printed (subject to the precision specification). For the ls type, width is specified in bytes. If the number of bytes in the output value is less than the specified width, single-byte blanks are added on the left or the right (depending on whether the - flag is specified) until the minimum width is reached. The width specification can be an asterisk (*), in which case an argument from the argument list supplies the value. The width argument must precede the value being formatted in the argument list. ═══ 6.175.4. Format Specification - Precision ═══ Precision is a nonnegative decimal integer preceded by a period, which specifies the number of characters to be printed or the number of decimal places. Unlike the width specification, the precision can cause truncation of the output value or rounding of a floating-point value. The precision specification can be an asterisk (*), in which case an argument from the argument list supplies the value. The precision argument must precede the value being formatted in the argument list. The interpretation of the precision value and the default when the precision is omitted depend upon the type, as shown in the following table: ┌───────┬───────────────────────────────────────────────┬──────────────────────┐ │ TYPE │ MEANING │ DEFAULT │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ i │ Precision specifies the minimum number of │ If precision is "0" │ │ d │ digits to be printed. If the number of │ or omitted entirely, │ │ u │ digits in the argument is less than │ or if the period (.) │ │ o │ precision, the output value is padded on the │ appears without a │ │ x │ left with zeros. The value is not truncated │ number following it, │ │ X │ when the number of digits exceeds precision. │ the precision is set │ │ │ │ to 1. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ f │ Precision specifies the number of digits to │ Default precision is │ │ e │ be printed after the decimal point. The last │ six. If precision │ │ E │ digit printed is rounded. │ is "0" or the period │ │ │ │ appears without a │ │ │ │ number following it, │ │ │ │ no decimal point is │ │ │ │ printed. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ g │ Precision specifies the maximum number of │ All significant │ │ G │ significant digits printed. │ digits are printed. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ c │ No effect. │ The character is │ │ │ │ printed. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ lc │ No effect. │ The "wchar_t" char- │ │ │ │ acter is printed. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ s │ Precision specifies the maximum number of │ Characters are │ │ │ characters to be printed. Characters in │ printed until a null │ │ │ excess of precision are not printed. │ character is │ │ │ │ encountered. │ ├───────┼───────────────────────────────────────────────┼──────────────────────┤ │ ls │ Precision specifies the maximum number of │ "wchar_t" characters │ │ │ bytes to be printed. Bytes in excess of pre- │ are printed until a │ │ │ cision are not printed; however, multibyte │ null character is │ │ │ integrity is always preserved. │ encountered. │ └───────┴───────────────────────────────────────────────┴──────────────────────┘ ═══ 6.175.5. Format Specification - h, l, L ═══ The h, l, and L characters specify the size of the expected argument. Their meanings are as follows: h A prefix with the integer types d, i, o, u, x, X, and n that specifies that the argument is short int or unsigned short int. l A prefix with d, i, o, u, x, X, and n types that specifies that the argument is a long int or unsigned long int. L A prefix with e, E, f, g, or G types that specifies that the argument is long double. ═══ Example of printf ═══ /************************************************************************ * This example prints data in a variety of formats. * ************************************************************************/ #include int main(void) { char ch = 'h', *string = "computer"; int count = 234, hex = 0x10, oct = 010, dec = 10; double fp = 251.7366; printf("%d %+d %06d %X %x %o\n\n", count, count, count, count, count, count); printf("1234567890123%n4567890123456789\n\n", &count); printf("Value of count should be 13; count = %d\n\n", count); printf("%10c%5c\n\n", ch, ch); printf("%25s\n%25.4s\n\n", string, string); printf("%f %.2f %e %E\n\n", fp, fp, fp, fp); printf("%i %i %i\n\n", hex, oct, dec); } /***************** Output should be similar to: ***************** 234 +234 000234 EA ea 352 12345678901234567890123456789 Value of count should be 13; count = 13 h h computer comp 251.736600 251.74 2.517366e+02 2.517366E+02 16 8 10 ═══ 6.176. putc - putchar - Write a Character ═══ ═══ Format ═══ #include int putc(int c, FILE *stream); int putchar(int c); ═══ Description ═══ Language Level: ANSI, SAA The putc function converts c to unsigned char and then writes c to the output stream at the current position. The putchar function is identical to putc(c, stdout). The putc and putchar functions return the character written. A return value of EOF indicates an error. The putc function can be implemented as a macro so the argument may be evaluated multiple times. Example of putc - putchar ═══ Example of putc - putchar ═══ /************************************************************************ * This example writes the contents of a buffer to a data stream. In this example, the body of the for statement is null because the example carries out the writing operation in the test expression. * ************************************************************************/ #include #include #define LENGTH 80 int main(void) { FILE *stream = stdout; int i, ch; char buffer[LENGTH + 1] = "Hello world"; /* This could be replaced by using the fwrite routine */ for ( i = 0; (i < strlen(buffer)) && ((ch = putc(buffer[i], stream)) != EOF); ++i); } /******************** Expected output: ************************** Hello world */ ═══ Related Information ═══ o fputc - Write a Character o _fputchar - Write Character o fwrite - Write Items o getc - Read a Character o _putch - Write Character to Screen o puts - Write a String o stdio.h o _write - Writes from Buffer to File ═══ 6.177. _putch - Write Character to Screen ═══ ═══ Format ═══ #include int _putch(int c); ═══ Description ═══ Language Level: Extension The _putch function writes the character c directly to the screen. If successful, _putch returns c. If an error occurs, _putch returns EOF. Example of _putch ═══ Example of _putch ═══ /************************************************************************ * This example defines a function gchar that is similar to _getche using the _putch and _getch functions: * ************************************************************************/ #include int gchar(void) { int ch; ch = _getch(); _putch(ch); return(ch); } ═══ Related Information ═══ o _cputs - Write String to Screen o _cprintf - Print Characters to Screen o fputc - Write a Character o _getch - _getche - Read Character from Keyboard o putc - putchar - Write a Character o puts - Write a String o _write - Writes from Buffer to File o conio.h ═══ 6.178. _putenv - Modify Environment Variables ═══ ═══ Format ═══ #include int _putenv(char *envstring); ═══ Description ═══ Language Level: Extension The _putenv function adds new environment variables or modifies the values of existing environment variables. Environment variables define the environment in which a process runs (for example, the default search path for libraries to be linked with a program). The envstring argument must be a pointer to a string with the form: varname=string where varname is the name of the environment variable to be added or modified and string is the value of the variable. See the Notes below. If varname is already part of the environment, string replaces its current value; if not, the new varname is added to the environment with the value string. To set a variable to an empty value, specify an empty string. A variable can be removed from the environment by specifying varname only, for example, _putenv("PATH"); Do not free a pointer to an environment entry while the environment entry is still in use, or the environment variable will point into freed space. A similar problem can occur if you pass a pointer to a local variable to _putenv and then exit from the function in which the variable is declared. The environment manipulated by _putenv is local to the process currently running. You cannot enter new items in your command level environment using _putenv. When the program ends, the environment reverts to the parent process environment. This environment is passed on to some child processes created by the _spawn, _exec, or system functions, and they get any new environment variables added using _putenv. DosScanEnv will not reflect any changes made using the _putenv function, but getenv will reflect any changes made by _putenv. Notes 1. The _putenv function can change the value of _environ, thus invalidating the envp argument to the main function. 2. %envvar%, where envvar is any OS/2 environment variable, cannot be used with _putenv to concatenate new envstring and old envstring. The _putenv function returns 0 if it is successful. A return value of -1 indicates an error. Example of _putenv ═══ Example of _putenv ═══ /************************************************************************ * This example tries to change the environment variable PATH, and then uses getenv to get the current path. If the call to _putenv fails, the example writes an error message. * ************************************************************************/ #include #include int main(void) { char *pathvar; if ( _putenv("PATH=a:\\bin;b:\\andy") == -1 ) { printf("_putenv failed - out of memory\n"); exit(-1); } /* getting and printing the current environment path */ pathvar = getenv("PATH"); printf("The current path is: %s\n", pathvar); return 0; /* The expected output is: The current path is: a:\bin;b:\andy */ } ═══ Related Information ═══ o _execl - _execvp - Load and Run Child Process o getenv - Search for Environment Variables o _spawnl -_spawnvpe -Start and Run Child Processes o system - Invoke the Command Processor o envp Parameter to main o stdlib.h ═══ 6.179. puts - Write a String ═══ ═══ Format ═══ #include int puts(const char *string); ═══ Description ═══ Language Level: ANSI, SAA The puts function writes the given string to the standard output stream stdout; it also appends a new-line character to the output. The terminating null character is not written. The puts function returns EOF if an error occurs. A nonnegative return value indicates that no error has occurred. Example of puts ═══ Example of puts ═══ /************************************************************************ * This example writes Hello World to stdout. * ************************************************************************/ #include int main(void) { if ( puts("Hello World") == EOF ) printf( "Error in puts\n" ); } /************************ Expected output: ********************* Hello World */ ═══ Related Information ═══ o _cputs - Write String to Screen o fputs - Print Strings o gets - Read a Line o putc - putchar - Write a Character o stdio.h ═══ 6.180. qsort - Sort Array ═══ ═══ Format ═══ #include void qsort(void *base, size_t num, size_t width, int(*compare)(const void *element1, const void *element2)); ═══ Description ═══ Language Level: ANSI, SAA, Extension The qsort function sorts an array of num elements, each of width bytes in size. The base pointer is a pointer to the array to be sorted. The qsort function overwrites this array with the sorted elements. The compare pointer points to a function, which you supply, that compares two array elements and returns an integer value specifying their relationship. The qsort function calls the compare function one or more times during the sort, passing pointers to two array elements on each call. The function must compare the elements, and then return one of the following values: Value Meaning Less than 0 element1 less than element2 0 element1 equal to element2 Greater than 0 element1 greater than element2 The sorted array elements are stored in ascending order, as defined by your comparison function. You can sort in reverse order by reversing the sense of "greater than" and "less than" in the comparison function. The order of the elements is unspecified when two elements compare equally. There is no return value. Example of qsort ═══ Example of qsort ═══ /************************************************************************ * This example sorts the arguments (argv) in ascending lexical sequence, using the comparison function compare() supplied in the example. * ************************************************************************/ #include #include #include /* Declaration of compare() as a function */ int compare(const void *, const void *); int main (int argc, char *argv[ ]) { int i; argv++; argc--; qsort((char *)argv, argc, sizeof(char *), compare); for (i = 0; i < argc; ++i) printf("%s\n", argv[i]); return 0; } int compare (const void *arg1, const void *arg2) { /* Compare all of both strings */ return(strcmp(*(char **)arg1, *(char **)arg2)); } /*********** If the program is passed the arguments: ************ ************ Does, this, really, sort, the, arguments, correctly?, **** **************** then the expected output is: ******************* arguments correctly? really sort the this Does */ ═══ Related Information ═══ o bsearch - Search Arrays o _lfind - _lsearch - Find Key in Array o search.h o stdlib.h ═══ 6.181. raise - Send Signal ═══ ═══ Format ═══ #include int raise(int sig); ═══ Description ═══ Language Level: ANSI, SAA The raise function sends the signal sig to the running program. The return value is zero if successful, nonzero if unsuccessful. Example of raise ═══ Example of raise ═══ /************************************************************************ * This example establishes a signal handler called sig_hand for the signal SIGUSR1. The signal handler is called whenever the SIGUSR1 signal is raised and will ignore the first nine occurrences of the signal. On the tenth raised signal, it exits the program with an error code of 10. Note that the signal handler must be reestablished each time it is called. * ************************************************************************/ #include #include void sig_hand(int); /* declaration of sig_hand() as a function */ int main(void) { signal(SIGUSR1, sig_hand); /* set up handler for SIGUSR1 */ . . . raise(SIGUSR1); /* signal SIGUSR1 is raised */ /* sig_hand() is called */ } void sig_hand(int sig) { static int count = 0; /* initialized only once */ count++; if (count == 10) /* ignore the first 9 occurrences of this signal */ exit(10); else signal(SIGUSR1, sig_hand); /* set up the handler again */ } ═══ Related Information ═══ o signal Install Interrupt Handlers o signal.h ═══ 6.182. rand - Generate Random Number ═══ ═══ Format ═══ #include int rand(void); ═══ Description ═══ Language Level: ANSI, SAA The rand function generates a pseudo-random integer in the range 0 to RAND_MAX (macro defined in ). Use the srand function before calling rand to set a starting point for the random number generator. If you do not make a call to srand, the default seed is 1. Example of rand ═══ Example of rand ═══ /************************************************************************ * This example prints the first 10 random numbers generated. * ************************************************************************/ #include #include int main(void) { int x; for (x = 1; x <= 10; x++) printf("iteration %d, rand=%d\n", x, rand()); } /********************* Output should be similar to: ************ iteration 1, rand=16838 iteration 2, rand=5758 iteration 3, rand=10113 iteration 4, rand=17515 iteration 5, rand=31051 iteration 6, rand=5627 iteration 7, rand=23010 iteration 8, rand=7419 iteration 9, rand=16212 iteration 10, rand=4086 */ ═══ Related Information ═══ o srand - Set Seed for rand Function o stdlib.h ═══ 6.183. _read - Read Into Buffer ═══ ═══ Format ═══ #include int _read(int handle, char *buffer, unsigned int count); ═══ Description ═══ Language Level: Extension The _read function reads count bytes from the file associated with handle into buffer. The read operation begins at the current position of the file pointer associated with the given file. After the read operation, the file pointer points to the next unread character. The _read function returns the number of bytes placed in buffer. This number can be less than count if there are fewer than count bytes left in the file or if the file was opened in text mode (see the note below). The return value 0 indicates an attempt to read at end-of-file. A return value -1 indicates an error. If -1 is returned, the current file position is undefined, and errno is set to one of the following values: Value Meaning EBADF The given handle is incorrect, or the file is not open for reading, or the file is locked. EOS2ERR The call to the operating system was not successful. Note: If the file was opened in text mode, the return value might not correspond to the number of bytes actually read. When text mode is in effect, carriage return characters are deleted from the input stream without affecting the file pointer. Example of _read ═══ Example of _read ═══ /************************************************************************ * This example opens the file sample.dat and attempts to read from it. * ************************************************************************/ #include #include #include #include #include int main(void) { int fh; char buffer[20]; memset(buffer,'\0',20); printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { perror("Unable to open sample.dat."); return 1; } if (7 != _read(fh,buffer,7)) { perror("Unable to read from sample.dat."); _close(fh); return 1; } printf("Successfully read in the following:\n%s\n ",buffer); _close(fh); return 0; /***************** The expected output is: **************************** Creating sample.dat. Successfully read in the following: Sample */ } ═══ Related Information ═══ o _creat - Create New File o fread - Read Items o _open - Open File o _sopen - Open Shared File o _write - Writes from Buffer to File o io.h ═══ 6.184. realloc - Change Reserved Storage Block Size ═══ ═══ Format ═══ #include /* also defined in */ void *realloc(void *ptr, size_t size); ═══ Description ═══ Language Level: ANSI, SAA , Extension The realloc function changes the size of a previously reserved storage block. The ptr argument points to the beginning of the block. The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes. If the ptr is NULL, realloc reserves a block of storage of size bytes. It does not necessarily give all bits of each element an initial value of 0. If size is 0 and the ptr is not NULL, the storage allocated to ptr is freed and NULL is returned. The realloc function returns a pointer to the reallocated storage block. The storage location of the block might be moved by the realloc function. Thus, the ptr argument to realloc is not necessarily the same as the return value. The return value is NULL if size is 0. If there is not enough storage to expand the block to the given size, the original block is unchanged and NULL is returned. The storage to which the return value points is guaranteed to be aligned for storage of any type of object. Example of realloc ═══ Example of realloc ═══ /************************************************************************ * This example allocates storage for the prompted size of array and then uses realloc to reallocate the block to hold the new size of the array. The contents of the array are printed after each allocation. * ************************************************************************/ #include #include int main(void) { long * array; /* start of the array */ long * ptr; /* pointer to array */ int i; /* index variable */ int num1, num2; /* number of entries of the array */ void print_array( long *ptr_array, int size); printf( "Enter the size of the array\n" ); scanf( "%i", &num1 ); /* allocate num1 entries using malloc() */ if ( (array = malloc( num1 * sizeof( long ))) != NULL ) { for ( ptr = array, i = 0; i < num1 ; ++i ) /* assign values */ *ptr++ = i; print_array( array, num1 ); printf("\n"); } else { /* malloc error */ perror( "Out of storage" ); abort(); } /* Change the size of the array ... */ printf( "Enter the size of the new array\n" ); scanf( "%i", &num2); if ( (array = realloc( array, num2* sizeof( long ))) != NULL ) { for ( ptr = array + num1, i = num1; i <= num2; ++i ) *ptr++ = i + 2000; /* assign values to new elements */ print_array( array, num2 ); } else { /* realloc error */ perror( "Out of storage" ); abort(); } } void print_array( long * ptr_array, int size ) { int i; long * index = ptr_array; printf("The array of size %d is:\n", size); for ( i = 0; i < size; ++i ) /* print the array out */ printf( " array[ %i ] = %li\n", i, ptr_array[i] ); } /****************** If the initial value entered ********************* ************** is 2 and the second value entered is 4, **************** ******************* then the expected output is: **************** Enter the size of the array The array of size 2 is: array[ 0 ] = 0 array[ 1 ] = 1 Enter the size of the new array The array of size 4 is: array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2002 array[ 3 ] = 2003 */ ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o _debug_realloc - Change Reserved Storage Block Size o free - Release Storage Blocks o malloc - Reserve Storage Block o _msize - Return Number of Bytes Allocated o _trealloc - Reallocate Tiled Storage Block o malloc.h o stdlib.h ═══ 6.185. remove - Delete File ═══ ═══ Format ═══ #include int remove(const char *filename); ═══ Description ═══ Language Level: ANSI, SAA The remove function deletes the file specified by filename. The remove function returns the value 0 if it successfully deletes the file. A return value of nonzero indicates an error. Note: You cannot remove a nonexistent file or a file that is open. Example of remove ═══ Example of remove ═══ /************************************************************************ * When you invoke this example with a file name, the program attempts to remove that file. It issues a message if an error occurs. * ************************************************************************/ #include int main(int argc, char ** argv) { if ( argc != 2 ) printf( "Usage: %s fn\n", argv[0] ); else if ( remove( argv[1] ) != 0 ) perror( "Could not remove file" ); } ═══ Related Information ═══ o fopen - Open Files o rename - Rename File o _rmtmp - Remove Temporary Files o _unlink - Delete File o stdio.h ═══ 6.186. rename - Rename File ═══ ═══ Format ═══ #include /* also defined in */ int rename(const char *oldname, const char *newname); ═══ Description ═══ Language Level: ANSI, SAA The rename function renames the file specified by oldname to the name given by newname. The oldname pointer must specify the name of an existing file. The newname pointer must not specify the name of an existing file. You cannot rename a file with the name of an existing file. You also cannot rename an open file. The rename function returns 0 if it is successful. On an error, it returns a nonzero value. Example of rename ═══ Example of rename ═══ /************************************************************************ * This example takes two file names as input and uses rename to change the file name from the first name to the second name. * ************************************************************************/ #include int main(int argc, char ** argv ) { if ( argc != 3 ) printf( "Usage: %s old_fn new_fn\n", argv[0] ); else if ( rename( argv[1], argv[2] ) != 0 ) perror ( "Could not rename file" ); } ═══ Related Information ═══ o fopen - Open Files o remove - Delete File o stdio.h ═══ 6.187. rewind - Adjust Current File Position ═══ ═══ Format ═══ #include void rewind(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The rewind function repositions the file pointer associated with stream to the beginning of the file. A call to rewind is the same as: (void) fseek(stream, 0L, SEEK_SET); except that rewind also clears the error indicator for the stream. There is no return value. Example of rewind ═══ Example of rewind ═══ /************************************************************************ * This example first opens a file myfile for input and output. It writes integers to the file, uses rewind to reposition the file pointer to the beginning of the file, and then reads the data back in. * ************************************************************************/ #include FILE *stream; int data1, data2, data3, data4; int main(void) { data1 = 1; data2 = -37; /* Place data in the file */ stream = fopen("myfile.dat", "w+"); fprintf(stream, "%d %d\n", data1, data2); /* Now read the data file */ rewind(stream); fscanf(stream, "%d", &data3); fscanf(stream, "%d", &data4); printf("The values read back in are: %d and %d\n", data3, data4); } /******************** Output should be similar to: ************** The values read back in are: 1 and -37 */ ═══ Related Information ═══ o fgetpos - Get File Position o fseek - Reposition File Position o fsetpos - Set File Position o ftell - Get Current Position o _lseek - Move File Pointer o _tell - Get Pointer Position o stdio.h ═══ 6.188. _rmdir - Remove Directory ═══ ═══ Format ═══ #include int _rmdir(char *pathname); ═══ Description ═══ Language Level: Extension The _rmdir function deletes the directory specified by pathname. The directory must be empty, and it must not be the current working directory or the root directory. The _rmdir function returns the value 0 if the directory is successfully deleted. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS One of the following has occurred: o The given path name is not a directory. o The directory is not empty. o The directory is read only. o The directory is the current working directory or root directory being used by a process. ENOENT The path name was not found. Example of _rmdir ═══ Example of _rmdir ═══ /************************************************************************ * This example deletes two directories. One is in the root directory and the other one in the current working directory. * ************************************************************************/ #include #include #include int main(void) { char *dir1, *dir2; /* Create the directory "aleng" in the root directory of the C: drive. */ dir1 = "c:\\aleng"; if ((_mkdir(dir1)) == 0) printf("%s directory was created.\n",dir1); else printf("%s directory was not created.\n",dir1); /* Create the subdirectory "simon" in the current directory. */ dir2 = "simon"; if ((_mkdir(dir2)) == 0) printf("%s directory was created.\n",dir2); else printf("%s directory was not created.\n",dir2); /* Remove the directory "aleng" from the root directory of the C: drive. */ printf("Removing directory 'aleng' from the root directory.\n"); if (_rmdir(dir1)) perror(NULL); else printf("%s directory was removed.\n",dir1); /* Remove the subdirectory "simon" from the current directory. */ printf("Removing subdirectory 'simon' from the current directory.\n"); if (_rmdir(dir2)) perror(NULL); else printf("%s directory was removed.\n",dir2); return 0; /*************** The output should be similar to: ******************** c:\aleng directory was created. simon directory was created. Removing directory 'aleng' from the root directory. c:\aleng directory was removed. Removing subdirectory 'simon' from the current directory. simon directory was removed. */ } ═══ Related Information ═══ o _chdir - Change Current Working Directory o _getdcwd - Get Full Path Name of Current Directory o _getcwd - Get Path Name of Current Directory o _mkdir - Create New Directory o direct.h ═══ 6.189. _rmtmp - Remove Temporary Files ═══ ═══ Format ═══ #include int _rmtmp(void); ═══ Description ═══ Language Level: Extension The _rmtmp function closes and deletes all temporary files in all directories that are held open by the calling process. The _rmtmp function returns the number of temporary files removed and deleted. Example of _rmtmp ═══ Example of _rmtmp ═══ /************************************************************************ * This example uses _rmtmp to remove a number of temporary files. * ************************************************************************/ #include int main(void) { int num; FILE *stream; if ( (stream = tmpfile()) == NULL ) printf("Could not open new temporary file\n"); else { num = _rmtmp(); printf("Number of temporary files removed = %d\n", num); } return 0; /* The expected output is: Number of temporary files removed = 1 */ } ═══ Related Information ═══ o _flushall - Write Buffers to Files o remove - Delete File o tmpfile - Create Temporary File o tmpnam - Produce Temporary File Name o _unlink - Delete File o stdio.h ═══ 6.190. _rotl - _rotr - Bit Rotation ═══ ═══ Format ═══ #include unsigned int _rotl(unsigned int value, int shift); unsigned int _rotr(unsigned int value, int shift); ═══ Description ═══ Language Level: Extension These functions take a 4-byte integer value and rotate it by shift bits. Note: Because the size of an int is only 2 bytes in 16-bit compilers, if you are migrating 16-bit programs, some parts of your programs may have to be rewritten if they use this function. Both functions return the rotated value. There is no error return. Example of _rotl - _rotr ═══ Example of _rotl - _rotr ═══ /************************************************************************ * This example uses _rotr and _rotl with different shift values to rotate the integer value 0x01234567: * ************************************************************************/ #include #include int main(void) { unsigned int val = 0X01234567; printf("The value of 0x%8.8lx rotated 4 bits to the left is 0x%8.8lx\n", val, _rotl(val, 4)); printf("The value of 0x%8.8lx rotated 16 bits to the right is 0x%8.8lx\n", val, _rotr(val, 16)); return 0; /*************** The output should be similar to: **************** The value of 0x01234567 rotated 4 bits to the left is 0x12345670 The value of 0x01234567 rotated 16 bits to the right is 0x45670123 */ } ═══ Related Information ═══ o _lrotl - _lrotr - Rotate Bits o _swab - Swap Adjacent Bytes o stdlib.h ═══ 6.191. scanf - Read Data ═══ ═══ Format ═══ #include int scanf(const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, Extension The scanf function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string. The format-string controls the interpretation of the input fields, and is a multibyte character string beginning and ending in its initial shift state. The format-string can contain one or more of the following: o White-space characters, as specified by isspace (such as blanks and new-line characters). A white-space character causes scanf to read, but not to store, all consecutive white-space characters in the input up to the next character that is not white space. One white-space character in format-string matches any combination of white-space characters in the input. o Characters that are not white space, except for the percent sign character (%). A non-white-space character causes scanf to read, but not to store, a matching non-white-space character. If the next character in stdin does not match, scanf ends. o Format specifications, introduced by the percent sign (%). A format specification causes scanf to read and convert characters in the input into values of a specified type. The value is assigned to an argument in the argument list. The scanf function reads format-string from left to right. Characters outside of format specifications are expected to match the sequence of characters in stdin; the matched characters in stdin are scanned but not stored. If a character in stdin conflicts with format-string, scanf ends. The conflicting character is left in stdin as if it had not been read. When the first format specification is found, the value of the first input field is converted according to the format specification and stored in the location specified by the first entry in argument-list. The second format specification converts the second input field and stores it in the second entry in argument-list, and so on through the end of format-string. An input field is defined as all characters up to the first white-space character (space, tab, or new line), up to the first character that cannot be converted according to the format specification, or until the field width is reached, whichever comes first. If there are too many arguments for the format specifications, the extra arguments are ignored. The results are undefined if there are not enough arguments for the format specifications. A format specification has the following form: ──%──┬─────┬──┬─────────┬──┬─────┬──type── │ │ │ │ │ │ └──*──┘ └──width──┘ ├──h──┤ │ │ ├──l──┤ │ │ └──L──┘ Each field of the format specification is a single character or a number signifying a particular format option. The type character, which appears after the last optional format field, determines whether the input field is interpreted as a character, a string, or a number. The simplest format specification contains only the percent sign and a type character (for example, %s). Each field of the format specification is discussed in Format Specification Fields. If a percent sign (%) is followed by a character that has no meaning as a format control character, that character and following characters up to the next percent sign are treated as an ordinary sequence of characters; that is, a sequence of characters that must match the input. For example, to specify a percent-sign character, use %%. The scanf function scans each input field character by character. It might stop reading a particular input field either before it reaches a space character, when the specified width is reached, or when the next character cannot be converted as specified. When a conflict occurs between the specification and the input character, the next input field begins at the first unread character. The conflicting character, if there was one, is considered unread and is the first character of the next input field or the first character in subsequent read operations on stdin. In extended mode, scanf also reads in the strings the strings "INFINITY", "INF", and "NAN" (in upper or lowercase) and converts them to the corresponding floating-point value. The sign of the value is determined by the format specification. See Infinity and NaN Support for more information on infinity and NaN values. The scanf function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. The return value is EOF for an attempt to read at end-of-file if no conversion was performed. A return value of 0 means that no fields were assigned. Example of scanf ═══ Related Information ═══ o fscanf - Read Formatted Data o printf - Formatted Print o sscanf - Read Data o Infinity and NaN Support o stdio.h ═══ 6.191.1. Format Specification Fields ═══ The scanf format specification fields are described below. * An asterisk (*) following the percent sign suppresses assignment of the next input field, which is interpreted as a field of the specified type. The field is scanned but not stored. width The width is a positive decimal integer controlling the maximum number of characters to be read from stdin. No more than width characters are converted and stored at the corresponding argument. Fewer than width characters are read if a white-space character (space, tab, or new line), or a character that cannot be converted according to the given format occurs before width is reached. h, l, L The optional prefix l shows that you use the long version of the following type, while the prefix h indicates that the short version is to be used. The corresponding argument should point to a long or double object (for the l character), a long double object (for the L character), or a short object (with the h character). The l and h modifiers can be used with the d, i, o, x, and u type characters. The l modifier can also be used with the e, f, and g type characters. The L modifier can be used with the e, f and g type characters. The l and h modifiers are ignored if specified for any other type. Note that the l modifier is also used with the c and s characters to indicate a multibyte character or string. type The type characters and their meanings are in the following table: ┌────────┬──────────────────────────────────┬──────────────────────────────────┐ │ CHAR- │ TYPE OF INPUT EXPECTED │ TYPE OF ARGUMENT │ │ ACTER │ │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "d" │ Decimal integer │ Pointer to "int" │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "o" │ Octal integer │ Pointer to "unsigned int" │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "x", │ Hexadecimal integer │ Pointer to "unsigned int" │ │ "X" │ │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "i" │ Decimal, hexadecimal, or octal │ Pointer to "int" │ │ │ integer │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "u" │ Unsigned decimal integer │ Pointer to "unsigned int" │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "e, f, │ Floating-point value consisting │ Pointer to "float" │ │ g" │ of an optional sign (+ or -); a │ │ │ │ series of one or more decimal │ │ │ "E, G" │ digits possibly containing a │ │ │ │ decimal point; and an optional │ │ │ │ exponent (e or E) followed by a │ │ │ │ possibly signed integer value │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "d(n,p)│ Packed decimal value consisting │ Pointer to "decimal(n,p)". │ │ │ of an optional sign (+ or -); │ │ │ │ then a nonempty sequence of │ │ │ │ digits optionally a series of │ │ │ │ one or more decimal digits pos- │ │ │ │ sibly containing a decimal │ │ │ │ point, but not a decimal suffix. │ │ │ │ The subject sequence is defined │ │ │ │ as the longest initial subse- │ │ │ │ quence of the input string, │ │ │ │ starting with the first non- │ │ │ │ white-space character, in the │ │ │ │ expected form. It contains no │ │ │ │ characters if the input string │ │ │ │ is empty or consists entirely of │ │ │ │ white space, or if the first │ │ │ │ non-white-space character is │ │ │ │ anything other than a sign, a │ │ │ │ digit, or a decimal point char- │ │ │ │ acter. │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "c" │ Character; white-space charac- │ Pointer to "char" large enough │ │ │ ters that are ordinarily skipped │ for input field │ │ │ are read when "c" is specified │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "s" │ String │ Pointer to character array large │ │ │ │ enough for input field plus a │ │ │ │ terminating null character │ │ │ │ ("\0"), which is automatically │ │ │ │ appended │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "n" │ No input read from stream or │ Pointer to "int", into which is │ │ │ buffer │ stored the number of characters │ │ │ │ successfully read from the │ │ │ │ stream or buffer up to that │ │ │ │ point in the call to "scanf" │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "p" │ Pointer to "void" converted to │ Pointer to "void" │ │ │ series of characters │ │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "lc" │ Multibyte character constant │ Pointer to "wchar_t" │ ├────────┼──────────────────────────────────┼──────────────────────────────────┤ │ "ls" │ Multibyte string constant │ Pointer to "wchar_t" string │ └────────┴──────────────────────────────────┴──────────────────────────────────┘ To read strings not delimited by space characters, substitute a set of characters in brackets ([ ]) for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: the input field is read up to the first character that does appear in the rest of the character set. To store a string without storing an ending null character (\0), use the specification %ac, where a is a decimal integer. In this instance, the c type character means that the argument is a pointer to a character array. The next a characters are read from the input stream into the specified location, and no null character is added. The input for a %x format specifier is interpreted as a hexadecimal number. ═══ Example of scanf ═══ /************************************************************************ * This example scans various types of data: * ************************************************************************/ #include int main(void) { int i; float fp; char c, s[81]; printf("Enter an integer, a real number, a character " "and a string : \n"); if (scanf("%d %f %c %s", &i, &fp, &c, s) != 4) printf("Not all of the fields were not assigned\n"); else { printf("integer = %d\n", i); printf("real number = %f\n", fp); printf("character = %c\n", c); printf("string = %s\n",s); } } /***************** If input is: 12 2.5 a yes, ******************* ************** then output should be similar to: **************** Enter an integer, a real number, a character and a string : integer = 12 real number = 2.500000 character = a string = yes */ /************************************************************************ * This example converts a hexadecimal integer to a decimal integer. The while loop ends if the input value is not a hexadecimal integer. * ************************************************************************/ #include int main(void) { int number; printf("Enter a hexadecimal number or anything else to quit:\n"); while (scanf("%x",&number)) { printf("Hexadecimal Number = %x\n",number); printf("Decimal Number = %d\n",number); } } /*************** If input is: 0x231 0xf5e 0x1 q, **************** **************** then output should be similar to: ************** Enter a hexadecimal number or anything else to quit: Hexadecimal Number = 231 Decimal Number = 561 Hexadecimal Number = f5e Decimal Number = 3934 Hexadecimal Number = 1 Decimal Number = 1 */ ═══ 6.192. _searchenv - Search for File ═══ ═══ Format ═══ #include void _searchenv(char *name, char *env_var, char *path); ═══ Description ═══ Language Level: Extension The _searchenv function searches for the target file in the specified domain. The env_var variable can be any environment variable that specifies a list of directory paths, such as PATH, LIB, INCLUDE, or other user-defined variables. Most often, it is PATH, causing a search for name in all directories specified in the PATH variable. The routine first searches for the file in the current working directory. If it does not find the file, it next looks through the directories specified by the environment variable. If the target file is found in one of the directories, the newly created path is copied into the buffer that path points to. You must ensure sufficient space for the constructed path name. If the target file is not found, path contains an empty null-terminated string. There is no return value. Example of _searchenv ═══ Example of _searchenv ═══ /************************************************************************ * This example searches for the files searchen.c and cmd.exe. * ************************************************************************/ #include #include int main(void) { char path_buffer [_MAX_PATH]; _searchenv ("cmd.exe", "PATH", path_buffer); printf ("path: %s\n", path_buffer); _searchenv ("searchen.c", "DPATH", path_buffer); printf ("path: %s\n", path_buffer); return 0; /***************** Output ************************ * If the first path that contains cmd.exe is * * in the C: environment and this program is * * not run from another directory with a cmd.exe * * file, the first line of the output should be * * similar to: * path: C:\OS2\cmd.exe */ * Assuming the file searchen.c does not exist in * * the current directory or any of the directories * * in the environment, the next line of the output * * should be similar to: * path: */ } ═══ Related Information ═══ o getenv - Search for Environment Variables o _putenv - Modify Environment Variables o stdlib.h ═══ 6.193. setbuf - Control Buffering ═══ ═══ Format ═══ #include void setbuf(FILE *stream, char *buffer); ═══ Description ═══ Language Level: ANSI, SAA The setbuf function allows you to control buffering for the specified stream. The stream pointer must refer to an open file before any I/O or repositioning has been done. If the buffer argument is NULL, the stream is unbuffered. If not, the buffer must point to a character array of length BUFSIZ, which is the buffer size defined in the stdio.h header file. The system uses the buffer, which you specify, for input/output buffering instead of the default system-allocated buffer for the given stream. The setvbuf function is more flexible than setbuf. There is no return value. Example of setbuf ═══ Example of setbuf ═══ /************************************************************************ * This example opens the file myfile for writing. It then calls the setbuf function to establish a buffer of length BUFSIZ. When string is written to the stream, the buffer buf is used and contains the string before it is flushed to the file. * ************************************************************************/ #include int main(void) { char buf[BUFSIZ]; char string[] = "hello world"; FILE *stream; memset(buf,'\0',BUFSIZ); /* initialize buf to null characters */ stream = fopen("myfile.dat", "wb"); setbuf(stream,buf); /* set up buffer */ fwrite(string, sizeof(string), 1, stream); printf("%s\n",buf); /* string is found in buf now */ fclose(stream); /* buffer is flushed out to myfile.dat */ } ═══ Related Information ═══ o fclose - Close Stream o fflush - Write Buffer to File o _flushall - Write Buffers to Files o fopen - Open Files o setvbuf - Control Buffering o stdio.h ═══ 6.194. _set_crt_msg_handle - Change Runtime Message Output Handle ═══ ═══ Format ═══ #include int _set_crt_msg_handle(int fh); ═══ Description ═══ Language Level: Extension The _set_crt_msg_handle function changes the file handle to which runtime messages are sent, which is usually file handle 2, to fh. Runtime messages include exception handling messages and output from debug memory management routines. Use _set_crt_msg_handle to trap runtime message output in applications where handle 2 is not defined, such as Presentation Manager applications. The file handle fh must be a writable file or pipe handle. Set fh only for the current library environment. The _set_crt_msg_handle function returns the handle to be used for runtime message output. If an handle that is not valid is passed as an argument, it is ignored and no change takes place. Example of _set_crt_msg_handle ═══ Example of _set_crt_msg_handle ═══ /************************************************************************ * This example causes an exception by dereferencing a null pointer and uses _set_crt_msg_handle to send the exception messages to the file crt.out. * ************************************************************************/ #include #include #include #include main() { int fh; char *p=NULL; if (-1 == (fh = open("crt.out",O_CREAT|O_TRUNC|O_RDWR, S_IREAD|S_IWRITE))) { perror("Unable to open crt.out"); return 1; } /* change file handle where messages are sent */ if (_set_crt_msg_handle(fh)!=fh) { perror("could not change msg handle"); return 1; } *p='x'; /* cause an exception, output should be in crt.out */ if (-1 == close(fh)) { perror("Unable to close crt.out"); return(1); } return(0); } ═══ Related Information ═══ o _open - Open File o _fileno - Determine File Handle o _sopen - Open Shared File o stdio.h ═══ 6.195. setjmp - Preserve Environment ═══ ═══ Format ═══ #include int setjmp(jmp_buf env); ═══ Description ═══ Language Level: ANSI, SAA The setjmp macro saves a stack environment that can subsequently be restored by longjmp. The setjmp macro and longjmp function provide a way to perform a nonlocal goto. They are often used in signal handlers. A call to setjmp causes it to save the current stack environment in env. A subsequent call to longjmp restores the saved environment and returns control to a point corresponding to the setjmp call. The values of all variables (except register variables) accessible to the function receiving control contain the values they had when longjmp was called. The values of register variables are unpredictable. Nonvolatile auto variables that are changed between calls to setjmp and longjmp are also unpredictable. The setjmp macro returns the value 0 after saving the stack environment. If setjmp returns as a result of a longjmp call, it returns the value argument of longjmp, or 1 if the value argument of longjmp is 0. There is no return value. Example of setjmp ═══ Example of setjmp ═══ /************************************************************************ * This example stores the stack environment at the statement: if(setjmp(mark) != 0) ... When the system first performs the if statement, it saves the environment in mark and sets the condition to FALSE because setjmp returns a 0 when it saves the environment. The program prints the message: setjmp has been called The subsequent call to function p tests for a local error condition, which can cause it to perform the longjmp function. Then, control returns to the original setjmp function using the environment saved in mark. This time the condition is TRUE because -1 is the return value from the longjmp function. The program then performs the statements in the block and prints: longjmp has been called Then the program calls the recover function and exits. * ************************************************************************/ #include #include jmp_buf mark; void p(void); void recover(void); int main(void) { if (setjmp(mark) != 0) { printf("longjmp has been called\n"); recover(); exit(1); } printf("setjmp has been called\n"); . . . p(); . . . } void p(void) { int error = 0; . . . error = 9; . . . if (error != 0) longjmp(mark, -1); . . . } void recover(void) { . . . } ═══ Related Information ═══ o longjmp - Restore Stack Environment o goto o volitile and constant Qualifiers o auto Storage Class Specifier o setjmp.h ═══ 6.196. setlocale - Set Locale ═══ ═══ Format ═══ #include char *setlocale(int category, const char *locale); ═══ Description ═══ Language Level: ANSI, SAA The setlocale function changes or queries variables, defined in the locale.h header file, that indicate location. The values for category are listed below. Category Purpose LC_ALL Names entire locale of program. LC_COLLATE Affects behavior of the strcoll and strxfrm functions. LC_CTYPE Affects behavior of the character handling functions. LC_MONETARY Affects monetary information returned by localeconv. LC_NUMERIC Affects the decimal-point character for the formatted input/output and string conversion functions, and the nonmonetary formatting information returned by the localeconv function. LC_TIME Affects behavior of the strftime function. LC_TOD Affects the behavior of the time functions. You can set the value of locale to "C", "",LC_C, LC_C_GERMANY, LC_C_FRANCE, LC_C_SPAIN, LC_C_ITALY, LC_C_JAPAN, LC_C_USA or LC_C_UK. A locale value of "C" indicates the default C environment. A locale value of "" tells setlocale to use the default locale for the implementation. The setlocale function returns a pointer to the string associated with the specified category for the new locale. The string can be used on a subsequent call to restore that part of the program's locale. Note: Because the string to which a successful call to setlocale points may be overwritten by subsequent calls to the setlocale function, you should copy the string if you plan to use it later. On error, the setlocale function returns NULL and the program's locale is not changed. To query the locale, give a NULL as the second parameter. For example, to query all the categories of your locale, enter the following statement: char *string = setlocale(LC_ALL, NULL); Example of setlocale ═══ Example of setlocale ═══ /************************************************************************ * This example sets the locale of the program to be LC_C_FRANCE and prints the string that is associated with the locale. * ************************************************************************/ #include #include char *string; int main(void) { string = setlocale(LC_ALL, LC_C_FRANCE); if (string != NULL) printf(" %s \n",string); } ═══ Related Information ═══ o getenv - Search for Environment Variables o localeconv - Query Locale Conventions o _putenv - Modify Environment Variables o locale.h ═══ 6.197. _setmode - Set File Translation Mode ═══ ═══ Format ═══ #include #include int _setmode(int handle, int mode); ═══ Description ═══ Language Level: Extension The _setmode function sets the translation mode of the file given by handle to mode. The mode must be one of the values in the following table: Value Meaning O_TEXT Sets the translated text mode. Carriage-return line-feed combinations are translated into a single line feed on input. Line-feed characters are translated into carriage-return line-feed combinations on output. O_BINARY Sets the binary (untranslated) mode. The above translations are suppressed. Use the _setmode function to change the translation mode of a file handle. The translation mode only affects the _read and _write functions. This function does not affect the translation mode of streams. If a file handle is acquired other than by a call to _open, _creat, _sopen or _fileno, The _setmode function should be called for that file handle before using it within the _read or _write functions. The _setmode function returns the previous translation mode if successful. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EBADF The file handle is not a handle for an open file. EINVAL Incorrect mode (neither O_TEXT nor O_BINARY) Example of _setmode ═══ Example of _setmode ═══ /************************************************************************ * This example uses _open to create the file SETMODE.DAT and writes to it. The program then uses _setmode to change the translation mode of SETMODE.DAT from binary to text. * ************************************************************************/ #include #include #include #include #include #define FILENAME "SETMODE.DAT" /* routine to validate return codes */ void ckrc(rc) { if ((rc) == -1) { printf("Unexpected return code = -1\n"); _exit(1); } } int main(void) { int h; int xfer; int mode; char rbuf[256]; char wbuf[] = "123\n456\n"; ckrc(h = _open(FILENAME, O_CREAT | O_RDWR | O_TRUNC | O_TEXT, S_IREAD | S_IWRITE)); ckrc(_write(h,wbuf,sizeof(wbuf))); /* write the file (text) */ ckrc(_lseek(h,0,SEEK_SET)); /* seek back to the start of the file */ ckrc(xfer = _read(h,rbuf,5)); /* read the file text */ printf("Read in %d characters (4 expected)\n",xfer); ckrc(mode = _setmode(h,O_BINARY)); if (mode == O_TEXT) printf("Mode changed from binary to text\n"); else printf("Previous mode was not text (unexpected)\n"); ckrc(xfer = _read(h,rbuf,5)); /* read the file (binary) */ printf("Read in %d characters (5 expected)\n",xfer); ckrc(_close(h)); remove (FILENAME); return 0; /**************** The expected output is: ***************************** Read in 4 characters (4 expected) Mode changed from binary to text Read in 5 characters (5 expected) */ } ═══ Related Information ═══ o _creat - Create New File o _open - Open File o _sopen - Open Shared File o _read - Read Into Buffer o _write - Writes from Buffer to File o fcntl.h o io.h o share.h o sys\stat.h ═══ 6.198. setvbuf - Control Buffering ═══ ═══ Format ═══ #include int setvbuf(FILE *stream, char *buf, int type, size_t size); ═══ Description ═══ Language Level: ANSI, SAA The setvbuf function allows control over the buffering strategy and buffer size for a specified stream. The stream must refer to a file that has been opened, but not read or written to. The array pointed to by buf designates an area that you provide that the C library may choose to use as a buffer for the stream. A buf value of NULL indicates that no such area is supplied and that the C library is to assume responsibility for managing its own buffers for the stream. If you supply a buffer, it must exist until the stream is closed. If type is _IOFBF or _IOLBF, size is the size of the supplied buffer. If buf is NULL, the C library will take size as the suggested size for its own buffer. If type is _IONBF, both buf and size are ignored. Value Meaning _IONBF No buffer is used. _IOFBF Full buffering is used for input and output. Use buf as the buffer and size as the size of the buffer. _IOLBF Line buffering is used. The buffer is flushed when a new-line character is written, when the buffer is full, or when input is requested. The value for size must be greater than 0. The setvbuf function returns a 0 if successful and nonzero if an invalid value was specified in the parameter list, or if the request cannot be performed. Warning: The array used as the buffer must still exist when the specified stream is closed. For example, if the buffer is declared within the scope of a function block, the stream must be closed before the function is terminated and frees the storage allocated to the buffer. Example of setvbuf ═══ Example of setvbuf ═══ /************************************************************************ * This example sets up a buffer of buf for stream1 and specifies that input to stream2 is to be unbuffered. * ************************************************************************/ #include #define BUF_SIZE 1024 char buf[BUF_SIZE]; FILE *stream1, *stream2; int main(void) { stream1 = fopen("myfile1.dat", "r"); stream2 = fopen("myfile2.dat", "r"); /* stream1 uses a user-assigned buffer of BUF_SIZE bytes */ if (setvbuf(stream1, buf, _IOFBF, sizeof(buf)) != 0) printf("Incorrect type or size of buffer\n"); /* stream2 is unbuffered */ if (setvbuf(stream2, NULL, _IONBF, 0) != 0) printf("Incorrect type or size of buffer\n"); . . . } ═══ Related Information ═══ o fclose - Close Stream o fflush - Write Buffer to File o _flushall - Write Buffers to Files o fopen - Open Files o setbuf - Control Buffering o stdio.h ═══ 6.199. signal Install Interrupt Handlers ═══ ═══ Format ═══ #include void (*signal(int sig, void (*sig_handler)(int)))(int); ═══ Description ═══ Language Level: ANSI, SAA, Extension The signal function assigns the interrupt signal sig to the signal handler sig_handler. The sig argument must be one of the signal constants defined in . The meanings of the values of sig are as follows: Value Meaning SIGABRT Abnormal termination signal sent by the abort function. Default action is to end the program with exit code 3. SIGBREAK Ctrl-Break signal. Default action is to end the program with exit code 99. SIGFPE Floating-point exceptions that are not masked, such as overflow, division by zero, and invalid operation. Default action is to end the program with exit code 99 and provide a machine-state dump. SIGILL Instruction not allowed. Default action is to end the program with exit code 99 and provide a machine-state dump. SIGINT Ctrl-C signal. Default action is to end the program with exit code 99. SIGSEGV Access to memory not valid. Default action is to end the program with exit code 99 and provide a machine-state dump. SIGTERM Program termination signal sent by the user. Default action is to end the program with exit code 99. SIGUSR1 Defined by the user. Default action is to ignore the signal. SIGUSR2 Defined by the user. Default action is to ignore the signal. SIGUSR3 Defined by the user. Default action is to ignore the signal. Signals can be reported as a result of a machine interrupt (for example, division by zero) or by an explicit request to report a signal by using the raise function. The sig_handler argument must be either the SIG_DFL or SIG_IGN constant, also defined in , or the address of a function that takes an integer argument (the signal). The action taken when the interrupt signal is received depends on the value of sig_handler: Value Meaning SIG_DFL This is the initial setting for all signals. For most signals, the system default is to end the program. All files controlled by the process are closed, but buffers are not flushed. A machine-state dump is provided for SIGFPE, SIGILL, and SIGSEGV. The default response for the user-defined signals (SIGUSR1, SIGUSR2, and SIGUSR3) is to ignore them. SIG_IGN The interrupt signal is ignored. SIG_HANDLER Installs the specified function as the signal handler for the given signal. For all signals, the function is passed two arguments. The first argument is the signal number and the second is 0, unless the signal is SIG_FPE. For SIG_FPE signals, the second argument passed is a floating-point error signal as defined in . If the signal handling function returns, the calling process resumes running immediately following the point at which it received the interrupt signal. When a signal is reported and the sig_handler called, signal handling for that signal is reset to the default. Depending on the purpose of the signal handler, it can be desirable to reestablish the signal handling from within the sig_handler function. You can also reset the default handling with an explicit call to signal. Signals and signal handlers are not shared between threads. If you do not establish a signal handler within a thread, the default signal handling will be used regardless of what handlers you may have established in other concurrent threads. Note: If an exception occurs in a math or critical library function, it is handled by the C/C++ Tools exception handler. Your sig_handler will not be called. All calls to the signal function return the address of the previous handler for the re-assigned signal. A return value of SIG_ERR, defined in , indicates an error, and errno is set to EINVAL. The possible causes of the error are an incorrect sig value or an undefined value for func. Example of signal ═══ Example of signal ═══ /************************************************************************ * In the following example, the call to signal in main establishes the function handler to process the interrupt signal raised by abort. An error value returned from this call to signal causes the program to end with a printed error message. * ************************************************************************/ #include #include #include void handler(int sig) { printf("Registered signal type for abort = %d\n", sig); printf("Abort should not flush this line"); } int main(void) { if (signal(SIGABRT, handler) == SIG_ERR) { perror("Could not set SIGABRT"); exit(-1); } abort(); /* signal raised by abort */ /* The expected output is: Registered signal type for abort = 5 */ } ═══ Related Information ═══ o abort - Stop a Program o atexit - Record Program Termination Function o exit - End Program o _exit - End Process o _fpreset - Reset Floating-Point Unit o raise - Send Signal o _spawnl -_spawnvpe -Start and Run Child Processes o signal.h ═══ 6.200. sin - Calculate Sine ═══ ═══ Format ═══ #include double sin(double x); /* Calculate sine of x */ ═══ Description ═══ Language Level: ANSI, SAA The sin function calculates the sine of x, with x expressed in radians. Example of sin ═══ Example of sin ═══ /************************************************************************ * This example computes y as the sine of у/2. * ************************************************************************/ #include #include int main(void) { double pi, x, y; pi = 3.1415926535; x = pi/2; y = sin(x); printf("sin( %lf ) = %lf\n", x, y); } /********************* Output should be similar to: ************* sin( 1.570796 ) = 1.000000 */ ═══ Related Information ═══ o asin - Calculate Arcsine o _fasin - Calculate Arcsine o _fcossin - Calculate Cosine and Sine o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine o sinh - Calculate Hyperbolic Sine o math.h ═══ 6.201. sinh - Calculate Hyperbolic Sine ═══ ═══ Format ═══ #include double sinh(double x); /* Calculate hyperbolic sine of x */ ═══ Description ═══ Language Level: ANSI, SAA The sinh function calculates the hyperbolic sine of x, with x expressed in radians. If the result is too large, sinh sets errno to ERANGE and returns the value HUGE_VAL (positive or negative, depending on the value of x). Example of sinh ═══ Example of sinh ═══ /************************************************************************ * This example computes y as the hyperbolic sine of у/2. * ************************************************************************/ #include #include int main(void) { double pi, x, y; pi = 3.1415926535; x = pi/2; y = sinh(x); printf("sinh( %lf ) = %lf\n", x, y); } /********************* Output should be similar to: ************* sinh( 1.570796 ) = 2.301299 */ ═══ Related Information ═══ o asin - Calculate Arcsine o cosh - Calculate Hyperbolic Cosine o _fasin - Calculate Arcsine o _fcossin - Calculate Cosine and Sine o _fsin - Calculate Sine o _fsincos - Calculate Sine and Cosine o sin - Calculate Sine o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.202. _sopen - Open Shared File ═══ ═══ Format ═══ #include #include #include #include int _sopen(char *pathname, int oflag, int shflag , int pmode); ═══ Description ═══ Language Level: Extension The _sopen function opens the file specified by pathname and prepares the file for subsequent shared reading or writing as defined by oflag and shflag. The oflag is an integer expression formed by combining one or more of the constants defined in . When more than one constant is given, the constants are joined with the OR operator (|). Oflag Meaning O_APPEND Reposition the file pointer to the end of the file before every write operation. O_CREAT Create and open a new file. This flag has no effect if the file specified by pathname exists. O_EXCL Return an error value if the file specified by pathname exists. This flag applies only when used with O_CREAT. O_RDONLY Open the file for reading only. If this flag is given, neither O_RDWR nor O_WRONLY can be given. O_RDWR Open the file for both reading and writing. If this flag is given, neither O_RDONLY nor O_WRONLY can be given. O_TRUNC Open and truncate an existing file to 0 length. The file must have write permission. The contents of the file are destroyed. On the OS/2 operating system, do not specify O_TRUNC with O_RDONLY. O_WRONLY Open the file for writing only. If this flag is given, neither O_RDONLY nor O_RDWR can be given. O_BINARY Open the file in binary (untranslated) mode. (See fopen. for a description of binary mode.) O_TEXT Open the file in text (translated) mode. (See fopen. for a description of text mode.) The shflag argument is one of the following constants, defined in . Shflag Meaning SH_DENYRW Deny read and write access to file SH_DENYWR Deny write access to file SH_DENYRD Deny read access to file SH_DENYNO Permit read and write access. There is no default value for the shflag. The pmode argument is an integer expression containing one or both of the constants S_IWRITE and S_IREAD, defined in . The pmode argument is required only when O_CREAT is specified. If the file does not exist, pmode specifies the permission settings of the file, which are set when the new file is closed for the first time. If the file exists, the pmode argument is ignored. The pmode argument is an integer expression containing one or both of the constants S_IWRITE and S_IREAD. The meanings of the pmode argument are in the following table. Value Meaning S_IWRITE Writing permitted S_IREAD Reading permitted S_IREAD | S_IWRITE Reading and writing permitted. If write permission is not given, the file is read only. On the OS/2 operating system, all files are readable; you cannot give write-only permission. Thus, the modes S_IWRITE and S_IREAD | S_IWRITE are equivalent. Specifying a pmode of S_IREAD is similar to making a file read-only with the ATTRIB system command. The _sopen function applies the current file permission mask to pmode before setting the permissions. (See _umask - Sets File Mask of Current Process for information on file permission masks.) The _sopen function returns a file handle for the opened file. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS The given path name is a directory, but the file is read-only and an open for writing was attempted, or a sharing violation occurred. EEXIST The O_CREAT and O_EXCL flags are specified, but the named file already exists. EMFILE No more file handles are available. ENOENT The file or path name was not found. EINVAL An incorrect argument was passed. EOS2ERR The call to the operating system was not successful. Example of _sopen ═══ Example of _sopen ═══ /************************************************************************ * This example opens the file sample.dat for shared reading and writing using _sopen. It then opens the file for shared reading. * ************************************************************************/ #include #include #include #include #include int main(void) { int fh1, fh2; printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); /* share open the file for reading and writing */ if (-1 == (fh1 = _sopen("sample.dat",O_RDWR,SH_DENYNO) )) { perror("_sopen failed"); return 1; } /* share open the file for reading only */ if (-1 == (fh2 = _sopen("sample.dat",O_RDONLY,SH_DENYNO) )) { perror("_sopen failed"); _close(fh1); return 1; } printf("File sample.dat successfully opened for sharing.\n"); _close(fh1); _close(fh2); return 0; /***************** The expected output is: **************************** Creating sample.dat. File sample.dat successfully opened for sharing. */ } ═══ Related Information ═══ o _close - Closes File Associated with Handle o _creat - Create New File o _open - Open File o _fdopen - Associates Input Or Output With File o fopen - Open Files o _sopen - Open Shared File o _umask - Sets File Mask of Current Process o fcntl.h o io.h o share.h o sys\stat.h ═══ 6.203. _spawnl -_spawnvpe -Start and Run Child Processes ═══ ═══ Format ═══ #include int _spawnl(int modeflag, char *pathname, char *arg0, char *arg1, ..., char *argn, NULL); int _spawnlp(int modeflag, char *pathname, char *arg0, char *arg1, ..., char *argn, NULL); int _spawnle(int modeflag, char *pathname, char *arg0, char *arg1, ..., char *argn, NULL, char *envp[ ]); int _spawnlpe(int modeflag, char *pathname, char *arg0, char *arg1, ..., char *argn, NULL, char *envp[ ]); int _spawnv(int modeflag, char *pathname, char *argv[ ]); int _spawnvp(int modeflag, char *pathname, char *argv[ ]); int _spawnve(int modeflag, char *pathname, char *argv[ ], char *envp[ ]); int _spawnvpe(int modeflag, char *pathname, char *argv[ ], char *envp[ ]) ═══ Description ═══ Language Level: Extension Each of the _spawn functions creates and runs a new child process. Enough storage must be available for loading and running the child process. All of the _spawn functions are versions of the same routine; the letters at the end determine the specific variation: Letter Variation p Uses PATH environment variable to find the file to be run l Lists command-line arguments separately v Passes to the child process an array of pointers to command-line arguments e Passes to the child process an array of pointers to environment strings. The modeflag argument determines the action taken by the parent process before and during the _spawn. The following values for modeflag are defined in . Value Meaning P_WAIT Suspend the parent process until the child process is complete. P_NOWAIT Continue to run the parent process concurrently. P_OVERLAY Start the child process, and then if successful, end the parent process. (This has the same effect as _exec calls.) The pathname argument specifies the file to run as the child process. The pathname can specify a full path (from the root), a partial path (from the current working directory), or just a file name. If pathname does not have a file name extension or end with a period, the _spawn functions add the extension .EXE and search for the file. If pathname has an extension, only that extension is used. If pathname ends with a period, the _spawn functions search for pathname with no extension. The _spawnlp, _spawnlpe, _spawnvp, and _spawnvpe functions search for pathname (using the same procedures) in the directories specified by the PATH environment variable. You pass arguments to the child process by giving one or more pointers to character strings as arguments in the _spawn routine. These character strings form the argument list for the child process. The argument pointers can be passed as separate arguments (_spawnl, _spawnle, _spawnlp, and _spawnlpe) or as an array of pointers (_spawnv, _spawnve, _spawnvp, and _spawnvpe). At least one argument, either arg0 or argv[0], must be passed to the child process. By convention, this argument is a copy of the pathname argument. However, a different value will not produce an error. Use the _spawnl, _spawnle, _spawnlp, and _spawnlpe routines in cases where you know the number of arguments. The arg0 is usually a pointer to pathname. The arg1 through argn arguments are pointers to the character strings forming the new argument list. Following argn, there must be a NULL pointer to mark the end of the argument list. The _spawnv, _spawnve, _spawnvp, and _spawnvpe functions are useful when the number of arguments to the child process is variable. Pointers to the arguments are passed as an array, argv. The argv[0] argument is usually a pointer to the pathname. The argv[1] through argv[n] arguments are pointers to the character strings forming the new argument list. The argv[n+1] argument must be a NULL pointer to mark the end of the argument list. Files that are open when a _spawn call is made remain open in the child process. In the _spawnl, _spawnlp, _spawnv, and _spawnvp calls, the child process inherits the environment of the parent. The _spawnle, _spawnlpe, _spawnve, and _spawnvpe functions let you alter the environment for the child process by passing a list of environment settings through the envp argument. The envp argument is an array of character pointers, each element of which points to a null-terminated string, that defines an environment variable. Such a string has the form: NAME=value where NAME is the name of an environment variable, and value is the string value to which that variable is set. (Notice that value is not enclosed in double quotation marks.) The final element of the envp array should be NULL. When envp itself is NULL, the child process inherits the environment settings of the parent process. Note: Signal settings are not preserved in child processes created by calls to _spawn functions. The signal settings are reset to the default in the child process. The return from a spawn has one of two different meanings. The return value of a synchronous spawn is the exit status of the child process. The return value of an asynchronous spawn is the process identification of the child process. You can use the _wait or _cwait functions to get the child process exit code if an asynchronous spawn was done. A return value of -1 indicates an error (the child process is not started), and errno is set to one of the following values: Value Meaning EAGAIN The limit of the number of processes that the OS/2 operating system permits has been reached. EINVAL The modeflag argument is incorrect. ENOENT The file or path name was not found or was not specified correctly. ENOEXEC The specified file is not executable or has an incorrect executable file format. ENOMEM Not enough storage is available to run the child process. Example of _spawnl - _spawnvpe ═══ Example of _spawnl - _spawnvpe ═══ /************************************************************************ * This example shows calls to four of the eight _spawn routines. When called without arguments from the command line, the program first runs the code for case PARENT. It spawns a copy of itself, waits for its child to run, then spawns a second child. The instructions for the child are blocked to run only if argv[0] and one parameter were passed (case CHILD). In its turn, each child spawns a grandchild as a copy of the same program. The grandchild instructions are blocked by the existence of two passed parameters. The grandchild is permitted to overlay the child. Each of the processes prints a message identifying itself. * ************************************************************************/ #include #include #define PARENT 1 #define CHILD 2 #define GRANDCHILD 3 int main(int argc, char **argv, char **envp) { int result; char *args[4]; switch(argc) { case PARENT: /* no argument was passed: spawn child and wait */ result = _spawnle(P_WAIT, argv[0], argv[0], "one", NULL, envp); if (result) abort(); args[0] = argv[0]; args[1] = "two"; args[2] = NULL; /* spawn another child, and wait for it */ result = _spawnve(P_WAIT, argv[0], args, envp); if (result) abort(); printf("Parent process ended\n"); _exit(0); case CHILD: /* one argument passed: allow grandchild to overlay */ printf("child process %s began\n", argv[1]); if (*argv[1] == 'o') /* child one? */ { _spawnl(P_OVERLAY, argv[0], argv[0], "one", "two", NULL); abort(); /* not executed because child was overlaid */ } if (*argv[1] == 't') /* child two? */ { args[0] = argv[0]; args[1] = "two"; args[2] = "one"; args[3] = NULL; _spawnv(P_OVERLAY, argv[0], args); abort(); /* not executed because child was overlaid */ } abort(); /* argument not valid */ case GRANDCHILD: /* two arguments passed */ printf("grandchild %s ran\n", argv[1]); _exit(0); } /****** The output should be similar to: ************* child process one began grandchild one ran child process two began Parent process ended grandchild two ran */ } ═══ Related Information ═══ o abort - Stop a Program o _cwait - Wait for Child Process o _execl - _execvp - Load and Run Child Process o exit - End Program o _exit - End Process o _wait - Wait for Child Process o process.h ═══ 6.204. _splitpath - Decompose Path Name ═══ ═══ Format ═══ #include void _splitpath(char *path, char *drive, char *dir, char *fname, char *ext); ═══ Description ═══ Language Level: Extension The _splitpath function decomposes an existing path name path into its four components. The path should point to a buffer containing the complete path name. The maximum size necessary for each buffer is specified by the _MAX_DRIVE, _MAX_DIR, _MAX_FNAME, and _MAX_EXT constants defined in . The other arguments point to the following buffers used to store the path name elements: Buffer Description drive Contains the drive letter followed by a colon (:) if a drive is specified in path. dir Contains the path of subdirectories, if any, including the trailing slash. Slashes (/), backslashes (\), or both may be present in path. fname Contains the base file name without any extensions. ext Contains the file name extension, if any, including the leading period (.). The return parameters contain empty strings for any path name components not found in path. There is no return value. Example of _splitpath ═══ Example of _splitpath ═══ /************************************************************************ * This example builds a file name path from the specified components, and then extracts the individual components. * ************************************************************************/ #include #include int main(void) { char path_buffer [_MAX_PATH]; char drive [_MAX_DRIVE]; char dir [_MAX_DIR]; char fname [_MAX_FNAME]; char ext [_MAX_EXT]; _makepath (path_buffer, "c", "qc\\bob\\eclibref\\e", "makepath", "c"); printf ("Path created with _makepath: %s\n\n", path_buffer); _splitpath (path_buffer, drive, dir, fname, ext); printf ("Path extracted with _splitpath:\n"); printf ("drive: %s\n", drive); printf ("directory: %s\n", dir); printf ("file name: %s\n", fname); printf ("extension: %s\n", ext); return 0; /************ The output should be similar to: ******** Path created with _makepath: c:qc\bob\eclibref\e\makepath.c Path extracted with _splitpath: drive: c: directory: qc\bob\eclibref\e\ file name: makepath extension: .c */ } ═══ Related Information ═══ o _fullpath - Get Full Path Name of Partial Path o _getcwd - Get Path Name of Current Directory o _getdcwd - Get Full Path Name of Current Directory o _makepath - Create Path o stdlib.h ═══ 6.205. sprintf - Formatted Print to Buffer ═══ ═══ Format ═══ #include int sprintf(char *buffer, const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, Extension The sprintf function formats and stores a series of characters and values in the array buffer. Any argument-list is converted and put out according to the corresponding format specification in the format-string. The format-string consists of ordinary characters and has the same form and function as the format-string argument for the printf function. See printf for a description of the format-string and arguments. In extended mode, sprintf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. The sprintf function returns the number of characters written in the array, not counting the ending null character. Example of sprintf ═══ Example of sprintf ═══ /************************************************************************ * The following example uses sprintf to format and print various data. * ************************************************************************/ #include char buffer[200]; int i, j; double fp; char *s = "baltimore"; char c; int main(void) { c = 'l'; i = 35; fp = 1.7320508; /* Format and print various data */ j = sprintf(buffer, "%s\n", s); j += sprintf(buffer+j, "%c\n", c); j += sprintf(buffer+j, "%d\n", i); j += sprintf(buffer+j, "%f\n", fp); printf("string:\n%s\ncharacter count = %d\n", buffer, j); } /********************* Output should be similar to: ************* string: baltimore l 35 1.732051 character count = 24 */ ═══ Related Information ═══ o _cprintf - Print Characters to Screen o fprintf - Write Formatted Data o printf - Formatted Print o sscanf - Read Data o Infinity and NaN Support o vfprintf - Print Argument Data o vprintf - Print Argument Data o vsprintf - Print Argument Data o stdio.h ═══ 6.206. sqrt - Calculate Square Root ═══ ═══ Format ═══ #include double sqrt(double x); ═══ Description ═══ Language Level: ANSI, SAA The sqrt function calculates the nonnegative value of the square root of x. The sqrt function returns the square root result. If x is negative, the function sets errno to EDOM, and returns 0. Example of sqrt ═══ Example of sqrt ═══ /************************************************************************ * This example computes the square root of the quantity passed as the first argument to main. It prints an error message if you pass a negative value. * ************************************************************************/ #include #include #include int main(int argc, char ** argv) { char * rest; double value; if ( argc != 2 ) printf( "Usage: %s value\n", argv[0] ); else { value = strtod( argv[1], &rest ); if ( value < 0.0 ) perror( "sqrt of a negative number" ); else printf("sqrt( %lf ) = %lf\n", value, sqrt( value )); } } /******************** If the input is 45, ***************************** **************** then the output should be similar to: ********** sqrt( 45.000000 ) = 6.708204 */ ═══ Related Information ═══ o exp - Exponential Function o _fsqrt - Calculate Square Root o hypot - Calculate Hypotenuse o log - Calculate Natural Logarithm o log10 - Calculate Base 10 Logarithm o pow - Compute Power o math.h ═══ 6.207. srand - Set Seed for rand Function ═══ ═══ Format ═══ #include void srand(unsigned int seed); ═══ Description ═══ Language Level: ANSI, SAA The srand function sets the starting point for producing a series of pseudo-random integers. If srand is not called, the rand seed is set as if srand(1) was called at program start. Any other value for seed sets the generator to a different starting point. The rand function generates the pseudo-random numbers. There is no return value. Example of srand ═══ Example of srand ═══ /************************************************************************ * This example first calls srand with a value other than 1 to initiate the random value sequence. Then the program computes 5 random values for the array of integers called ranvals. * ************************************************************************/ #include #include int main(void) { int i, ranvals[5]; srand(17); for (i = 0; i < 5; i++) { ranvals[i] = rand(); printf("Iteration %d ranvals [%d] = %d\n", i+1, i, ranvals[i]); } } /****************** Output should be similar to: **************** Iteration 1 ranvals [0] = 24107 Iteration 2 ranvals [1] = 16552 Iteration 3 ranvals [2] = 12125 Iteration 4 ranvals [3] = 9427 Iteration 5 ranvals [4] = 13152 */ ═══ Related Information ═══ o rand - Generate Random Number o stdlib.h ═══ 6.208. sscanf - Read Data ═══ ═══ Format ═══ #include int sscanf(const char *buffer, const char *format, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, Extension The sscanf function reads data from buffer into the locations given by argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string. See scanf for a description of the format-string. The sscanf function returns the number of fields that were successfully converted and assigned. The return value does not include fields that were read but not assigned. In extended mode, sscanf also reads in the strings the strings "INFINITY", "INF", and "NAN" (in upper or lowercase) and converts them to the corresponding floating-point value. The sign of the value is determined by the format specification. See Infinity and NaN Support for more information on infinity and NaN values. The return value is EOF when the end of the string is encountered before anything is converted. Example of sscanf ═══ Example of sscanf ═══ /************************************************************************ * This example uses sscanf to read various data from the string tokenstring, and then displays the data. * ************************************************************************/ #include #define SIZE 81 char *tokenstring = "15 12 14"; int i; float fp; char s[SIZE]; char c; int main(void) { /* Input various data */ sscanf(tokenstring, "%s %c%d%f", s, &c, &i, &fp); /* If there were no space between %s and %c, */ /* sscanf would read the first character following */ /* the string, which is a blank space. */ /* Display the data */ printf("string = %s\n",s); printf("character = %c\n",c); printf("integer = %d\n",i); printf("floating-point number = %f\n",fp); } /***************** Output should be similar to: ***************** string = 15 character = 1 integer = 2 floating-point number = 14.000000 */ ═══ Related Information ═══ o _cscanf - Read Data from Keyboard o fscanf - Read Formatted Data o scanf - Read Data o sprintf - Formatted Print to Buffer o Infinity and NaN Support o stdio.h ═══ 6.209. _stat - Get Information about File or Directory ═══ ═══ Format ═══ #include #include int _stat(const char *pathname, struct stat *buffer); ═══ Description ═══ Language Level: Extension The _stat function stores information about the file or directory specified by pathname in the structure to which buffer points. The _stat structure, defined in , contains the following fields: Field Value st_mode Bit mask for file-mode information. The _stat function sets the S_IFCHR bit if handle refers to a device. The S_IFDIR bit is set if pathname specifies a directory. The S_IFREG bit is set if pathname specifies an ordinary file. User read/write bits are set according to the permission mode of the file. The S_IEXEC bit is set using the file name extension. The other bits are undefined. F E D C B A 9 8 7 6 5 4 3 2 1 0 │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘       S_IFREG──────┘ │ │ │ │ └──────execute/search permission, (regular file) │ │ │ │ owner (S_IEXEC) S_IFDIR────────┘ │ │ └────────write permission, owner S_IFCHR──────────┘ └──────────read permission, owner st_dev Drive number of the disk containing the file. st_rdev Drive number of the disk containing the file (same as st_dev). st_nlink Always 1. st_size Size of the file in bytes. st_atime Time of last modification of file. st_mtime Same as st_atime if not provided by the file system. st_ctime Same as st_atime if not provided by the file system. Note: If the given pathname specifies only a device (for example C:\), _stat returns an error, and fields in the _stat structure are not meaningful. The _stat function returns the value 0 if the file status information is obtained. A return value of -1 indicates an error, and errno is set to ENOENT, indicating that the file name or path name could not be found. Example of _stat ═══ Example of _stat ═══ /************************************************************************ * This example requests that the status information for the file test.exe be placed into the structure buf. If the request is successful and the file is executable, the example runs test.exe. * ************************************************************************/ #include #include #include #include int main(void) { struct stat buf; if (_stat("test.exe", &buf) == 0) { if ( (buf.st_mode & S_IFREG) && (buf.st_mode & S_IEXEC) ) _execl("test.exe", "test", NULL); /* file is executable */ } else printf("File could not be found\n"); return 0; /* The source for test.exe #include int main(void) { */ puts("test.exe is an executable file"); } */ */ /********** The output should be similar to: *********** test.exe is an executable file */ } ═══ Related Information ═══ o _fstat - Information about Open File o sys\stat.h o sys\types.h ═══ 6.210. _status87 - Get Floating-Point Status Word ═══ ═══ Format ═══ #include /* also defined in */ unsigned int _status87(void); ═══ Description ═══ Language Level: Extension The _status87 function gets the current floating-point status word. The floating-point status word is a combination of the numeric coprocessor status word and other conditions detected by the numeric exception handler, such as floating-point stack underflow and overflow. The bits in the value returned reflect the floating-point status for the current thread only before the call was made. The _status87 function does not affect any other threads that may be processing. Example of _status87 ═══ Example of _status87 ═══ /************************************************************************ * This example uses _status87 to get the value of the floating-point status word. * ************************************************************************/ #include #include double a = 1e-40, b; float x, y; int main(void) { printf("status = 0x%.4x - clear\n", _status87( )); /* change control word to mask all exceptions */ _control87(0x037f,0xffff); y = a; /* store into y is inexact and causes underflow */ printf("status = 0x%.4X - inexact, underflow\n", _status87( )); /* reinitialize the floating point unit */ _fpreset(); /* change control word to mask all exceptions */ _control87(0x037f,0xffff); b = y; /* y is denormal */ printf("status = 0x%.4X - denormal\n", _status87()); /* reinitialize the floating point unit */ _fpreset(); return 0; /* The expected output is: status = 0x0000 - clear status = 0x0030 - inexact, underflow status = 0x0002 - denormal */ } ═══ Related Information ═══ o _clear87 - Clear Floating-Point Status Word o _control87 - Set Floating-Point Status Word o _fpreset - Reset Floating-Point Unit o float.h ═══ 6.211. strcat - Concatenate Strings ═══ ═══ Format ═══ #include char *strcat(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strcat function concatenates string2 to string1 and ends the resulting string with the null character. The strcat function operates on null-terminated strings. The string arguments to the function should contain a null character (\0) marking the end of the string. No length checking is performed. Do not use a literal string for a string1 value, although string2 may be a literal string. If the storage of string1 overlaps the storage of string2, the behavior is undefined. The strcat function returns a pointer to the concatenated string (string1). Example of strcat ═══ Example of strcat ═══ /************************************************************************ * This example creates the string "computer program" using strcat. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char buffer1[SIZE] = "computer"; char * ptr; ptr = strcat( buffer1, " program" ); printf( "buffer1 = %s\n", buffer1 ); } /***************** Output should be similar to: ***************** computer program */ ═══ Related Information ═══ o strchr - Search for Character o strcmp - Compare Strings o strcpy - Copy Strings o strcspn - Compare Strings o strncat - Concatenate Strings o wcscat - Append wchar_t Strings o wcsncat - Concatenate wchar_t Strings o string.h ═══ 6.212. strchr - Search for Character ═══ ═══ Format ═══ #include char *strchr(const char *string, int c); ═══ Description ═══ Language Level: ANSI, SAA The strchr function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr function operates on null-terminated strings. The string arguments to the function should contain a null character (\0) marking the end of the string. The strchr function returns a pointer to the first occurrence of c converted to a character in string. The function returns NULL if the ending null character is not found. Example of strchr ═══ Example of strchr ═══ /************************************************************************ * This example finds the first occurrence of the character p in "computer program". * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char buffer1[SIZE] = "computer program"; char * ptr; int ch = 'p'; ptr = strchr( buffer1, ch ); printf( "The first occurrence of %c in '%s' is '%s'\n", ch, buffer1, ptr ); } /***************** Output should be similar to: ***************** The first occurrence of p in 'computer program' is 'puter program' */ ═══ Related Information ═══ o strcmp - Compare Strings o strcspn - Compare Strings o strncmp - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcsspn - Search wchar_t Characters in String o string.h ═══ 6.213. strcmp - Compare Strings ═══ ═══ Format ═══ #include int strcmp(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strcmp function compares string1 and string2. The function operates on null-terminated strings. The string arguments to the function should contain a null character (\0) marking the end of the string. The strcmp function returns a value indicating the relationship between the two strings, as follows: Value Meaning Less than 0 string1 less than string2 0 string1 identical to string2 Greater than 0 string1 greater than string2. Example of strcmp ═══ Example of strcmp ═══ /************************************************************************ * This example compares the two strings passed to main using strcmp. * ************************************************************************/ #include #include int main(int argc, char ** argv) { int result; if ( argc != 3 ) { printf( "Usage: %s string1 string2\n", argv[0] ); } else { result = strcmp( argv[1], argv[2] ); if ( result == 0 ) printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] ); else if ( result < 0 ) printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] ); else printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] ); } } /**************** If the input is the strings ************************* *********** "is this first?" and "is this before that one?", ********** ****************** then the expected output is: ***************** "is this first?" is greater than "is this before that one?" */ ═══ Related Information ═══ o strcmpi - Compare Strings o strcoll - Compare Strings o strcspn - Compare Strings o stricmp - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.214. strcmpi - Compare Strings ═══ ═══ Format ═══ #include int strcmpi(const char *string1, const char *string2); ═══ Description ═══ Language Level: Extension The strcmpi function compares string1 and string2 without sensitivity to case. All alphabetic characters in the two arguments string1 and string2 are converted to lowercase before the comparison. The function operates on null-ended strings. The string arguments to the function are expected to contain a null character (\0) marking the end of the string. The strcmpi function returns a value indicating the relationship between the two strings, as follows: Value Meaning Less than 0 string1 less than string2 0 string1 equivalent to string2 Greater than 0 string1 greater than string2. Example of strcmpi ═══ Example of strcmpi ═══ /************************************************************************ * This example uses strcmpi to compare two strings: * ************************************************************************/ #include #include int main(void) { /* Compare two strings without regard to case */ if (0 == strcmpi("hello","HELLO")) printf("The strings are equivalent.\n"); else printf("The strings are not equivalent.\n"); return 0; /*************** The output should be similar to: ********************* The strings are equivalent. */ } ═══ Related Information ═══ o strcoll - Compare Strings o strcspn - Compare Strings o strdup - Duplicate String o stricmp - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.215. strcoll - Compare Strings ═══ ═══ Format ═══ #include int strcoll(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strcoll function compares two strings using the collating sequence specified by the program's locale. The strcoll function returns a value indicating the relationship between the strings, as listed below. Value Meaning Less than 0 string1 less than string2 0 string1 equivalent to string2 Greater than 0 string1 greater than string2 Example of strcoll ═══ Example of strcoll ═══ /************************************************************************ * This example compares the two strings passed to main. * ************************************************************************/ #include #include int main(int argc, char ** argv) { int result; if ( argc != 3 ) { printf( "Usage: %s string1 string2\n", argv[0] ); } else { result = strcoll( argv[1], argv[2] ); if ( result == 0 ) printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] ); else if ( result < 0 ) printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] ); else printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] ); } } /****************** If the input is the strings *********************** **************** "firststring" and "secondstring", ******************** ****************** then the expected output is: ***************** "firststring" is less than "secondstring" */ ═══ Related Information ═══ o setlocale - Set Locale o strcmp - Compare Strings o strcmpi - Compare Strings o stricmp - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o strcspn - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.216. strcpy - Copy Strings ═══ ═══ Format ═══ #include char *strcpy(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strcpy function copies string2, including the ending null character, to the location specified by string1 The strcpy function operates on null-terminated strings. The string arguments to the function should contain a null character (\0) marking the end of the string. No length checking is performed. You should not use a literal string for a string1 value, although string2 may be a literal string. The strcpy function returns string1. Example of strcpy ═══ Example of strcpy ═══ /************************************************************************ * This example copies the contents of source to destination. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char source[ SIZE ] = "This is the source string"; char destination[ SIZE ] = "And this is the destination string"; char * return_string; printf( "destination is originally = \"%s\"\n", destination ); return_string = strcpy( destination, source ); printf( "After strcpy, destination becomes \"%s\"\n", destination ); } /***************** Output should be similar to: ***************** destination is originally = "And this is the destination string" After strcpy, destination becomes "This is the source string" */ ═══ Related Information ═══ o strcat - Concatenate Strings o strdup - Duplicate String o strncpy - Copy Strings o wcscpy - Copy wchar_t Strings o wcsncpy - Copy wchar_t Strings o string.h ═══ 6.217. strcspn - Compare Strings ═══ ═══ Format ═══ #include size_t strcspn(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strcspn function finds the first occurrence of a character in string1 that belongs to the set of characters specified by string2. Ending null characters are not considered in the search. The strcspn function operates on null-terminated strings. The string arguments to the function should contain a null character (\0) marking the end of the string. The strcspn function returns the index of the first character found. This value is equivalent to the length of the initial substring of string1 that consists entirely of characters not in string2. Example of strcspn ═══ Example of strcspn ═══ /************************************************************************ * This example uses strcspn to find the first occurrence of any of the characters a, x, l or e in string. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char string[ SIZE ] = "This is the source string"; char * substring = "axle"; printf( "The first %i characters in the string \"%s\" " "are not in the string \"%s\" \n", strcspn(string, substring), string, substring); } /********** Output should be similar to: ************** The first 10 characters in the string "This is the source string" are not in the string "axle" */ ═══ Related Information ═══ o strchr - Search for Character o strcmp - Compare Strings o strcmpi - Compare Strings o stricmp - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o strpbrk - Find Characters in String o strspn - Search Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.218. _strdate - Copy Current Date ═══ ═══ Format ═══ #include char *_strdate(char *date); ═══ Description ═══ Language Level: Extension The _strdate function stores the current date as a string in the buffer pointed to by date in the following format: mm/dd/yy The two digits mm represent the month, the digits dd represent the day of the month, and the digits yy represent the year. For example, the string 10/08/91 represents October 8, 1991. The buffer must be at least 9 bytes. Note: The time and date functions begin at 00:00 Coordinated Universal Time, January 1, 1970. The _strdate function returns a pointer to the buffer containing the date string. There is no error return. Example of _strdate ═══ Example of _strdate ═══ /************************************************************************ * This example prints the current date: * ************************************************************************/ #include #include int main(void) { char buffer [9]; printf("The current date is %s \n", _strdate(buffer)); return 0; /************** The output should be similar to: ********************** The current date is 03/21/93 */ } ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o time - Determine Current Time o _tzset - Assign Values to Locale Information o time.h ═══ 6.219. strdup - Duplicate String ═══ ═══ Format ═══ #include char *strdup(const char *string); ═══ Description ═══ Language Level: Extension &ipfisyn. root=copy.copy copying duplicate duplicating The strdup function reserves storage space for a copy of string by calling malloc. The string argument to this function is expected to contain a null character (\0) marking the end of the string. The strdup function returns a pointer to the storage space containing the copied string. If it cannot reserve storage strdup returns NULL. Example of strdup ═══ Example of strdup ═══ /************************************************************************ * This example uses strdup to duplicate a string and print the copy. * ************************************************************************/ #include #include int main(void) { char *string = "this is a copy"; char *newstr; /* Make newstr point to a duplicate of str3 */ if ( (newstr = strdup(string)) != NULL ) printf("The new string is: %s\n", newstr); return 0; /* The expected ouput: The new string is: this is a copy */ } ═══ Related Information ═══ o strcpy - Copy Strings o strncpy - Copy Strings o wcscpy - Copy wchar_t Strings o wcsncpy - Copy wchar_t Strings o string.h ═══ 6.220. strerror - Set Pointer to Runtime Error Message ═══ ═══ Format ═══ #include char *strerror(int errnum); ═══ Description ═══ Language Level: ANSI, SAA The strerror function maps the error number in errnum to an error message string. The strerror function returns a pointer to the string. It does not use the program locale in any way. Example of strerror ═══ Example of strerror ═══ /************************************************************************ * This example opens a file and prints a runtime error message if an error occurs. * ************************************************************************/ #include #include #include int main(void) { FILE *stream; . . . if ((stream = fopen("myfile.dat", "r")) == NULL) printf(" %s \n", strerror(errno)); } ═══ Related Information ═══ o clearerr - Reset Error Indicators o ferror - Test for Read/Write Errors o perror - Print Error Message o _strerror - Set Pointer to System Error String o string.h ═══ 6.221. _strerror - Set Pointer to System Error String ═══ ═══ Format ═══ #include char *_strerror(char *string); ═══ Description ═══ Language Level: Extension The _strerror function tests for system error. It gets the system error message for the last library call that produced an error and prefaces it with your string message. Your string message can be a maximum of 94 bytes. Unlike perror, _strerror by itself does not print a message. To print the message returned by _strerror to stdout, use a printf statement similar to the following: if ((access("datafile",2)) == -1) printf(stderr,_strerror(NULL)); You could also print the message to stderr with an fprintf statement. To produce accurate results, call _strerror immediately after a library function returns with an error. Otherwise, subsequent calls might write over the errno value. If string is equal to NULL, _strerror returns a pointer to a string containing the system error message for the last library call that produced an error, ended by a new-line character (\n). If string is not equal to NULL, _strerror returns a pointer to a string containing: o Your string message o A colon o A space o The system error message for the last library call producing an error o A new-line character (\n). Example of _strerror ═══ Example of _strerror ═══ /************************************************************************ * This example shows how _strerror can be used with the fopen function. * ************************************************************************/ #include #include int main(void) { FILE *fh1, *fh2; fh1 = fopen("data1","r"); if (fh1 == NULL) /* the error message goes through stdout not stderr */ printf(_strerror("Open failed on input file")); fh2 = fopen("data2","w+"); if (fh2 == NULL) printf(_strerror("Open failed on output file")); else printf("Open on output file was successful.\n"); if (fh1 != NULL) fclose(fh1); if (fh2 != NULL) fclose(fh2); return 0; /*************** The output should be similar to: ********************* Open failed on input file: The file cannot be found. Open on output file was successful. */ } ═══ Related Information ═══ o clearerr - Reset Error Indicators o ferror - Test for Read/Write Errors o perror - Print Error Message o strerror - Set Pointer to Runtime Error Message o string.h ═══ 6.222. strftime - Convert to Formatted Time ═══ ═══ Format ═══ #include size_t strftime(char *dest, size_t maxsize, const char *format, const struct tm *timeptr); ═══ Description ═══ Language Level: ANSI, SAA The strftime function places characters into the array pointed to by dest according to the string pointed to by format. The format string is a multibyte character string. This function uses the current locale. The format string contains: o Conversion specification characters o Multibyte characters that are placed unchanged into the array. The characters that are converted are determined by the locale and by the values in the time structure pointed to by timeptr. The conversion specifiers and their meanings are listed below: ┌──────────┬───────────────────────────────────────────────────────────────────┐ │ SPECIFIER│ MEANING │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%a" │ Insert abbreviated weekday name of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%A" │ Insert full weekday name of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%b" │ Insert abbreviated month name of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%B" │ Insert full month name of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%c" │ Insert date and time of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%d" │ Insert day of the month (01-31). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%H" │ Insert hour (24-hour clock) as a decimal number (00-23). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%I" │ Insert hour (12-hour clock) as a decimal number (01-12). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%j" │ Insert day of the year (001-366). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%m" │ Insert month (01-12). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%M" │ Insert minute (00-59). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%p" │ Insert equivalent of either AM or PM of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%S" │ Insert second (00-61). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%U" │ Insert week number of the year (00-53) where Sunday is the first │ │ │ day of the week. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%w" │ Insert weekday (0-6) where Sunday is 0. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%W" │ Insert week number of the year (00-53) where Monday is the first │ │ │ day of the week. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%x" │ Insert date representation of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%X" │ Insert time representation of locale. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%y" │ Insert year without the century (00-99). │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%Y" │ Insert year. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%Z" │ Insert name of time zone, or no characters if time zone is not │ │ │ available. │ ├──────────┼───────────────────────────────────────────────────────────────────┤ │ "%%" │ Insert %. │ └──────────┴───────────────────────────────────────────────────────────────────┘ The behavior is undefined when objects being copied overlap. maxsize specifies the maximum number of characters that can be copied into the array. The strftime function returns the number of characters (bytes) placed into the array, not including the terminating null character. On error, 0 is returned. Note: The time and date functions begin at 00:00 Universal Time, January 1, 1970. Example of strftime ═══ Example of strftime ═══ /************************************************************************ * This example places characters into the array dest and prints the resulting string. * ************************************************************************/ #include #include int main(void) { char dest[70]; int ch; time_t temp; struct tm *timeptr; temp = time(NULL); timeptr = localtime(&temp); ch = strftime(dest,sizeof(dest)-1,"Today is %A," " %b %d. \n Time: %I:%M %p", timeptr); printf("%d characters placed in string to make: \n \n %s", ch, dest); } /***************** Output should be similar to: ***************** 44 characters placed in string to make: Today is Wednesday, Oct 23. Time: 03:07 PM */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o setlocale - Set Locale o time - Determine Current Time o time.h ═══ 6.223. stricmp - Compare Strings ═══ ═══ Format ═══ #include int stricmp(const char *string1, const char *string2); ═══ Description ═══ Language Level: Extension The stricmp function compares string1 and string2 without sensitivity for case. All alphabetic characters in the arguments string1 and string2 are converted to lowercase before the comparison. The stricmp function operates on null-terminated strings. The function returns a value that indicates the following relationship between the two strings : Value Meaning Less than 0 string1 less than string2 0 string1 identical to string2 Greater than 0 string1 greater than string2. Example of stricmp ═══ Example of stricmp ═══ /************************************************************************ * This example uses stricmp to compare two strings. * ************************************************************************/ #include #include int main(void) { char *str1 = "this is a string"; char *str2 = "THIS IS A STRING"; /* Compare two strings without regard to case */ if ( stricmp( str1,str2 ) ) printf("str1 is not the same as str2\n"); else printf("str1 is the same as str2\n"); return 0; /* The expected output is: str 1 is the same as str 2 */ } ═══ Related Information ═══ o strcmp - Compare Strings o strcmpi - Compare Strings o strcspn - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h o strnicmp - Compare Strings ═══ 6.224. strlen - Determine String Length ═══ ═══ Format ═══ #include size_t strlen(const char *string); ═══ Description ═══ Language Level: ANSI, SAA The strlen function determines the length of string excluding the terminating null character. The strlen function returns the length of string. Example of strlen ═══ Example of strlen ═══ /************************************************************************ * This example determines the length of the string that is passed to main. * ************************************************************************/ #include #include int main(int argc, char ** argv) { if ( argc != 2 ) printf( "Usage: %s string\n", argv[0] ); else printf( "Input string has a length of %i\n", strlen( argv[1] )); } /****************** If the input is the string *********************** *****************"How long is this string?", ****************** ****************** then the expected output is: ***************** Input string has a length of 24 */ ═══ Related Information ═══ o mblen - Multibyte String Length o strrev - Reverse String o wcslen - Calculate Length of wchar_t String o string.h ═══ 6.225. strlwr - Convert Uppercase to Lowercase ═══ ═══ Format ═══ #include char *strlwr(char *string); ═══ Description ═══ Language Level: Extension The strlwr function converts any uppercase letters in the given null-terminated string to lowercase. Other characters are not affected. The strlwr function returns a pointer to the converted string. There is no error return. Example of strlwr ═══ Example of strlwr ═══ /************************************************************************ * This example makes a copy in all lowercase of the string "General Assembly", and then prints the copy. * ************************************************************************/ #include #include int main(void) { char *string="General Assembly"; char *copy; copy = strlwr(strdup(string)); printf("Expected result: general assembly\n"); printf("strlwr returned: %s\n", copy); return 0; /* The expected output is: Expected result: general assembly strlwr returned: general assembly */ } ═══ Related Information ═══ o strupr - Convert Lowercase to Uppercase o _toascii - _tolower - _toupper - Convert Character o tolower - toupper - Convert Character Case o string.h ═══ 6.226. strncat - Concatenate Strings ═══ ═══ Format ═══ #include char *strncat(char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA The strncat function appends the first count characters of string2 to string1 and ends the resulting string with a null character (\0). If count is greater than the length of string2, the length of string2 is used in place of count. The strncat function operates on null-terminated strings. The string argument to the function should contain a null character (\0) marking the end of the string. The strncat function returns a pointer to the joined string (string1). Example of strncat ═══ Example of strncat ═══ /************************************************************************ * This example demonstrates the difference between strcat and strncat. strcat appends the entire second string to the first, whereas strncat appends only the specified number of characters in the second string to the first. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char buffer1[SIZE] = "computer"; char * ptr; /* Call strcat with buffer1 and " program" */ ptr = strcat( buffer1, " program" ); printf( "strcat : buffer1 = \"%s\"\n", buffer1 ); /* Reset buffer1 to contain just the string "computer" again */ memset( buffer1, '\0', sizeof( buffer1 )); ptr = strcpy( buffer1, "computer" ); /* Call strncat with buffer1 and " program" */ ptr = strncat( buffer1, " program", 3 ); printf( "strncat: buffer1 = \"%s\"\n", buffer1 ); } /***************** Output should be similar to: ***************** strcat : buffer1 = "computer program" strncat: buffer1 = "computer pr" */ ═══ Related Information ═══ o strcat - Concatenate Strings o strnicmp - Compare Strings o wcscat - Append wchar_t Strings o wcsncat - Concatenate wchar_t Strings o string.h ═══ 6.227. strncmp - Compare Strings ═══ ═══ Format ═══ #include int strncmp(const char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA The strncmp function compares the first count characters of string1 and string2. The strncmp function returns a value indicating the relationship between the substrings, as follows: Value Meaning Less than 0 substring1 less than substring2 0 substring1 equivalent to substring2 Greater than 0 substring1 greater than substring2 Example of strncmp ═══ Example of strncmp ═══ /************************************************************************ * This example demonstrates the difference between strcmp and strncmp. * ************************************************************************/ #include #include #define SIZE 10 int main(void) { int result; int index = 3; char buffer1[SIZE] = "abcdefg"; char buffer2[SIZE] = "abcfg"; void print_result( int, char *, char * ); result = strcmp( buffer1, buffer2 ); printf( "Comparison of each character\n" ); printf( " strcmp: " ); print_result( result, buffer1, buffer2 ); result = strncmp( buffer1, buffer2, index); printf( "\nComparison of only the first %i characters\n", index ); printf( " strncmp: " ); print_result( result, buffer1, buffer2 ); } void print_result( int res, char * p_buffer1, char * p_buffer2 ) { if ( res == 0 ) printf( "\"%s\" is identical to \"%s\"\n", p_buffer1, p_buffer2); else if ( res < 0 ) printf( "\"%s\" is less than \"%s\"\n", p_buffer1, p_buffer2 ); else printf( "\"%s\" is greater than \"%s\"\n", p_buffer1, p_buffer2 ); } /***************** Output should be similar to: ***************** Comparison of each character strcmp: "abcdefg" is less than "abcfg" Comparison of only the first 3 characters strncmp: "abcdefg" is identical to "abcfg" */ ═══ Related Information ═══ o strcmp - Compare Strings o strcmpi - Compare Strings o strcoll - Compare Strings o strcspn - Compare Strings o stricmp - Compare Strings o strnicmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.228. strncpy - Copy Strings ═══ ═══ Format ═══ #include char *strncpy(char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA The strncpy function copies count characters of string2 to string1. If count is less than or equal to the length of string2, a null character (\0) is not appended to the copied string. If count is greater than the length of string2, the string1 result is padded with null characters (\0) up to length count. The strncpy function returns string1. Example of strncpy ═══ Example of strncpy ═══ /************************************************************************ * This example demonstrates the difference between strcpy and strncpy. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char source[ SIZE ] = "123456789"; char source1[ SIZE ] = "123456789"; char destination[ SIZE ] = "abcdefg"; char destination1[ SIZE ] = "abcdefg"; char * return_string; int index = 5; /* This is how strcpy works */ printf( "destination is originally = '%s'\n", destination ); return_string = strcpy( destination, source ); printf( "After strcpy, destination becomes '%s'\n\n", destination ); /* This is how strncpy works */ printf( "destination1 is originally = '%s'\n", destination1 ); return_string = strncpy( destination1, source1, index ); printf( "After strncpy, destination1 becomes '%s'\n", destination1 ); } /***************** Output should be similar to: ***************** destination is originally = 'abcdefg' After strcpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After strncpy, destination1 becomes '12345fg' */ ═══ Related Information ═══ o strcpy - Copy Strings o strdup - Duplicate String o strnicmp - Compare Strings o string.h ═══ 6.229. strnicmp - Compare Strings ═══ ═══ Format ═══ #include int strnicmp(const char *string1, const char *string2, int n); ═══ Description ═══ Language Level: Extension The strnicmp function operates on, at most, the first n characters of null-terminated strings. This function compares, at most, the first n characters of string1 and string2. The strnicmp function is case insensitive; the uppercase and lowercase forms of a letter are considered equivalent. The strnicmp returns a value indicating the relationship between the substrings, as listed below. Value Meaning Less than 0 substring1 less than substring2 0 substring1 equivalent to substring2 Greater than 0 substring1 greater than substring2. Example of strnicmp ═══ Example of strnicmp ═══ /************************************************************************ * This example uses strnicmp to compare two strings. * ************************************************************************/ #include #include int main(void) { char *str1 = "THIS IS THE FIRST STRING"; char *str2 = "This is the second string"; int numresult; /* Compare the first 11 characters of str1 and str2 without regard to case */ numresult = strnicmp(str1, str2, 11); if (numresult < 0) printf("String 1 is less than string2.\n"); else if (numresult > 0) printf("String 1 is greater than string2.\n"); else printf("The two strings are equivalent.\n"); return 0; /* The expected output is: The two strings are equivalent. */ } ═══ Related Information ═══ o strcmp - Compare Strings o strcmpi - Compare Strings o stricmp - Compare Strings o strncmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcsncmp - Compare wchar_t Strings o string.h ═══ 6.230. strnset - strset - Set Characters in String ═══ ═══ Format ═══ #include char *strnset(char *string, int c, size_t n); char *strset(char *string, int c); ═══ Description ═══ Language Level: Extension The strnset function sets at most the first n characters of string to c (converted to a char). If n is greater than the length of string, the length of string is used in place of n. The strset function sets all characters of string except the ending null character (\0) to c (converted to a char). For both functions, the string must be initialized and must end with a null character (\0). Both strset and strnset return a pointer to the altered string. There is no error return value. Example of strnset and strset ═══ Example of strnset and strset ═══ /************************************************************************ * In this example, the strnset function sets not more than 4 characters of a string to the character 'x' Then the strset function changes any non-null characters of a string to the character 'k'. * ************************************************************************/ #include #include int main(void) { char *str = "abcdefghi"; printf("This is the string: %s\n",str); printf("This is the string after strnset: %s\n", strnset(str, 'x', 4)); printf("This is the string after strset: %s\n", strset(str, 'k')); return 0; /**************** The output should be similar to: ******************** This is the string: abcdefghi This is the string after strnset: xxxxefghi This is the string after strset: kkkkkkkkk */ } ═══ Related Information ═══ o strchr - Search for Character o strpbrk - Find Characters in String o wcschr - Search wchar_t String for Given wchar_t o wcspbrk - Locate wchar_t Characters in String o string.h ═══ 6.231. strpbrk - Find Characters in String ═══ ═══ Format ═══ #include char *strpbrk(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strpbrk function locates the first occurrence in the string pointed to by string1 of any character from the string pointed to by string2. The strpbrk function returns a pointer to the character. If string1 and string2 have no characters in common, a NULL pointer is returned. Example of strpbrk ═══ Example of strpbrk ═══ /************************************************************************ * This example returns a pointer to the first occurrence in the array string of either a or b. * ************************************************************************/ #include #include int main(void) { char *result, *string = "A Blue Danube"; char *chars = "ab"; result = strpbrk(string, chars); printf("The first occurrence of any of the characters \"%s\" in " "\"%s\" is \"%s\"\n", chars, string, result); } /***************** Output should be similar to: ***************** The first occurrence of any of the characters "ab" in "The Blue Danube" is "anube" */ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcswcs - Locate wchar_t Substring in wchar_t String o string.h ═══ 6.232. strrchr - Find Last Occurrence of Character in String ═══ ═══ Format ═══ #include char *strrchr(const char *string, int c); ═══ Description ═══ Language Level: ANSI, SAA The strrchr function finds the last occurrence of c (converted to a character) in string. The ending null character is considered part of the string. The strrchr function returns a pointer to the last occurrence of c in string. If the given character is not found, a NULL pointer is returned. Example of strrchr ═══ Example of strrchr ═══ /************************************************************************ * This example compares the use of strchr and strrchr. It searches the string for the first and last occurrence of p in the string. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { char buf[SIZE] = "computer program"; char * ptr; int ch = 'p'; /* This illustrates strchr */ ptr = strchr( buf, ch ); printf( "The first occurrence of %c in '%s' is '%s'\n", ch, buf, ptr ); /* This illustrates strrchr */ ptr = strrchr( buf, ch ); printf( "The last occurrence of %c in '%s' is '%s'\n", ch, buf, ptr ); } /***************** Output should be similar to: ***************** The first occurrence of p in 'computer program' is 'puter program' The last occurrence of p in 'computer program' is 'program' */ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcswcs - Locate wchar_t Substring in wchar_t String o string.h ═══ 6.233. strrev - Reverse String ═══ ═══ Format ═══ #include char *strrev(char *string); ═══ Description ═══ Language Level: Extension The strrev function reverses the order of the characters in the given string. The ending null character (\0) remains in place. The strrev function returns a pointer to the altered string. There is no error return value. Example of strrev ═══ Example of strrev ═══ /************************************************************************ * This example determines if a string is a palindrome. A palindrome is a string that reads the same forward and backward. * ************************************************************************/ #include #include int palindrome(char *string); { char *string2; /* Duplicate string for comparison */ if (( string2 = strdup(string) ) == NULL) { printf ("Storage could not be reserved for string\n"); _exit(-1); } /* If result equals 0, the string is a palindrome */ return (strcmp(string, strrev(string2))); } int main(void) { char string[81]; printf("Please enter a string.\n"); scanf("%80s", string); if (palindrome(string)) printf("The string is not a palindrome.\n"); else printf("The string is a palindrome.\n"); return 0; /************** The output should be similar to: ********************** Please enter a string. level The string is a palindrome. ** ... or ... ** Please enter a string. bolton The string is not a palindrome. */ } ═══ Related Information ═══ o strcat - Concatenate Strings o strcmp - Compare Strings o strcpy - Copy Strings o strdup - Duplicate String o strnset - strset - Set Characters in String o string.h ═══ 6.234. strspn - Search Strings ═══ ═══ Format ═══ #include size_t strspn(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strspn function finds the first occurrence of a character in string1 that is not contained in the set of characters specified by string2. The null character (\0) that ends string2 is not considered in the matching process. The strspn function returns the index of the first character found. This value is equal to the length of the initial substring of string1 that consists entirely of characters from string2. If string1 begins with a character not in string2, strspn returns 0. If all the characters in string1 are found in string2, the length of string1 is returned. Example of strspn ═══ Example of strspn ═══ /************************************************************************ * This example finds the first occurrence in the array string of a character that is neither an a, b, nor c. Because the string in this example is cabbage, strspn returns 5, the length of the segment of cabbage before a character that is not an a, b or c. * ************************************************************************/ #include #include int main(void) { char * string = "cabbage"; char * source = "abc"; int index; index = strspn( string, "abc" ); printf( "The first %d characters of \"%s\" are found in \"%s\"\n", index, string, source ); } /***************** Output should be similar to: ***************** The first 5 characters of "cabbage" are found in "abc" */ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o string.h ═══ 6.235. strstr - Locate Substring ═══ ═══ Format ═══ #include char *strstr(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strstr function finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process. The strstr function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, strstr returns NULL. If string2 points to a string with zero length, the function returns string1. Example of strstr ═══ Example of strstr ═══ /************************************************************************ * This example locates the string haystack in the string "needle in a haystack". * ************************************************************************/ #include #include int main(void) { char *string1 = "needle in a haystack"; char *string2 = "haystack"; char *result; result = strstr(string1,string2); /* Result = a pointer to "haystack" */ printf("%s\n", result); } /***************** Output should be similar to: ***************** haystack */ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o string.h ═══ 6.236. _strtime - Copy Time ═══ ═══ Format ═══ #include char *_strtime(char *time); ═══ Description ═══ Language Level: Extension The _strtime function copies the current time into the buffer to which time points. The format is: hh:mm:ss where hh represents the hour in 24-hour notation, mm represents the minutes past the hour, ss represents the number of seconds. For example, the string 18:23:44 represents 23 minutes and 44 seconds past 6 p.m. The buffer must be at least 9 bytes. Note: The time and date functions begin at 00:00 Coordinated Universal Time, January 1, 1970. The value returned is a pointer to the buffer. There is no error return. Example of _strtime ═══ Example of _strtime ═══ /************************************************************************ * This example prints the current time: * ************************************************************************/ #include #include int main(void) { char buffer[9]; printf("The current time is %s \n", _strtime(buffer)); return 0; /********* The output should be similar to: ******* The current time is 16:09:22 */ } ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o time - Determine Current Time o _tzset - Assign Values to Locale Information o time.h ═══ 6.237. strtod - Convert Character String to Numeric ═══ ═══ Format ═══ #include double strtod(const char *nptr, char **endptr); ═══ Description ═══ Language Level: ANSI, SAA The strtod function converts a character string to a double-precision value. The parameter nptr points to a sequence of characters that can be interpreted as a numerical value of the type double. This function stops reading the string at the first character that it cannot recognize as part of a number. This character can be the null character at the end of the string. The strtod function expects nptr to point to a string with the following form: ─┬──────────────┬──┬───────┬──┬─────────────────────────────────┬─ │ │ │ │ │ │ └──whitespace──┘ ├── + ──┤ ├─digits───┬──────┬───┬────────┬──┤ │ │ │ │ │ │ │ │ └── - ──┘ │ └── . ─┘ └─digits─┘ │ │ │ └──────── . ──digits──────────────┘ ─┬───────────────────────────┬── │ │ ├──e──┬───┬─────┬───digits──┘ │ │ │ │ └──E──┘ ├─ + ─┤ │ │ └─ - ─┘ The first character that does not fit this form stops the scan. The strtod function returns the value of the floating-point number, except when the representation causes an underflow or overflow. In the case of an overflow, it returns -HUGE_VAL or +HUGE_VAL; in the case of an underflow, it returns 0. In both cases, errno is set to ERANGE, depending on the base of the value. If the string pointed to by nptr does not have the expected form, no conversion is performed and the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a NULL pointer. Example of strtod ═══ Example of strtod ═══ /************************************************************************ * This example converts the strings to a double value. It prints out the converted value and the substring that stopped the conversion. * ************************************************************************/ #include #include int main(void) { char *string, *stopstring; double x; string = "3.1415926This stopped it"; x = strtod(string, &stopstring); printf("string = %s\n", string); printf(" strtod = %lf\n", x); printf(" Stopped scan at %s\n\n", stopstring); string = "100ergs"; x = strtod(string, &stopstring); printf("string = \"%s\"\n", string); printf(" strtod = %lf\n", x); printf(" Stopped scan at \"%s\"\n\n", stopstring); } /***************** Output should be similar to: ***************** string = 3.1415926This stopped it strtod = 3.141593 Stopped scan at This stopped it string = 100ergs strtod = 100.000000 Stopped scan at ergs */ ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o strtoul - Convert String Segment to Unsigned Integer o stdlib.h ═══ 6.238. strtok - Tokenize String ═══ ═══ Format ═══ #include char *strtok(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA The strtok function reads string1 as a series of zero or more tokens and string2 as the set of characters serving as delimiters of the tokens in string1. The tokens in string1 can be separated by one or more of the delimiters from string2. The tokens in string1 can be located by a series of calls to strtok. In the first call to strtok for a given string1, strtok searches for the first token in string1, skipping over leading delimiters. A pointer to the first token is returned. To read the next token from string1, call strtok with a NULL string1 argument. A NULL string1 argument causes strtok to search for the next token in the previous token string. Each delimiter is replaced by a null character. The set of delimiters can vary from call to call, so string2 can take any value. The first time strtok is called, it returns a pointer to the first token in string1. In later calls with the same token string, strtok returns a pointer to the next token in the string. A NULL pointer is returned when there are no more tokens. All tokens are null-terminated. Example of strtok ═══ Example of strtok ═══ /************************************************************************ * Using a loop, this example gathers tokens, separated by blanks or commas, from a string until no tokens are left. After processing the tokens (not shown), the example returns the pointers to the tokens a, string, of, and tokens. The next call to strtok returns NULL and the loop ends. * ************************************************************************/ #include #include int main(void) { char *token, *string = "a string, of, ,tokens\0,after null terminator"; /* the string pointed to by string is broken up into the tokens "a string", " of", " ", and "tokens" ; the null terminator (\0) is encountered and execution stops after the token "tokens" */ token = strtok(string, ","); do { printf("token: %s\n", token); } while (token = strtok(NULL, ",")); } /***************** Output should be similar to: ***************** token: a string token: of token: token: tokens */ ═══ Related Information ═══ o strcat - Concatenate Strings o strchr - Search for Character o strcmp - Compare Strings o strcpy - Copy Strings o strcspn - Compare Strings o strspn - Search Strings o string.h ═══ 6.239. strtol - Convert Character String to Numeric ═══ ═══ Format ═══ #include long int strtol(const char *nptr, char **endptr, int base); ═══ Description ═══ Language Level: ANSI, SAA The strtol function converts a character string to a long-integer value. The parameter nptr points to a sequence of characters that can be interpreted as a numerical value of type long int. This function stops reading the string at the first character that it cannot recognize as part of a number. This character can be the null character (\0) at the end of the string. The ending character can also be the first numeric character greater than or equal to the base. When you use the strtol function, nptr should point to a string with the following form: ──┬──────────────┬──┬───────┬──┬──────┬──┬──────────┬── │ │ │ │ │ │ │ │ └──whitespace──┘ ├── + ──┤ ├──0───┤ └──digits──┘ │ │ │ │ └── - ──┘ ├──0x──┤ │ │ └──0X──┘ If base is in the range of 2 through 36, it becomes the base of the number. If base is 0, the prefix determines the base (8, 16, or 10): the prefix 0 means base 8; the prefix 0x or 0X means base 16; using any other digit without a prefix means decimal. The strtol function returns the value represented in the string, except when the representation causes an overflow. In the case of an overflow, it returns LONG_MAX or LONG_MIN, according to the sign of the value and errno is set to ERANGE. If base is not a valid number, strtol sets errno to EDOM. errno is set to ERANGE for the exceptional cases, depending on the base of the value. If the string pointed to by nptr does not have the expected form, no conversion is performed and the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a NULL pointer. Example of strtol ═══ Example of strtol ═══ /************************************************************************ * This example converts the strings to a long value. It prints out the converted value and the substring that stopped the conversion. * ************************************************************************/ #include #include int main(void) { char *string, *stopstring; long l; int bs; string = "10110134932"; printf("string = %s\n", string); for (bs = 2; bs <= 8; bs *= 2) { l = strtol(string, &stopstring, bs); printf(" strtol = %ld (base %d)\n", l, bs); printf(" Stopped scan at %s\n\n", stopstring); } } /***************** Output should be similar to: ***************** string = 10110134932 strtol = 45 (base 2) Stopped scan at 34932 strtol = 4423 (base 4) Stopped scan at 4932 strtol = 2134108 (base 8) Stopped scan at 932 */ ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o _ltoa - Convert Long Integer to String o strtod - Convert Character String to Numeric o strtold - Convert String to Long Double o strtoul - Convert String Segment to Unsigned Integer o stdlib.h ═══ 6.240. strtold - Convert String to Long Double ═══ ═══ Format ═══ #include long double strtold(const char *nptr, char **endptr); ═══ Description ═══ Language Level: Extension The strtold function converts a character string pointed to by nptr to a long double value. When it reads a character it does not recognize as part of a number, strtold stops conversion and endptr points to the remainder of nptr. This character may be the ending null character. The string pointed to by nptr must have the following format: ─┬──────────────┬──┬───────────────────────────────────────────┬─ └──whitespace──┘ └─┬───────┬──┬─────────────────────────────┬┘ ├───+───┤ ├──digits──┬─────┬─┬────────┬─┤ └───-───┘ │ └──.──┘ └─digits─┘ │ └─────.───────digits──────────┘ ─┬──────────────────────────┬─ ├──e──┬──┬─────┬───digits──┘ └──E──┘ ├──+──┤ └──-──┘ The digits are one or more decimal digits. If no digits appear before the decimal point, at least one digit must follow the decimal point. An exponent expressed as a decimal integer may follow the digits. The exponent may be signed. The value of nptr can also be one of the strings infinity, inf, or nan. These strings are case insensitive, and can be preceded by a unary minus (-). They are converted to infinity and NaN values. See Infinity and NaN Support for more information about using infinity and NaN values. If the string pointed to by nptr does not have the expected form, no conversion is performed and endptr points to the value of nptr. The strtold function ignores any white-space characters, as defined by the isspace function. If successful, strtold returns the value of the long double number. If it fails, strtold returns 0. In the case of an underflow or overflow, it returns the following: Condition Return Value Underflow 0 with errno set to ERANGE Positive overflow +_LHUGE_VAL Negative overflow -_LHUGE_VAL. Example of strtold ═══ Example of strtold ═══ /************************************************************************ * This example uses strtold to convert two strings, " -001234.5678e10end of string" and "NaNQthis cannot be converted" to their corresponding long double values. It also prints out the part of the string that cannot be converted. * ************************************************************************/ #include #include int main(void) { char *nptr; char *endptr; nptr = " -001234.5678e10end of string"; printf("strtold = %.10Le\n", strtold(nptr, &endptr) ); printf("end pointer at = %s\n\n", endptr); nptr = "NaNthis cannot be converted"; printf("strtold = %.10Le\n", strtold(nptr, &endptr) ); printf("end pointer at = %s\n\n", endptr); return 0; /* The expected output is: strtold = -1.2345678000e+13 end pointer at = end of string strtold = nan end pointer at = this cannot be converted */ } ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtoul - Convert String Segment to Unsigned Integer o Infinity and NaN Support o stdlib.h ═══ 6.241. strtoul - Convert String Segment to Unsigned Integer ═══ ═══ Format ═══ #include unsigned long int strtoul(const char *string1, char **string2, int base); ═══ Description ═══ Language Level: ANSI, SAA The strtoul function converts a character string to an unsigned long-integer value. The input string1 is a sequence of characters that can be interpreted as a numerical value of the type unsigned long int. The function stops reading the string at the first character that it cannot recognize as part of a number. This character can be the first numeric character greater than or equal to the base. The strtoul function sets string2 to point to the resulting output string if a conversion is performed and provided that string2 is not a NULL pointer. When you are using the strtoul function, string1 should point to a string with the following form: ──┬──────────────┬──┬───────┬──┬──────┬──┬──────────┬── │ │ │ │ │ │ │ │ └──whitespace──┘ ├── + ──┤ ├──0───┤ └──digits──┘ │ │ │ │ └── - ──┘ ├──0x──┤ │ │ └──0X──┘ If base is in the range of 2 through 36, it becomes the base of the number. If base is 0, the prefix determines the base (8, 16, or 10): the prefix 0 means base 8; the prefix 0x or 0X means base 16; using any other digit without a prefix means decimal. The strtoul function returns the value represented in the string or returns 0 if no conversion could be performed. For an overflow, strtoul returns ULONG_MAX and sets errno to ERANGE. If base is not a valid number, strtoul sets errno to EDOM. Example of strtoul ═══ Example of strtoul ═══ /************************************************************************ * This example converts the string to an unsigned long value. It prints out the converted value and the substring that stopped the conversion. * ************************************************************************/ #include #include #define BASE 2 int main(void) { char *string, *stopstring; unsigned long ul; string = "1000e13 e"; printf("string = %s\n", string); ul = strtoul(string, &stopstring, BASE); printf(" strtoul = %ld (base %d)\n", ul, BASE); printf(" Stopped scan at %s\n\n", stopstring); } /***************** Output should be similar to: ***************** string = 1000e13 e strtoul = 8 (base 2) Stopped scan at e13 e */ ═══ Related Information ═══ o atof - Convert Character Strings o atoi - Convert Character Strings o atol - Convert Character Strings o _atold - Convert ASCII String to Long Double o strtod - Convert Character String to Numeric o strtol - Convert Character String to Numeric o strtold - Convert String to Long Double o _ultoa - Convert Unsigned Long Integer to String o stdlib.h ═══ 6.242. strupr - Convert Lowercase to Uppercase ═══ ═══ Format ═══ #include char *strupr(char *string); ═══ Description ═══ Language Level: Extension The strupr function converts any lowercase letters in string to uppercase. Other characters are not affected. The strupr function returns a pointer to the converted string. There is no error return. Example of strupr ═══ Example of strupr ═══ /************************************************************************ * This example makes a copy in all-uppercase of the string "DosWrite", and then prints the copy. * ************************************************************************/ #include #include int main(void) { char *string = "DosWrite"; char *copy; copy=strupr(strdup(string)); printf("This is a copy of the string\n"); printf("with all letters capitalized: %s\n",copy); return 0; /* The expected output is: This is a copy of the string with all letters capitalized: DOSWRITE */ } ═══ Related Information ═══ o strlwr - Convert Uppercase to Lowercase o _toascii - _tolower - _toupper - Convert Character o tolower - toupper - Convert Character Case o string.h ═══ 6.243. strxfrm - Transform Strings ═══ ═══ Format ═══ #include size_t strxfrm(char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA The strxfrm function transforms the string pointed to by string2 and places the result into the string pointed to by string1. The transformation is determined by the program's current locale. The transformed string is not necessarily readable, but can be used with the strcmp or strncmp functions. The strxfrm function returns the length of the transformed string, excluding the terminating null character. If the value returned is greater than or equal to count, the contents of the transformed string are indeterminate. Example of strxfrm ═══ Example of strxfrm ═══ /************************************************************************ * This example prompts the user to input a string of characters, then uses strxfrm to transform the string and return its length. * ************************************************************************/ #include #include int main(void) { char *string1, buffer[80]; int length; printf("Type in a string of characters.\n "); string1 = gets(buffer); length = strxfrm(NULL, string1, 0); printf("You would need a %d element array to hold the string\n",length); printf("\n\n%s\n\n transformed according",string1); printf(" to this program's locale. \n"); } ═══ Related Information ═══ o localeconv - Query Locale Conventions o setlocale - Set Locale o strcmp - Compare Strings o strcmpi - Compare Strings o strcoll - Compare Strings o stricmp - Compare Strings o strncmp - Compare Strings o strnicmp - Compare Strings o string.h ═══ 6.244. _swab - Swap Adjacent Bytes ═══ ═══ Format ═══ #include void _swab(char *source, char *destination, int n); ═══ Description ═══ Language Level: Extension The _swab function copies n bytes from source, swaps each pair of adjacent bytes, and stores the result at destination. The integer n should be an even number to allow for swapping. If n is an odd number, a null character (\0) is added after the last byte. The _swab function is typically used to prepare binary data for transfer to a machine that uses a different byte order. There is no return value. Example of _swab ═══ Example of _swab ═══ /************************************************************************ * This example copies n bytes from one location to another, swapping each pair of adjacent bytes: * ************************************************************************/ #include #include /* This array is not a string because it does not end with a null character */ char from[20] = "hTsii s atsirgn..x "; char to[20]; int main(void) { _swab(from, to, 19); printf("%s\n", to); /* Because swab appends a null character, */ /* the array is now a string */ return 0; /*************** The output should be similar to: ********************* This is a string.. */ } ═══ Related Information ═══ o fgetc - Read a Character o fputc - Write a Character o stdlib.h ═══ 6.245. system - Invoke the Command Processor ═══ ═══ Format ═══ #include int system(char *string); ═══ Description ═══ Language Level: ANSI, SAA, Extension The system function passes the command string to a command processor to be run. The command processor specified in the COMSPEC environment variable is searched for first. If it does not exist or is not a valid executable file, the default command processor, CMD.EXE, is searched for in the current directory and in all the directories specified in the PATH environment variable. If the specified command is the name of an executable file created from a C program, full initialization and termination is performed, including automatic flushing of buffers and closing of files. To pass information across a system function, use a method of interprocess communication like pipes or shared memory. You can also use system to redirect standard streams using the redirection operators (the angle brackets), for example: rc = system("cprogram < in.file"); The defaults for the standard streams will be whatever the standard streams are at the point of the system call; for example, if the root program redirects stdout to file.txt, a printf call in a C module invoked by a system call will append to file.txt. If the argument is a null pointer, the system function returns nonzero if a command processor exists and 0 if it does not exist. The return value will be the return value from the command processor if it is successfully called. If system cannot call the command processor successfully, the return value is -1 and errno is set to one of the following values: Value Meaning ENOCMD No valid command processor found. ENOMEM Insufficient memory to complete the function. EOS2ERR A system error occurred. Check _doserrno for the specific OS/2 error code. Example of system ═══ Example of system ═══ /************************************************************************ * This example shows how to use system to execute the OS/2 command dir c:\ : * ************************************************************************/ #include int main(void) { int rc; rc = system("dir c:\\"); exit(rc); /* The expected output is a listing of files on the root directory of the c: drive */ } ═══ Related Information ═══ o exit - End Program o _exit - End Process o process.h o stdlib.h ═══ 6.246. tan - Calculate Tangent ═══ ═══ Format ═══ #include double tan(double x); ═══ Description ═══ Language Level: ANSI, SAA The tan function calculates the tangent of x, where x is expressed in radians. If x is too large, a partial loss of significance in the result can occur. Example of tan ═══ Example of tan ═══ /************************************************************************ * This example computes x as the tangent of у/4. * ************************************************************************/ #include #include int main(void) { double pi, x; pi = 3.1415926; x = tan(pi/4.0); printf("tan( %lf ) is %lf\n", pi/4, x); } /****************** Output should be similar to: **************** tan( 0.785398 ) is 1.000000 */ ═══ Related Information ═══ o atan - atan2 - Calculate Arctangent o cos - Calculate Cosine o _fpatan - Calculate Arctangent o _fptan - Calculate Tangent o sin - Calculate Sine o tanh - Calculate Hyperbolic Tangent o math.h ═══ 6.247. tanh - Calculate Hyperbolic Tangent ═══ ═══ Format ═══ #include double tanh(double x); ═══ Description ═══ Language Level: ANSI, SAA The tanh function calculates the hyperbolic tangent of x, where x is expressed in radians. The result of the tanh function cannot have a range error. ═══ Example of tanh ═══ /************************************************************************ * This example computes x as the hyperbolic tangent of у/4. * ************************************************************************/ #include #include int main(void) { double pi, x; pi = 3.1415926; x = tanh(pi/4); printf("tanh( %lf ) = %lf\n", pi/4, x); } /****************** Output should be similar to: **************** tanh( 0.785398 ) = 0.655794 */ ═══ Related Information ═══ o atan - atan2 - Calculate Arctangent o cosh - Calculate Hyperbolic Cosine o _fpatan - Calculate Arctangent o _fptan - Calculate Tangent o sinh - Calculate Hyperbolic Sine o tan - Calculate Tangent o math.h ═══ 6.248. _tcalloc - Reserve Tiled Storage Block ═══ ═══ Format ═══ #define __TILED__ #include /* also defined in */ void *_tcalloc(size_t number, size_t size) ═══ Description ═══ Language Level: Extension The _tcalloc function allocates tiled memory for an array of number elements, each of length size bytes, and initializes all bits of each element to 0. The allocated memory is guaranteed not to cross a 64K boundary if the size is not greater than 64K. Otherwise, the memory is aligned on a 64K boundary. Note: Memory allocated by _tcalloc must be freed using the _tfree function, and not any other version of free. The _tcalloc function returns a pointer to the allocated tiled memory. If not enough storage is available, or if num or size is 0, _tcalloc returns NULL. Example of _tcalloc ═══ Example of _tcalloc ═══ /************************************************************************ * This program allocates tiled memory for an array of 100 elements of size char. * ************************************************************************/ #ifndef __TILED__ #define __TILED__ #endif #include int main() { char *memoryPtr; if ((memoryPtr = _tcalloc( 100, sizeof(char)) != NULL) { printf("Successfully allocated 100 char of tiled memory.\n"); _tfree(memoryPtr); } else printf("Unable to allocate tiled object.\n"); /******** If the program is successful, the output should be: ****** Successfully allocated 100 char of tiled memory. *********************************************************************/ } ═══ Related Information ═══ o calloc - Reserve and Initialize Storage o _debug_calloc - Reserve and Initialize Storage o _msize - Return Number of Bytes Allocated o _tmalloc - Reserve Tiled Storage Block o _trealloc - Reallocate Tiled Storage Block o _tfree - Free Tiled Storage Block ═══ 6.249. _tell - Get Pointer Position ═══ ═══ Format ═══ #include long _tell(int handle); ═══ Description ═══ Language Level: Extension The _tell function gets the current position of the file pointer associated with handle. The position is the number of bytes from the beginning of the file. The _tell function returns the current position. A return value of -1L indicates an error, and errno is set to one of the following values: Value Meaning EBADF The file handle is not valid. EOS2ERR The call to the operating system was not successful. On devices incapable of seeking (such as screens and printers), the return value is -1L. Example of _tell ═══ Example of _tell ═══ /************************************************************************ * This example opens the file sample.dat. It then uses tell to get the current position of the file pointer and report if it is successful or unsuccessful. The program then closes sample.dat. * ************************************************************************/ #include #include #include #include int main(void) { long filePtrPos; int fh; printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { perror("Unable to open sample.dat"); return 1; } /* Get the current file pointer position. */ if ( -1 == (filePtrPos = _tell(fh))) { perror("Unable to _tell"); _close(fh); return 1; } printf("File pointer is at position %d.\n",filePtrPos); _close(fh); return 0; /******************* The expected output is: ************************** Creating sample.dat. File pointer is at position 0. */ } ═══ Related Information ═══ o fseek - Reposition File Position o ftell - Get Current Position o _lseek - Move File Pointer o io.h ═══ 6.250. _tempnam - Produce Temporary File Name ═══ ═══ Format ═══ #include char *_tempnam(char *dir, char *prefix); ═══ Description ═══ Language Level: Extension The _tempnam function creates a temporary file name in another directory. The prefix is the prefix to the file name. The _tempnam function tests for the existence of the file with the given name in the following directories, listed in order of precedence: o If the TMP environment variable is set and the directory specified by TMP exists, the directory is specified by TMP. o If the TMP environment variable is not set or the directory specified by TMP does not exist, the directory is specified by the dir argument to _tempnam o If the dir argument is NULL, or dir is the name of nonexistent directory, the directory is pointed to by P_tmpdir in . o If P_tmpdir does not exist, the directory is the current working directory. Note: Because _tempnam uses malloc to reserve space for the created file name, you must free this space when you no longer need it. The _tempnam function returns a pointer to the temporary name, if successful. If the name cannot be created or it already exists, _tempnam returns the value NULL. Example of _tempnam ═══ Example of _tempnam ═══ /*************************************************************************** * * This example creates a temporary file name using the directory a:\tmp: * ************************************************************************/ #include int main(void) { char *name1; if((name1 = _tempnam("a:\\tmp","stq")) != NULL) printf("%s is safe to use as a temporary file.\n", name1); else printf("Cannot create unique filename\n"); return 0; /***************** The output should be similar to: ******************* D:\stqU3CP2.C2T is safe to use as a temporary file. */ } ═══ Related Information ═══ o malloc - Reserve Storage Block o _rmtmp - Remove Temporary Files o tmpfile - Create Temporary File o tmpnam - Produce Temporary File Name o stdio.h ═══ 6.251. _tfree - Free Tiled Storage Block ═══ ═══ Format ═══ #define __TILED__ #include /* also defined in */ void _tfree(void *ptr); ═══ Description ═══ Language Level: Extension The _tfree function frees the tiled memory pointed to by ptr that has been allocated by one of the memory management functions. If ptr is NULL, then no action occurs. Note: The _tfree function can only be used to free memory allocated by the tiled memory management functions. The _tfree function has no return value. Example of _tfree ═══ Example of _tfree ═══ /************************************************************************ * This example uses the _tfree function to free a block of tiled memory that was previously allocated by the _tmalloc function. * ************************************************************************/ #ifndef __TILED__ #define __TILED__ #endif #include int main() { char *memoryPtr; if ((memoryPtr = _tmalloc(100)) != NULL) { printf("Successfully allocated 100 bytes of tiled memory.\n"); _tfree(memoryPtr); } else printf("Unable to allocate tiled object.\n"); /******** If the program is successful, the output should be: ***** Successfully allocated 100 bytes of tiled memory. ********************************************************************/ } ═══ Related Information ═══ o free - Release Storage Blocks o _debug_free - Release Storage Blocks o _tcalloc - Reserve Tiled Storage Block o _trealloc - Reallocate Tiled Storage Block o _tmalloc - Reserve Tiled Storage Block ═══ 6.252. _threadstore - Access Thread-Specific Storage ═══ ═══ Format ═══ #include void *_threadstore(void); ═══ Description ═══ Language Level: Extension The _threadstore function gives you access to a private thread pointer that is initialized to NULL. You can assign any thread-specific data structure to this pointer. The _threadstore function returns the address of the pointer to the defined thread storage space. Example of _threadstore ═══ Example of _threadstore ═══ /************************************************************************ * This example uses the _threadstore function to point to storage that is local to the thread. It prints the address pointed to by _threadstore. * ************************************************************************/ #include #include #include #define privateStore (*_threadstore()) void thread(void *dummy) { privateStore = malloc(100); printf("The starting address of the storaged space is %p\n", privateStore); /* user must free storage before exiting thread */ free (privateStore); _endthread(); } int main(void) { int i; for (i=0;i < 10; i++) { _beginthread(thread,NULL,(unsigned) 32096, NULL) ; } DosSleep(5000L); } ═══ Related Information ═══ o _beginthread - Create New Thread o _endthread - Terminate Current Thread o stdlib.h ═══ 6.253. time - Determine Current Time ═══ ═══ Format ═══ #include time_t time(time_t *timeptr); ═══ Description ═══ Language Level: ANSI, SAA The time function determines the current calendar time, which is not necessarily the local time localtime. The time function returns the current calendar time. The return value is also stored in the location given by timeptr. If timeptr is NULL, the return value is not stored. If the calendar time is not available, the value (time_t)(-1) is returned. Note: The time and date functions begin at 00:00 Universal Time, January 1, 1970. Example of time ═══ Example of time ═══ /************************************************************************ * This example gets the time and assigns it to ltime. It then uses the ctime function to convert the number of seconds to the current date and time. This example then prints a message giving the current time. * ************************************************************************/ #include #include int main(void) { time_t ltime; time(<ime); printf("The time is %s\n", ctime(<ime)); } /****************** Output should be similar to: **************** The time is Mon Mar 22 19:01:41 1993 */ ═══ Related Information ═══ o asctime - Convert Time o ctime - Convert Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o _strtime - Copy Time o time.h ═══ 6.254. _tmalloc - Reserve Tiled Storage Block ═══ ═══ Format ═══ #define __TILED__ #include /* also defined in */ void _tmalloc(size_t size); ═══ Description ═══ Language Level: Extension The _tmalloc function allocates tiled memory for an object of size size, the value of which is indeterminate. If the size is less than 64K, then the memory block is guaranteed not to cross a 64K boundary. Otherwise, the block will begin on a 64K boundary. Note: Memory allocated by the _tmalloc function may only be freed using the _tfree function. The _tmalloc function returns a pointer to the allocated tiled memory. If not enough storage is available, or if size is 0, then _tmalloc returns NULL. Example of _tmalloc ═══ Example of _tmalloc ═══ /************************************************************************ * This example used the _tmalloc function to allocate 100 bytes of tiled memory. * ************************************************************************/ #ifndef __TILED__ #define __TILED__ #endif #include int main() { char *memoryPtr; if ((memoryPtr = _tmalloc(100)) != NULL) { printf("Successfully allocated 100 bytes of tiled memory.\n"); _tfree(memoryPtr); } else printf("Unable to allocate tiled object.\n"); /******** If the program is successful, the output should be: ****** Successfully allocated 100 bytes of tiled memory. *********************************************************************/ } ═══ Related Information ═══ o _debug_malloc - Reserve Storage Blocks o malloc - Reserve Storage Block o _msize - Return Number of Bytes Allocated o _tcalloc - Reserve Tiled Storage Block o _trealloc - Reallocate Tiled Storage Block o _tfree - Free Tiled Storage Block o stdlib.h ═══ 6.255. tmpfile - Create Temporary File ═══ ═══ Format ═══ #include FILE *tmpfile(void); ═══ Description ═══ Language Level: ANSI, SAA The tmpfile function creates a temporary binary file. The file is automatically removed when it is closed or when the program is terminated. The tmpfile function opens the temporary file in wb+ mode. The tmpfile function returns a stream pointer, if successful. If it cannot open the file, it returns a NULL pointer. On normal termination (exit), these temporary files are removed. Example of tmpfile ═══ Example of tmpfile ═══ /************************************************************************ * This example creates a temporary file and if successful, writes tmpstring to it. At program termination, the file is removed. * ************************************************************************/ #include FILE *stream; char tmpstring[ ] = "This is the string to be temporarily written"; int main(void) { if((stream = tmpfile( )) == NULL) perror("Cannot make a temporary file"); else fprintf(stream, "%s", tmpstring); } ═══ Related Information ═══ o fopen - Open Files o tmpnam - Produce Temporary File Name o _tempnam - Produce Temporary File Name o _rmtmp - Remove Temporary Files o stdio.h ═══ 6.256. tmpnam - Produce Temporary File Name ═══ ═══ Format ═══ #include char *tmpnam(char *string); ═══ Description ═══ Language Level: ANSI, SAA The tmpnam function produces a valid file name that is not the same as the name of any existing file. It stores this name in string. If string is NULL, tmpnam leaves the result in an internal static buffer. Any subsequent calls destroy this value. If string is not NULL, it must point to an array of at least L_tmpnam bytes. The value of L_tmpnam is defined in . The tmpnam function returns a pointer to the name, unless it cannot create a unique name; in which case, it returns NULL. The tmpnam function produces a different name each time it is called within a module up to at least TMP_MAX (a value of at least 25) names. Note that files created using names returned by tmpnam are not automatically discarded at the end of the program. Files can be removed by the remove function. Example of tmpnam ═══ Example of tmpnam ═══ /************************************************************************ * This example calls tmpnam to produce a valid file name. * ************************************************************************/ #include int main(void) { char *name1; if ((name1 = tmpnam(NULL)) !=NULL) printf("%s can be used as a file name.\n", name1); else printf("Cannot create a unique file name\n"); } ═══ Related Information ═══ o fopen - Open Files o remove - Delete File o _tempnam - Produce Temporary File Name o stdio.h ═══ 6.257. _toascii - _tolower - _toupper - Convert Character ═══ ═══ Format ═══ #include int _toascii(int c); int _tolower(int c); int _toupper(int c); ═══ Description ═══ Language Level: Extension The _toascii, _tolower, and _toupper macros convert a single character as described below. The _toascii macro sets all but the low-order 7 bits of c to 0 so that the converted value represents a character in the ASCII character set. If c already represents an ASCII character, c is unchanged. Important Only use the _tolower macro when you know that c is uppercase. The result of _tolower is undefined if c is not an uppercase letter. Only use the _toupper macro when you know that c is lowercase. The result of _toupper is undefined if c is not a lowercase letter. Note: These are all macros, but _tolower and _toupper also have function versions because the macro versions do not correctly handle arguments with side effects. Function declarations of _tolower and _toupper are given in . The function versions are part of the standard library, and are defined in the SAA standard. For portability, use the functions instead of the macros. The _toascii, _tolower, and _toupper macros return the possibly converted character c. There is no error return. Example of _toascii - _tolower - _toupper ═══ Example of _toascii &ndask. _tolower - _toupper ═══ /************************************************************************ * This example prints four sets of characters. The first set is the ASCII characters having graphic images, which range from 0x21 through 0x7e. The second set takes integers 0x7f21 through 0x7f7e and applies the _toascii macro to them, yielding the same set of printable characters. The third set is the characters with all lowercase letters converted to uppercase. The fourth set is the characters with all uppercase letters converted to lowercase. * ************************************************************************/ #include #include int main(void) { int ch; printf("Characters 0x01 to 0x03, and integers 0x7f01 to 0x7f03 mapped to\n"); printf("ASCII by _toascii() both yield the same graphic characters.\n\n"); for (ch = 0x01; ch <= 0x03; ch++) { printf("char 0x%.4X: %c ", ch, ch); printf("char _toascii(0x%.4X): %c\n", ch+0x7f00, ch+0x7f00); } printf("\nCharacters A, B and C converted to lower case and\n"); printf("Characters a, b and c converted to upper case.\n\n"); for (ch = 0x41; ch <= 0x43; ch++) { printf("_tolower(%c) = %c ", ch, _tolower(ch) ); printf("_toupper(%c) = %c\n", ch+0x20, _toupper(ch+0x20) ); } return 0; /********** The output should be similar to: ************** Characters 0x01 to 0x03, and integers 0x7f01 to 0x7f03 mapped to ASCII by _/toascii() both yield the same graphic characters. char 0x0001:  char _toascii(0x7F01):  char 0x0002:  char _toascii(0x7F02):  char 0x0003:  char _toascii(0x7F03):  Characters A, B and C converted to lower case and Characters a, b and c converted to upper case. _tolower(A) = a _toupper(a) = A _tolower(B) = b _toupper(b) = B _tolower(C) = c _toupper(c) = C */ } ═══ Related Information ═══ o isalnum to isxdigit - Test Integer Value o _isascii - Test Integer Values o _iscsym - _iscsymf - Test Integer o tolower - toupper - Convert Character Case o ctype.h ═══ 6.258. tolower - toupper - Convert Character Case ═══ ═══ Format ═══ #include int tolower(int c); /* Convert c to lowercase if appropriate */ int toupper(int c); /* Convert c to uppercase if appropriate */ ═══ Description ═══ Language Level: ANSI, SAA The tolower function returns a lowercase c if c represents an uppercase letter; otherwise, c is returned. c is unchanged. The toupper function returns an uppercase c if c represents a lowercase letter; otherwise, c is returned. c is unchanged. Example of tolower - toupper ═══ Example of tolower - toupper ═══ /************************************************************************ * This example uses the toupper and tolower functions to modify characters between code 0 and code 7f. * ************************************************************************/ #include #include int main(void) { int ch; for (ch = 0; ch <= 0x7f; ch++) { printf("toupper=%#04x\n", toupper(ch)); printf("tolower=%#04x\n", tolower(ch)); putchar('\n'); } } ═══ Related Information ═══ o isalnum to isxdigit - Test Integer Value o _isascii - Test Integer Values o _iscsym - _iscsymf - Test Integer o _toascii - _tolower - _toupper - Convert Character o ctype.h ═══ 6.259. _trealloc - Reallocate Tiled Storage Block ═══ ═══ Format ═══ #define __TILED__ #include /* also defined in */ void _trealloc(void *ptr, size_t size); ═══ Description ═══ Language Level: Extension The _trealloc function changes the size of the tiled memory pointed to ptr to the specified size, in bytes. The contents of the tiled memory are unchanged up to the smaller of the new and old sizes. Any new tiled memory that is allocated is uninitialized. Note: The _trealloc function reallocates tiled memory that has been allocated by the _tmalloc, _tcalloc or _trealloc functions. If the memory was not allocated by one of these functions or was previously freed, a message appears and the program ends. The _trealloc function returns a pointer to the reallocated tiled memory. If not enough storage is available or size is 0, then _trealloc returns NULL and the original block does not change. Example of _trealloc ═══ Example of _trealloc ═══ /************************************************************************ * This example uses _trealloc to reallocate a block of tiled memory that was previously allocated by _tmalloc. * ************************************************************************/ #ifndef __TILED__ #define __TILED__ #endif #include int main() { char *memoryPtr; if ((memoryPtr = _tmalloc(100)) != NULL) { printf("Successfully allocated 100 bytes of tiled memory.\n"); } else { printf("Unable to allocate tiled object.\n"); return 1; } if ((memoryPtr = _trealloc(memoryPtr,1000)) != NULL) { printf("Successfully reallocated 1000 bytes of tiled memory.\n"); _tfree(memoryPtr); } else { printf("Unable to allocate tiled object.\n"); return 1; } if ((memoryPtr = _tmalloc(100)) != NULL) /******** If the program is successful, the output should be: ***** Successfully reallocated 100 bytes of tiled memory. ********************************************************************/ } ═══ Related Information ═══ o _debug_calloc - Reserve and Initialize Storage o _msize - Return Number of Bytes Allocated o realloc - Change Reserved Storage Block Size o _tcalloc - Reserve Tiled Storage Block o _tmalloc - Reserve Tiled Storage Block o _tfree - Free Tiled Storage Block o stdlib.h ═══ 6.260. _tzset - Assign Values to Locale Information ═══ ═══ Format ═══ #include void _tzset(void); ═══ Description ═══ Language Level: Extension The _tzset function uses the environment variable TZ to change the time zone and daylight saving time (DST) zone values of your current locale. These values are used by the gmtime and localtime functions to make corrections from Coordinated Universal Time (formerly GMT) to local time. To use _tzset, set the TZ variable to the appropriate values. (For the possible values for TZ, see the chapter on runtime environment variables in the Programming Guide) Then call _tzset to incorporate the changes in the time zone information into your current locale. To set TZ from within a program, use the _putenv function before calling _tzset. Note: The time and date functions begin at 00:00 Coordinated Universal Time, January 1, 1970. :enote. There is no return value. Example of _tzset ═══ Example of _tzset ═══ /************************************************************************ * This example uses the _putenv and _tzset functions to set the time zone to Central Time. * ************************************************************************/ #include #include int main(void) { time_t currentTime; struct tm * ts; /* Get the current time */ (void)time(¤tTime); printf( "The GMT time is %s\n", asctime(gmtime(¤tTime)) ); ts = localtime(¤tTime); if (ts->tm_isdst > 0) /* check if Daylight Saving Time is in effect */ { printf("The local time is %s", asctime(ts)); printf("Daylight Saving Time is in effect.\n"); } else { printf("The local time is %s",asctime(ts)); printf("Daylight Saving Time is not in effect.\n\n"); } printf("**** Changing to Central Time **** \n\n"); _putenv("TZ=CST6CDT"); _tzset(); ts = localtime(¤tTime); if (ts->tm_isdst > 0) /* check if Daylight Saving Time is in effect */ { printf("The local time is %s",asctime(ts)); printf("Daylight Saving Time is in effect.\n"); } else { printf("The local time is %s",asctime(ts)); printf("Daylight Saving Time is not in effect.\n"); } /* Possible output could be: The GMT time is Thu Sep 3 11:55:04 1991 The local time is Thu Sep 3 07:55:04 1991 Daylight Saving Time is in effect. **** Changing to Central Time **** The local time is Thu Sep 3 06:55:04 1991 Daylight Saving Time is in effect. */ } ═══ Related Information ═══ o asctime - Convert Time o _ftime - Store Current Time o gmtime - Convert Time o localtime - Convert Time o mktime - Convert Local Time o _putenv - Modify Environment Variables o time - Determine Current Time o time.h ═══ 6.261. _ultoa - Convert Unsigned Long Integer to String ═══ ═══ Format ═══ #include char *_ultoa(unsigned long value, char *string, int radix); ═══ Description ═══ Language Level: Extension The _ultoa function converts the digits of the given unsigned long value to a null-terminated character string and stores the result in string. No overflow checking is performed. The radix argument specifies the base of value; it must be in the range of 2 through 36. Note: The space allocated for string must be large enough to hold the returned string. The function can return up to 33 bytes, including the null character (\0). The _ultoa function returns a pointer to string. There is no error return value. Example of _ultoa ═══ Example of _ultoa ═══ /************************************************************************ * This example converts the digits of the value 255 to decimal, binary and hexadecimal representations: * ************************************************************************/ #include #include int main(void) { char buffer[10]; char *p; p = _ultoa(255UL, buffer, 10); printf("The result of _ultoa(255) with radix of 10 is %s\n", p); p = _ultoa(255UL, buffer, 2); printf("The result of _ultoa(255) with radix of 2 is %s\n", p); p = _ultoa(255UL, buffer, 16); printf("The result of _ultoa(255) with radix of 16 is %s\n", p); return 0; /* The expected output is: The result of _ultoa(255) with radix of 10 is 255 The result of _ultoa(255) with radix of 2 is 11111111 The result of _ultoa(255) with radix of 16 is ff */ } ═══ Related Information ═══ o _ecvt - Convert Floating-Point to Character o _fcvt - Convert Floating-Point to String o _gcvt - Convert Floating-Point to String o _itoa - Convert Integer to String o _ltoa - Convert Long Integer to String o stdlib.h ═══ 6.262. _umask - Sets File Mask of Current Process ═══ ═══ Format ═══ #include #include int _umask(int pmode); ═══ Description ═══ Language Level: Extension The _umask function sets the file permission mask of the executing process environment to the mode specified by pmode. The file permission mask modifies the permission setting of new files created by _creat, _open, or _sopen. If a bit in the mask is 1, the corresponding bit in the requested permission value of the file is set to 0 (disallowed). If a bit in the mask is 0, the corresponding bit is left unchanged. The permission setting for a new file is not set until the file is closed for the first time. The _umask function returns the previous value of pmode. A return value of -1 indicates that the value used for pmode was not valid, and errno is set to EINVAL. The variable pmode contains one or both of the constants S_WRITE and S_IREAD, defined in . The possible values for pmode are: Value Meaning S_IREAD No effect S_IWRITE Writing not permitted S_IREAD | S_IWRITE Writing not permitted. If the write bit is set in the mask, any new files will be read-only. You cannot give write-only permission, meaning that setting the read bit has no effect. Example of _umask ═══ Example of _umask ═══ /************************************************************************ * This example sets the permission mask to create a write-only file. * ************************************************************************/ #include #include #include int main(void) { int oldMask; oldMask = _umask(S_IWRITE); printf("\nDefault system startup mask is %d.\n",oldMask); return 0; /****************** The expected output is: *************************** Default system startup mask is 0. */ } ═══ Related Information ═══ o _chmod - Change File Permission Setting o _creat - Create New File o _open - Open File o _sopen - Open Shared File o io.h o sys\stat.h o sys\types.h ═══ 6.263. ungetc - Push Character onto Input Stream ═══ ═══ Format ═══ #include int ungetc(int c, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA The ungetc function pushes the unsigned character c back onto the given input stream. However, only one sequential ungetc is guaranteed to be pushed back onto the input stream if you call ungetc consecutively. The stream must be open for reading. A subsequent read operation on the stream starts with c. You cannot push EOF back on the stream using ungetc. Characters placed on the stream by ungetc will be erased if a fseek, fsetpos, rewind, or fflush function is called before the character is read from the stream. The ungetc function returns the integer argument c converted to an unsigned char or EOF if c cannot be pushed back. Example of ungetc ═══ Example of ungetc ═══ /************************************************************************ * In this example, the while statement reads decimal digits from an input data stream by using arithmetic statements to compose the numeric values of the numbers as it reads them. When a nondigit character appears before the end of the file, ungetc replaces it in the input stream so that later input functions can process it. * ************************************************************************/ #include #include int main(void) { FILE *stream; int ch; unsigned int result = 0; . . . while ((ch = getc(stream)) != EOF && isdigit(ch)) result = result * 10 + ch - '0'; if (ch != EOF) ungetc(ch,stream); /* Put the nondigit character back */ } ═══ Related Information ═══ o getc - Read a Character o fflush - Write Buffer to File o fseek - Reposition File Position o fsetpos - Set File Position o putc - putchar - Write a Character o rewind - Adjust Current File Position o _ungetch - Push Character Back to Keyboard o stdio.h ═══ 6.264. _ungetch - Push Character Back to Keyboard ═══ ═══ Format ═══ #include int _ungetch(int c); ═══ Description ═══ Language Level: Extension The _ungetch function pushes the character c back to the keyboard, causing c to be the next character read. The _ungetch function fails if called more than once before the next read operation. The character c cannot be the EOF character. If successful, the _ungetch function returns the character c. A return value of EOF indicates an error. Example of _ungetch ═══ Example of _ungetch ═══ /************************************************************************ * This example uses _getch to read a string delimited by the character 'x'. It then calls _ungetch to return the delimiter to the keyboard buffer. Other input routines can then process the delimiter. * ************************************************************************/ #include #include int main(void) { int ch; _cprintf("\nType in some letters."); printf("\n"); _cprintf("If you type in an 'x', the program ends.\n"); printf("\n"); for(;;) { ch = _getch(); if (ch == 'x') { _ungetch(ch); break; } _putch(ch); } ch=_getch(); printf("\n"); _cprintf("\nThe last character was '%c'.", ch); return 0; /************** The output should be similar to: ********************** Type in some letters. If you type in an 'x', the program ends. One Two Three Four Five Si The last character was 'x'. */ } ═══ Related Information ═══ o _cscanf - Read Data from Keyboard o _getch - _getche - Read Character from Keyboard o ungetc - Push Character onto Input Stream o conio.h ═══ 6.265. _unlink - Delete File ═══ ═══ Format ═══ #include /* also defined in */ int _unlink(const char *pathname); ═══ Description ═══ Language Level: Extension The _unlink function deletes the file specified by pathname. For portability, you can use the SAA remove function. The _unlink function returns the value 0 if the file is successfully deleted. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS The path name specifies a read-only file or a directory. EISOPEN The file is open. ENOENT An incorrect path name was specified, or the file or path name was not found. Example of _unlink ═══ Example of _unlink ═══ /************************************************************************ * This example deletes the file tmpfile from the system or prints an error message if unable to delete it. * ************************************************************************/ #include int main(void) { if (_unlink("tmpfile") == -1) perror("Cannot delete tmpfile"); else printf("tmpfile has been successfully deleted\n"); return 0; /***************** The output should be similar to: ******************* tmpfile has been successfully deleted */ } ═══ Related Information ═══ o remove - Delete File o _rmtmp - Remove Temporary Files o stdio.h ═══ 6.266. _utime - Set Modification Time ═══ ═══ Format ═══ #include #include int _utime(char *pathname, struct utimbuf *times); ═══ Description ═══ Language Level: Extension The _utime function sets the modification time for the file specified by pathname. The process must have write access to the file; otherwise, the time cannot be changed. Although the utimbuf structure contains a field for access time, only the modification time is set in the OS/2 operating system. If times is a NULL pointer, the modification time is set to the current time. Otherwise, times must point to a structure of type utimbuf, defined in . The modification time is set from the modtime field in this structure. Note: The _utime function accepts only even numbers of seconds. If you enter an odd number of seconds, the function rounds it down. The _utime function returns the value 0 if the file modification time was changed. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EACCESS The path name specifies a directory or read-only file. EMFILE There are too many open files. The file must be opened to change its modification time. ENOENT The file path name was not found, or the file name was incorrectly specified. Example of _utime ═══ Example of _utime ═══ /************************************************************************ * This example sets the last modification time of file \TMP\DATA to the current time. It prints an error message if it cannot. * ************************************************************************/ #include #include #include #include int main(void) { struct utimbuf ubuf; struct stat statbuf; /* seconds to current date from 1970 Jan 1 */ ubuf.modtime = 946702799; /* Sat Dec 31 23:59:59 1999 */ /* changing file modification time */ if (_utime("\\tmp\\data", &ubuf ) == -1) { perror("_utime failed"); _exit(-1); } /* display the modification time */ if (_stat("\\tmp\\data", &statbuf) == 0) printf("The file modification time is %s\n", ctime(&statbuf.st_mtime)); else printf("File could not be found\n"); return 0; /*********** The output should be similar to: ************ The file modification time is Fri Dec 31 23:59:58 1999 */ } ═══ Related Information ═══ o _fstat - Information about Open File o _stat - Get Information about File or Directory o sys\utime.h o sys\types.h ═══ 6.267. va_arg - va_end - va_start - Access Function Arguments ═══ ═══ Format ═══ #include var_type va_arg(va_list arg_ptr, var_type); void va_end(va_list arg_ptr); void va_start(va_list arg_ptr, variable_name); ═══ Description ═══ Language Level: ANSI, SAA The va_arg, va_end, and va_start macros access the arguments to a function when it takes a fixed number of required arguments and a variable number of optional arguments. You declare required arguments as ordinary parameters to the function and access the arguments through the parameter names. The va_start macro initializes the arg_ptr pointer for subsequent calls to va_arg and va_end. The argument variable_name is the identifier of the rightmost named parameter in the parameter list (preceding , ...). Use the va_start macro before the va_arg macro. Corresponding va_start and va_end macros must be in the same function. The va_arg macro retrieves a value of the given var_type from the location given by arg_ptr and increases arg_ptr to point to the next argument in the list. The va_arg macro can retrieve arguments from the list any number of times within the function. The var_type argument must be one of int, long, double, struct, union, or pointer, or a typedef of one of these types. The va_end macro is needed to indicate the end of parameter scanning. The va_arg macro returns the current argument. The va_end and va_start macros do not return a value. Example of va_arg - va_end - va_start ═══ Example of va_arg - va_end - va_start ═══ /************************************************************************ * This example passes a variable number of arguments to a function, stores each argument in an array, and prints each argument. * ************************************************************************/ #include #include int vout(int max, ...); int main(void) { vout(3, "Sat", "Sun", "Mon"); printf("\n"); vout(5, "Mon", "Tues", "Wed", "Thurs", "Fri"); } int vout(int max, ...) { va_list arg_ptr; int args = 0; char *days[7]; va_start(arg_ptr, max); while(args < max) { days[args] = va_arg(arg_ptr, char *); printf("Day: %s \n", days[args++]); } va_end(arg_ptr); } /****************** Output should be similar to: **************** Day: Sat Day: Sun Day: Mon Day: Mon Day: Tues Day: Wed Day: Thurs Day: Fri */ ═══ Related Information ═══ o vfprintf - Print Argument Data o vprintf - Print Argument Data o vsprintf - Print Argument Data o stdarg.h ═══ 6.268. vfprintf - Print Argument Data ═══ ═══ Format ═══ #include #include int vfprintf(FILE *stream, const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, Extension The vfprintf function is similar to fprintf, except that arg_ptr points to a list of arguments whose number can vary from call to call in the program. These arguments should be initialized by va_start for each call. In contrast, fprintf can have a list of arguments, but the number of arguments in that list is fixed when you compile the program. For a specification of the format string, see printf. In extended mode, vfprintf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. If there is no error, vfprintf returns the number of characters written to stream. If an error occurs, the function returns a negative value. Example of vfprintf ═══ Example of vfprintf ═══ /************************************************************************ * This example prints out a variable number of strings to the file myfile. * ************************************************************************/ #include #include void vout(FILE *stream, char *fmt, ...); char fmt1 [] = "%s %s %s\n"; int main(void) { FILE *stream; stream = fopen("myfile.dat", "w"); vout(stream, fmt1, "Sat", "Sun", "Mon"); } void vout(FILE *stream, char *fmt, ...) { va_list arg_ptr; va_start(arg_ptr, fmt); vfprintf(stream, fmt, arg_ptr); va_end(arg_ptr); } /****************** Output should be similar to: **************** Sat Sun Mon */ ═══ Related Information ═══ o fprintf - Write Formatted Data o printf - Formatted Print o sprintf - Formatted Print to Buffer o va_arg - va_end - va_start - Access Function Arguments o vprintf - Print Argument Data o vsprintf - Print Argument Data o Infinity and NaN Support o stdarg.h o stdio.h ═══ 6.269. vprintf - Print Argument Data ═══ ═══ Format ═══ #include #include int vprintf(const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, Extension The vprintf function is similar to printf, except that arg_ptr points to a list of arguments whose number can vary from call to call in the program. These arguments should be initialized by va_start for each call. In contrast, printf can have a list of arguments, but the number of arguments in that list is fixed when you compile the program. For a specification of the format string, see printf. In extended mode, vprintf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. If there is no error, vprintf returns the number of characters written to stdout. If an error occurs, this function returns a negative value. Example of vprintf ═══ Example of vprintf ═══ /************************************************************************ * This example prints out a variable number of strings to stdout. * ************************************************************************/ #include #include void vout(char *fmt, ...); char fmt1 [] = "%s %s %s %s %s \n"; int main(void) { FILE *stream; stream = fopen("myfile.dat", "w"); vout(fmt1, "Mon", "Tues", "Wed", "Thurs", "Fri"); } void vout(char *fmt, ...) { va_list arg_ptr; va_start(arg_ptr, fmt); vprintf(fmt, arg_ptr); va_end(arg_ptr); } /****************** Output should be similar to: **************** Mon Tues Wed Thurs Fri */ ═══ Related Information ═══ o fprintf - Write Formatted Data o printf - Formatted Print o sprintf - Formatted Print to Buffer o va_arg - va_end - va_start - Access Function Arguments o vfprintf - Print Argument Data o vsprintf - Print Argument Data o Infinity and NaN Support o stdarg.h o stdio.h ═══ 6.270. vsprintf - Print Argument Data ═══ ═══ Format ═══ #include #include int vsprintf(char *target-string, const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, Extension The vsprintf function is similar to sprintf except that arg_ptr points to a list of arguments whose number can vary from call to call in the program. In contrast, sprintf can have a list of arguments, but the number of arguments in that list is fixed when you compile the program. For a specification of the format string, see printf. In extended mode, vsprintf also converts floating-point values of NaN and infinity to the strings "NAN" or "nan" and "INFINITY" or "infinity". The case and sign of the string is determined by the format specifiers. See Infinity and NaN Support for more information on infinity and NaN values. If there is no error, vsprintf returns the number of characters written to target-string. If an error occurs, this function returns a negative value. Example of vsprintf ═══ Example of vsprintf ═══ /************************************************************************ * This example assigns a variable number of strings to string and prints the resultant string. * ************************************************************************/ #include #include void vout(char *string, char *fmt, ...); char fmt1 [] = "%s %s %s\n"; int main(void) { char string[100]; vout(string, fmt1, "Sat", "Sun", "Mon"); printf("The string is: %s\n", string); } void vout(char *string, char *fmt, ...) { va_list arg_ptr; va_start(arg_ptr, fmt); vsprintf(string, fmt, arg_ptr); va_end(arg_ptr); } /****************** Output should be similar to: **************** The string is: Sat Sun Mon */ ═══ Related Information ═══ o fprintf - Write Formatted Data o printf - Formatted Print o sprintf - Formatted Print to Buffer o va_arg - va_end - va_start - Access Function Arguments o vfprintf - Print Argument Data o vprintf - Print Argument Data o Infinity and NaN Support o stdarg.h o stdio.h ═══ 6.271. _wait - Wait for Child Process ═══ ═══ Format ═══ #include int _wait (int *stat_loc); ═══ Description ═══ Language Level: Extension The _wait function delays a parent process until one of the immediate child processes stops. If all the child processes stop before _wait is called, control returns immediately to the parent function. If stat_loc is NULL, the _wait function does not use it. If it is not NULL, _wait places information about the return status and the return code ot the child process that ended in the location to which stat_loc points. If the child process ended normally, with a call to the OS/2 DosExit function, the lowest-order byte of stat_loc is 0, and the next higher-order byte contains the lowest-order byte of the argument passed to DosExit by the child process. The value of this byte depends on how the child process caused the system to call DosExit. If the child process called exit, _exit, or return from main, the byte contains the lowest-order byte of the argument the child process passed to exit, _exit, or return. The value of the byte is undefined if the child process caused a DosExit call simply by reaching the end of main. If the child process ended abnormally, the lowest-order byte of stat_loc contains the return status code from the OS/2 DosWaitChild function, and the next higher-order byte is 0. See the Toolkit online Programming Reference for details about the DosWaitChild return status codes. If _wait returns after a normal end of a child process, it returns the process identifier of the child process to the parent process. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning ECHILD There were no child processes or they all ended before the call to _wait. This value indicates that no child processes exist for the particular process. EINTR Unexpected end of a child process. Example of _wait ═══ Example of _wait ═══ /************************************************************************ * This example creates a new process called CHILD.EXE, specifying P_NOWAIT when the child process is called. The parent process calls _wait and waits for the child process to stop running. The parent process then displays the return information of the child process in hexadecimal. * ************************************************************************/ #include #include int stat_child; int main(void) { int pid; _spawnl(P_NOWAIT,"child2.exe", "child2.exe", NULL); if ( (pid=_wait(&stat_child)) == -1 ) perror(NULL); /* Display error status message, if any */ else printf("child process %d just ran.\n",pid); /* Display the word returned when child ended. */ printf("return information was 0x%X\n",stat_child); return 0; /* If the source for child2.exe is: */ /* */ /* #include */ /* int main(void) */ /* { */ /* puts("child2.exe is an executable file"); */ /* } */ /* */ /* Then the ouput should be similar to: */ /* child process 24 just ran. */ /* return information was 0x0 */ } ═══ Related Information ═══ o _cwait - Wait for Child Process o _execl - _execvp - Load and Run Child Process o exit - End Program o _exit - End Process o _spawnl -_spawnvpe -Start and Run Child Processes o process.h ═══ 6.272. wcscat - Append wchar_t Strings ═══ ═══ Format ═══ #include wchar_t *wcscat(wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcscat function appends a copy of the string pointed to by string2 to the end of the string pointed to by string1. The wcscat function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. Boundary checking is not performed. The wcscat function returns the value of string1. Example of wcscat ═══ Example of wcscat ═══ /************************************************************************* * This example creates the wide character string "computer program" using wcscat. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t buffer1[SIZE] = L"computer"; wchar_t * string = L" program"; wchar_t * ptr; ptr = wcscat( buffer1, string ); printf( "buffer1 = %ls\n", buffer1 ); } /************************************************************************ * /**************** Output should be similar to: ****************** buffer1 = computer program */ * ************************************************************************/ ═══ Related Information ═══ o strcat - Concatenate Strings o strncat - Concatenate Strings o wcsncat - Concatenate wchar_t Strings o wcstr.h ═══ 6.273. wcschr - Search wchar_t String for Given wchar_t ═══ ═══ Format ═══ #include wchar_t *wcschr(const wchar_t *string1, wchar_t character); ═══ Description ═══ Language Level: SAA The wcschr function searches string for the occurrence of character. The character may be a wchar_t null character (\0); the wchar_t null character at the end of string is included in the search. The wcschr function operates on null-terminated wchar_t strings. The string argument to this function should contain a wchar_t null character marking the end of the string. The wcschr function returns a pointer to the first occurrence of character in string. If the character is not found, a NULL pointer is returned. Example of wcschr ═══ Example of wcschr ═══ /************************************************************************* * This example finds the first occurrence of the character p in the wide character string "computer program". * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t buffer1[SIZE] = L"computer program"; wchar_t * ptr; wchar_t ch = L'p'; ptr = wcschr( buffer1, ch ); printf( "The first occurrence of %lc in '%ls' is '%ls'\n", ch, buffer1, ptr ); } /************************************************************************ * /**************** Output should be similar to: ****************** The first occurrence of p in 'computer program' is 'puter program' */ * ************************************************************************/ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcscspn - Find Offset of First wchar_t Match o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o wcstr.h ═══ 6.274. wcscmp - Compare wchar_t Strings ═══ ═══ Format ═══ #include int wcscmp(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcscmp function compares two wchar_t strings. The wcscmp function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. Boundary checking is not performed when a string is added to or copied. The wcscmp function returns a value indicating the relationship between the two strings, as follows: Value Meaning Less than 0 string1 less than string2 0 string1 identical to string2 Greater than 0 string1 greater than string2. Example of wcscmp ═══ Example of wcscmp ═══ /************************************************************************* * This example compares the wide character string string1 to string2 using wcscmp. * ************************************************************************/ #include #include int main(void) { int result; wchar_t string1[] = L"abcdef"; wchar_t string2[] = L"abcdefg"; result = wcscmp( string1, string2 ); if ( result == 0 ) printf( "\"%ls\" is identical to \"%ls\"\n", string1, string2); else if ( result < 0 ) printf( "\"%ls\" is less than \"%ls\"\n", string1, string2 ); else printf( "\"%ls\" is greater than \"%ls\"\n", string1, string2); } /************************************************************************ * /**************** Output should be similar to: ****************** "abcdef" is less than "abcdefg" */ * ************************************************************************/ ═══ Related Information ═══ o strcmp - Compare Strings o strcmpi - Compare Strings o stricmp - Compare Strings o strnicmp - Compare Strings o wcsncmp - Compare wchar_t Strings o wcstr.h ═══ 6.275. wcscpy - Copy wchar_t Strings ═══ ═══ Format ═══ #include wchar_t *wcscpy(wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcscpy function copies the contents of string2 (including the ending wchar_t null character) into string1. The wcscpy function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. Boundary checking is not performed. The wcscpy function returns the value of string1. Example of wcscpy ═══ Example of wcscpy ═══ /************************************************************************* * This example copies the contents of source to destination. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t source[ SIZE ] = L"This is the source string"; wchar_t destination[ SIZE ] = L"And this is the destination string"; wchar_t * return_string; printf( "destination is originally = \"%ls\"\n", destination ); return_string = wcscpy( destination, source ); printf( "After wcscpy, destination becomes \"%ls\"\n", destination ); } /************************************************************************ * /**************** Output should be similar to: ****************** destination is originally = "And this is the destination string" After wcscpy, destination becomes "This is the source string" */ * ************************************************************************/ ═══ Related Information ═══ o strcpy - Copy Strings o strdup - Duplicate String o strncpy - Copy Strings o wcsncpy - Copy wchar_t Strings o wcstr.h ═══ 6.276. wcscspn - Find Offset of First wchar_t Match ═══ ═══ Format ═══ #include /* SAA extension to ANSI */ size_t wcscspn(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcscspn function determines the number of wchar_t characters in the initial segment of the string pointed to by string1 that do not appear in the string pointed to by string2. The wcscspn function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. The wcscspn function returns the number of wchar_t characters in the segment. Example of wcscspn ═══ Example of wcscspn ═══ /************************************************************************* * This example uses wcscspn to find the first occurrence of any of the characters a, x, l, or e in string. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t string[ SIZE ] = L"This is the source string"; wchar_t * substring = L"axle"; printf( "The first %i characters in the string \"%ls\" are not in the " "string \"%ls\" \n", wcscspn( string, substring), string, substring ); } /************************************************************************ * /**************** Output should be similar to: ****************** The first 10 characters in the string "This is the source string" are not in the string "axle" */ * ************************************************************************/ ═══ Related Information ═══ o strcspn - Compare Strings o strspn - Search Strings o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o wcstr.h ═══ 6.277. wcslen - Calculate Length of wchar_t String ═══ ═══ Format ═══ #include size_t wcslen(const wchar_t *string); ═══ Description ═══ Language Level: SAA The wcslen function computes the number of wchar_t characters in the string pointed to by string. The wcslen function returns the number of wchar_t characters that precede the terminating wchar_t null character. Example of wcslen ═══ Example of wcslen ═══ /************************************************************************* * This example computes the length of a wchar_t string. * ************************************************************************/ #include #include int main(void) { wchar_t * string = L"abcdef"; printf( "Length of \"%ls\" is %i\n", string, wcslen( string )); } /************************************************************************ * /**************** Output should be similar to: ****************** Length of "abcdef" is 6 */ * ************************************************************************/ ═══ Related Information ═══ o mblen - Multibyte String Length o strlen - Determine String Length o wcstr.h ═══ 6.278. wcsncat - Concatenate wchar_t Strings ═══ ═══ Format ═══ #include wchar_t *wcsncat(wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA The wcsncat function appends up to count wide characters from string2 to the end of string1 and appends a wchar_t null character to the result. The wcsncat function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. The wcsncat function returns string1. Example of wcsncat ═══ Example of wcsncat ═══ /************************************************************************* * This example demonstrates the difference between wcscat and wcsncat. wcscat appends the entire second string to the first whereas wcsncat appends only the specified number of characters in the second string to the first. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t buffer1[SIZE] = L"computer"; wchar_t * ptr; /* Call wcscat with buffer1 and " program" */ ptr = wcscat( buffer1, L" program" ); printf( "wcscat : buffer1 = \"%ls\"\n", buffer1 ); /* Reset buffer1 to contain just the string "computer" again */ memset( buffer1, L'\0', sizeof( buffer1 )); ptr = wcscpy( buffer1, L"computer" ); /* Call wcsncat with buffer1 and " program" */ ptr = wcsncat( buffer1, L" program", 3 ); printf( "wcsncat: buffer1 = \"%ls\"\n", buffer1 ); } /************************************************************************ * /**************** Output should be similar to: ****************** wcscat : buffer1 = "computer program" wcsncat: buffer1 = "computer pr" */ * ************************************************************************/ ═══ Related Information ═══ o strncat - Concatenate Strings o strcat - Concatenate Strings o wcscat - Append wchar_t Strings o wcstr.h ═══ 6.279. wcsncmp - Compare wchar_t Strings ═══ ═══ Format ═══ #include int wcsncmp(const wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA The wcsncmp function compares up to count wide characters in string1 to string2. The wcsncmp function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. The wcsncmp function returns a value indicating the relationship between the two strings, as follows: Value Meaning Less than 0 string1 less than string2 0 string1 identical to string2 Greater than 0 string1 greater than string2. Example of wcsmcmp ═══ Example of wcsncmp ═══ /************************************************************************* * This example demonstrates the difference between wcscmp and wcsncmp. * ************************************************************************/ #include #include #define SIZE 10 int main(void) { int result; int index = 3; wchar_t buffer1[SIZE] = L"abcdefg"; wchar_t buffer2[SIZE] = L"abcfg"; void print_result( int, wchar_t *, wchar_t * ); result = wcscmp( buffer1, buffer2 ); printf( "Comparison of each character\n" ); printf( " wcscmp: " ); print_result( result, buffer1, buffer2 ); result = wcsncmp( buffer1, buffer2, index); printf( "\nComparison of only the first %i characters\n", index ); printf( " wcsncmp: " ); print_result( result, buffer1, buffer2 ); } void print_result( int res, wchar_t * p_buffer1, wchar_t * p_buffer2 ) { if ( res == 0 ) printf( "\"%ls\" is identical to \"%ls\"\n", p_buffer1, p_buffer2); else if ( res < 0 ) printf( "\"%ls\" is less than \"%ls\"\n", p_buffer1, p_buffer2 ); else printf( "\"%ls\" is greater than \"%ls\"\n", p_buffer1, p_buffer2 ); } /************************************************************************ * /**************** Output should be similar to: ****************** Comparison of each character wcscmp: "abcdefg" is less than "abcfg" Comparison of only the first 3 characters wcsncmp: "abcdefg" is identical to "abcfg" */ * ************************************************************************/ ═══ Related Information ═══ o strncmp - Compare Strings o strcmp - Compare Strings o strcoll - Compare Strings o strcmpi - Compare Strings o stricmp - Compare Strings o strnicmp - Compare Strings o wcscmp - Compare wchar_t Strings o wcstr.h ═══ 6.280. wcsncpy - Copy wchar_t Strings ═══ ═══ Format ═══ #include wchar_t *wcsncpy(wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA The wcsncpy function copies up to count wide characters from string2 to string1. If string2 is shorter than count characters, string1 is padded out to count characters with wchar_t null characters. The wcsncpy function operates on null-terminated wchar_t strings. The string arguments to this function should contain a wchar_t null character marking the end of the string. The wcsncpy function returns string1. Example of wcsncpy ═══ Example of wcsncpy ═══ /************************************************************************* * This example demonstrates the difference between wcscpy and wcsncpy. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t source[ SIZE ] = L"123456789"; wchar_t source1[ SIZE ] = L"123456789"; wchar_t destination[ SIZE ] = L"abcdefg"; wchar_t destination1[ SIZE ] = L"abcdefg"; wchar_t * return_string; int index = 5; /* This is how wcscpy works */ printf( "destination is originally = '%ls'\n", destination ); return_string = wcscpy( destination, source ); printf( "After wcscpy, destination becomes '%ls'\n\n", destination ); /* This is how wcsncpy works */ printf( "destination1 is originally = '%ls'\n", destination1 ); return_string = wcsncpy( destination1, source1, index ); printf( "After wcsncpy, destination1 becomes '%ls'\n", destination1 ); } /************************************************************************ * /**************** Output should be similar to: ****************** destination is originally = 'abcdefg' After wcscpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After wcsncpy, destination1 becomes '12345fg' */ * ************************************************************************/ ═══ Related Information ═══ o strcpy - Copy Strings o strncpy - Copy Strings o wcscpy - Copy wchar_t Strings o wcstr.h ═══ 6.281. wcspbrk - Locate wchar_t Characters in String ═══ ═══ Format ═══ #include wchar_t *wcspbrk(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcspbrk function locates the first occurrence in the string pointed to by string1 of any character from the string pointed to by string2. The wcspbrk function returns a pointer to the character, or NULL if no wchar_t from string2 occurs in string1. Example of wcscpbrk ═══ Example of wcspbrk ═══ /************************************************************************ * This example returns a pointer to the first occurrence in the array string of either a or b. * ************************************************************************/ #include #include int main(void) { wchar_t * result; wchar_t * string = L"The Blue Danube"; wchar_t *chars = L"ab"; result = wcspbrk( string, chars); printf("The first occurrence of any of the characters \"%ls\" in " "\"%ls\" is \"%ls\"\n", chars, string, result); } /************************************************************************ * /**************** Output should be similar to: ****************** The first occurrence of any of the characters "ab" in "The Blue Danube" is "anube" */ * ************************************************************************/ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcsncmp - Compare wchar_t Strings o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o wcstr.h ═══ 6.282. wcsrchr - Locate wchar_t Character in String ═══ ═══ Format ═══ #include wchar_t *wcsrchr(const wchar_t *string, wchar_t character); ═══ Description ═══ Language Level: SAA The wcsrchr function locates the last occurrence of character in the string pointed to by string. The terminating wchar_t null character is considered to be part of the string. The wcsrchr function returns a pointer to the character, or a NULL pointer if character does not occur in the string. Example of wcsrchr ═══ Example of wcsrchr ═══ /************************************************************************ * This example compares the use of wcschr and wcsrchr. It searches the string for the first and last occurrence of p in the wide character string. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t buf[SIZE] = L"computer program"; wchar_t * ptr; int ch = 'p'; /* This illustrates wcschr */ ptr = wcschr( buf, ch ); printf( "The first occurrence of %c in '%ls' is '%ls'\n", ch, buf, ptr ); /* This illustrates wscrchr */ ptr = wcsrchr( buf, ch ); printf( "The last occurrence of %c in '%ls' is '%ls'\n", ch, buf, ptr ); } /************************************************************************ * /**************** Output should be similar to: ****************** The first occurrence of p in 'computer program' is 'puter program' The last occurrence of p in 'computer program' is 'program' */ * ************************************************************************/ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o wcspbrk - Locate wchar_t Characters in String o wcstr.h ═══ 6.283. wcsspn - Search wchar_t Characters in String ═══ ═══ Format ═══ #include size_t wcsspn(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcsspn function computes the number of wchar_t characters in the initial segment of the string pointed to by string1, which consists entirely of wchar_t characters from the string pointed to by string2. The wcsspn function returns the number of wchar_t characters in the segment. Example of wcsspn ═══ Example of wcsspn ═══ /************************************************************************ * This example finds the first occurrence in the array string of a character that is neither an a, b, nor c. Because the string in this example is cabbage, wcsspn returns 5, the index of the segment of cabbage before a character that is not an a, b, or c. * ************************************************************************/ #include #include int main(void) { wchar_t * string = L"cabbage"; wchar_t * source = L"abc"; int index; index = wcsspn( string, L"abc" ); printf( "The first %d characters of \"%ls\" are found in \"%ls\"\n", index, string, source ); } /************************************************************************ * /**************** Output should be similar to: ****************** The first 5 characters of "cabbage" are found in "abc" */ * ************************************************************************/ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcswcs - Locate wchar_t Substring in wchar_t String o wcspbrk - Locate wchar_t Characters in String o wcstr.h ═══ 6.284. wcstombs - Convert wchar_t String to Multibyte Character String ═══ ═══ Format ═══ #include size_t wcstombs(char *dest, const wchar_t *string, size_t count); ═══ Description ═══ Language Level: ANSI, SAA The wcstombs function converts the wchar_t string pointed to by string into the multibyte array pointed to by dest. The converted string begins in the initial shift state. The conversion stops after count bytes in dest are filled up or a wchar_t null character is encountered. The wcstombs function returns the length in bytes of the multibyte character string, not including a terminating null character. The value (size_t)-1 is returned if an invalid multibyte character is encountered. Example of wcstombs ═══ Example of wcstombs ═══ /************************************************************************* * In this example, a wchar_t string is converted to a char string twice. The first call converts the entire string, while the second call only converts three characters. The results are printed each time. * ************************************************************************/ #include #include #include #define SIZE 20 int main(void) { char dest[SIZE]; wchar_t * dptr = L"string"; size_t count = SIZE; size_t length; length = wcstombs( dest, dptr, count ); printf( "%d characters were converted.\n", length ); printf( "The converted string is \"%s\"\n\n", dest ); /* Reset the destination buffer */ memset( dest, '\0', sizeof(dest)); /* Now convert only 3 characters */ length = wcstombs( dest, dptr, 3 ); printf( "%d characters were converted.\n", length ); printf( "The converted string is \"%s\"\n", dest ); } /************************************************************************ * /**************** Output should be similar to: ****************** 6 characters were converted. The converted string is "string" 3 characters were converted. The converted string is "str" */ * ************************************************************************/ ═══ Related Information ═══ o mbstowcs - Convert Multibyte Characters to wchar_t Characters o wcslen - Calculate Length of wchar_t String o wctomb - Convert wchar_t Character to Multibyte Character o stdlib.h ═══ 6.285. wcswcs - Locate wchar_t Substring in wchar_t String ═══ ═══ Format ═══ #include wchar_t *wcswcs(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA The wcswcs function locates the first occurrence in the string pointed to by string1 of the sequence of wchar_t characters (excluding the terminating wchar_t null character) in the string pointed to by string2. The wcswcs function returns a pointer to the located string or NULL if the string is not found. If string2 points to a string with zero length, the function returns string1. Example of wcswcs ═══ Example of wcswcs ═══ /************************************************************************* * This example finds the first occurrence of the wide character string pr in buffer1. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { wchar_t buffer1[SIZE] = L"computer program"; wchar_t * ptr; wchar_t * wch = L"pr"; ptr = wcswcs( buffer1, wch ); printf( "The first occurrence of %ls in '%ls' is '%ls'\n", wch, buffer1, ptr ); } /************************************************************************ * /**************** Output should be similar to: ****************** The first occurrence of pr in 'computer program' is 'program' */ * ************************************************************************/ ═══ Related Information ═══ o strchr - Search for Character o strcspn - Compare Strings o strpbrk - Find Characters in String o strrchr - Find Last Occurrence of Character in String o strspn - Search Strings o wcschr - Search wchar_t String for Given wchar_t o wcscspn - Find Offset of First wchar_t Match o wcspbrk - Locate wchar_t Characters in String o wcsrchr - Locate wchar_t Character in String o wcsspn - Search wchar_t Characters in String o wcstr.h ═══ 6.286. wctomb - Convert wchar_t Character to Multibyte Character ═══ ═══ Format ═══ #include int wctomb(char *string, wchar_t character); ═══ Description ═══ Language Level: ANSI, SAA The wctomb function converts the wchar_t value of character into a multibyte array pointed to by string. If the value of character is 0, the function is left in the initial shift state. At most, wctomb stores MB_CUR_MAX characters in string. The wctomb function returns the length in bytes of the multibyte character. The value -1 is returned if character is not a valid multibyte character. If string is a NULL pointer, the wctomb function returns nonzero if shift-dependent encoding is used, or 0 otherwise. Example of wctomb ═══ Example of wctomb ═══ /************************************************************************* * This example converts the wide character c to a character. * ************************************************************************/ #include #include #define SIZE 40 int main(void) { static char buffer[ SIZE ]; wchar_t wch = L'c'; int length; length = wctomb( buffer, wch ); printf( "The number of bytes that comprise the multibyte " "character is %i\n", length ); printf( "And the converted string is \"%s\"\n", buffer ); } /************************************************************************ * /**************** Output should be similar to: ****************** The number of bytes that comprise the multibyte character is 1 And the converted string is "c" */ * ************************************************************************/ ═══ Related Information ═══ o mbtowc - Convert Multibyte Character to wchar_t o wcslen - Calculate Length of wchar_t String o wcstombs - Convert wchar_t String to Multibyte Character String o stdlib.h ═══ 6.287. _write - Writes from Buffer to File ═══ ═══ Format ═══ #include int _write(int handle, const void *buffer, unsigned int count); ═══ Description ═══ Language Level: Extension The _write function writes count bytes from buffer into the file associated with handle. The write operation begins at the current position of the file pointer associated with the given file. If the file is open for appending, the operation begins at the end of the file. After the write operation, the file pointer is increased by the number of bytes actually written. If the given file was opened in text mode, each line feed character is replaced with a carriage return/line feed pair in the output. The replacement does not affect the return value. The _write function returns the number of bytes moved from the buffer to the file. The return value may be positive but less than count. A return value of -1 indicates an error, and errno is set to one of the following values: Value Meaning EBADF The file handle is not valid, or the file is not open for writing. ENOSPC No space is left on the device. EOS2ERR The call to the operating system was not successful. Example of _write ═══ Example of _write ═══ /************************************************************************ * This example writes the contents of the character array buffer to the output file whose handle is fh. * ************************************************************************/ #include #include #include #include #include int main(void) { int fh; char buffer[20]; memset(buffer,'a',20); /* initialize storage */ printf("\nCreating sample.dat.\n"); system("echo Sample Program > sample.dat"); if (-1 == (fh = _open("sample.dat",O_RDWR | O_APPEND))) { perror("Unable to open sample.dat"); return 1; } if (5 != _write(fh,buffer,5) ) { perror("Unable to write to sample.dat"); _close(fh); return 1; } printf("Successfully appended 5 characters.\n"); _close(fh); return 0; /****************** The expected output is: *************************** Creating sample.dat. Successfully appended 5 characters. */ } ═══ Related Information ═══ o _creat - Create New File o fread - Read Items o fwrite - Write Items o _lseek - Move File Pointer o _open - Open File o _read - Read Into Buffer o _sopen - Open Shared File o _tell - Get Pointer Position o io.h ═══ 7. Include Files ═══ The include files provided with the runtime library contain macro and constant definitions, type definitions, and function declarations. Some functions require definitions and declarations from include files to work properly. The inclusion of files is optional, as long as the necessary statements from the files are coded directly into the source. Note: If the /Ms compiler option (use _System linkage) is specified, you must include the appropriate header files with the declarations of the library functions that you use. This section describes the following include files, explains their contents, and lists the functions that use the files. o assert.h o builtin.h o conio.h o ctype.h o direct.h o errno.h o fcntl.h o float.h o io.h o limits.h o locale.h o malloc.h o math.h o memory.h o process.h o search.h o setjmp.h o share.h o signal.h o stdarg.h o stddef.h o stdio.h o stdlib.h o string.h o sys\stat.h o sys\timeb.h o sys\types.h o sys\utime.h o time.h o wcstr.h ═══ Related Information ═══ o #include ═══ 7.1. assert.h ═══ The assert.h include file defines the assert macro. You must include assert.h when you use assert. The definition of assert is in an #ifndef preprocessor block. If you have not defined the identifier NDEBUG through a #define directive or on the compiler command line, the assert macro tests a given expression (the assertion). If the assertion is false, the system prints a message to stderr and an abort signal is raised for the program. If NDEBUG is defined, assert is defined to do nothing. You can suppress program assertions by defining NDEBUG. ═══ Related Information ═══ o #define o #ifndef o Include Files o #include ═══ 7.2. builtin.h ═══ The builtin.h include file contains function declarations for the following built-in functions: _alloca _disable _enable _facos _fasin _fcos _fcossin _fpatan _fptan _fsin _fsincos _fyl2x _fyl2xp1 _f2xm1 _getTIBvalue _inp _inpd _inpw _interrupt _outp _outpd _outpw __parmdwords The builtin.h file also includes declaration for the following intrinsic functions: _clear87 _control87 _status87 The functions _clear87, _control87, and _status87 are also defined in float.h. The function _alloca is also defined in stdlib.h and malloc.h. The functions _inp, _inpd, _inpw, _outp, _outpd, and _outpw are also defined in conio.h. The builtin.h file also includes a declaration for the type size_t, which is also defined in stddef.h. ═══ Related Information ═══ o Intrinsic Functions o Include Files o #include ═══ 7.3. conio.h ═══ The conio.h include file contains definitions for the functions that involve screen and console input and output: _cgets _cprintf _cputs _cscanf _getch _getche _inp _inpd _inpw _kbhit _outp _outpd _outpw _putch _ungetch ═══ Related Information ═══ o io.h o stdio.h o Include Files o #include ═══ 7.4. ctype.h ═══ The ctype.h include file defines functions used in character classification. The functions defined in ctype.h are: isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit &tolower. &toupper. In extended mode, the ctype.h file also includes definitions for the following C/C++Tools extensions: _isascii _iscsym _iscsymf _toascii _tolower _toupper In the C/C++ Tools compiler, the ctype.h functions are all implemented as macros. ═══ Related Information ═══ o Include Files o #include ═══ 7.5. direct.h ═══ The direct.h include file contains definitions for functions that control directories and drives. The functions defined in direct.h are: _chdir _chdrive _getcwd _getdcwd _getdrive _mkdir _rmdir ═══ Related Information ═══ o Include Files o #include ═══ 7.6. errno.h ═══ The errno.h include file defines the macros EDOM and ERANGE, and a modifiable lvalue having type int called errno. It also defines the global variable _doserrno, which is determined by the OS/2 error code when an operating system error occurs. See Runtime Return Codes and Messages for a list of the runtime error messages and the errno values associated with each message. Note: If you are going to test the value of errno after library function calls, first set it to 0, because its value may not be reset during the call. The definitions of errno and _doserrno are also provided in stdlib.h. ═══ Related Information ═══ o Runtime Return Codes and Messages o stdlib.h o Include Files o #include ═══ 7.7. fcntl.h ═══ The fcntl.h contains definitions for constants used by the _open and _sopen functions. Definitions for these two functions are included in io.h. Additional definitions for _sopen are provided in share.h. ═══ Related Information ═══ o io.h o share.h o Include Files o #include ═══ 7.8. float.h ═══ The float.h include file contains definitions of constants that specify the ranges of floating-point data types, for example, the maximum number of digits for objects of type double or the minimum exponent for objects of type float. In extended mode, float.h also defines the macros that represent infinity and NaN (not-a-number) values, and contains the definitions for the following functions that manipulate the floating-point control and status words, and for the constants that they use: _clear87 _control87 _fpreset _status87 ═══ Related Information ═══ o Infinity and NaN Support o Floating-Point Variables o Include Files o #include ═══ 7.9. io.h ═══ The io.h include file contains definitions for the following file handle and low-level input and output functions: _access _chmod _chsize _close _creat _dup _dup2 __eof _filelength _isatty _lseek _open _read remove rename _setmode _sopen _tell _umask _unlink _write Two additional functions, _fstat and _stat, are defined in sys\stat. Constants required by the _open and _sopen functions are provided in fcntl.h. Additional constants used by _sopen are defined in share.h. The _unlink function is also defined in stdio.h. ═══ Related Information ═══ o fcntl.h o share.h o sys\stat.h o stdlib.h o conio.h o stdio.h o Include Files o #include ═══ 7.10. limits.h ═══ The limits.h include file contains definitions of constants that specify the ranges of integer and character data types, such as the maximum value for an object of type char. ═══ Related Information ═══ o Characters o Integers o Include Files o #include ═══ 7.11. locale.h ═══ The locale.h include file contains declarations for the setlocale and localeconv library functions. These functions are useful for changing the C locale when you are creating applications for international markets. locale.h also contains the declaration for the type struct lconv and the following macro definitions: NULL LC_ALL LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME LC_C_TOD LC_C LC_C_FRANCE LC_C_GERMANY LC_C_ITALY LC_C_JAPAN LC_C_SPAIN LC_C_UK LC_C_USA NULL is also defined in stddef.h on page stddef.h, stdio.h on page stdio.h, stdlib.h on page stdlib.h, string.h on page string.h, time.h on page time.h, and wcstr.h on page wcstr.h. ═══ Related Information ═══ o Include Files o #include ═══ 7.12. malloc.h ═══ The malloc.h include file contains definitions for the following memory allocation functions: _alloca calloc _debug_calloc _debug_free _debug_malloc _debug_heapmin _debug_realloc _dump_allocated free _heap_check malloc &mszize. realloc It also includes a definition for the type size_t. The SAA definitions of calloc, free, malloc, and realloc are provided in stdlib.h, as are _alloca and _heapmin. The _debug_calloc, _debug_free, _debug_malloc, _debug_heapmin, _debug_realloc, _dump_allocated, and _heap_check functions are also defined as standard extensions in stdlib.h. Note: To use these functions, you must also define the __DEBUG_ALLOC__ macro. See Debug Memory Management Functions for more information about these functions. The _tcalloc, _tfree, _tmalloc, _trealloc functions are also defined as standard extensions in stdlib.h. Note: 1. To use these functions, you must also define the __TILED__ macro. See Tiled Memory Management Functions for more information about these functions. 2. If you define __DEBUG_ALLOC__ and __TILED__ at the same time, the tiled memory functions are provided, and the debug memory features are disabled. The malloc.h include file also defines a number of far and near pointer macros to the corresponding SAA or standard library function. These macros are: _fcalloc _ffree _fheapmin _fmalloc _frealloc _ncalloc _nfree _nheapmin _nmalloc _nrealloc These macros are also defined in stdlib.h. ═══ Related Information ═══ o stdlib.h o Include Files o #include ═══ 7.13. math.h ═══ The math.h include file contains function declarations for all the floating-point math functions: acos asin atan atan2 bessel ceil cos cosh erf erfc exp fabs floor fmod frexp gamma hypot ldexp log log10 modf pow sin sinh sqrt tan tanh Note: bessel does not correspond to a single function but to the functions named _j0, _j1, _jn, _y0, _y1, and _yn. The math.h file also includes definitions for the following C/C++ Tools extensions: ┌─────────────────────────┬──────────────────────────┬─────────────────────────┐ │ _atold │ _cabs │ _matherr │ └─────────────────────────┴──────────────────────────┴─────────────────────────┘ The _atold function is also defined in stdlib.h. The math.h include file defines the macros HUGE, _LHUGE, HUGE_VAL, and _LHUGE_VAL, which expand to a positive double expression or to infinity. You can define a macro _FP_INLINE to inline the functions sin, cos, tan, atan, acos and asin. If you use _FP_INLINE to inline the functions, you cannot use the functions defined in complex.h, or an error message is generated. For all mathematical functions, a domain error occurs when an input argument is outside the range of values allowed for that function. In the event of a domain error, errno is set to the value of EDOM. A range error occurs if the result of the function cannot be represented in a double value. If the magnitude of the result is too large (overflow), the function returns the positive or negative value of the macro HUGE_VAL, and sets errno to ERANGE. If the result is too small (underflow), the function returns zero. ═══ Related Information ═══ o stdlib.h o Include Files o #include ═══ 7.14. memory.h ═══ The memory.h include file contains definitions for the following buffer manipulation functions: memccpy memchr memcmp memcpy memicmp memmove memset The SAA definitions of these functions are provided in string.h. The memory.h include file also defines a number of far and near pointer macros to the corresponding SAA or standard library function. These macros are: _fmemccpy _fmemchr _fmemcmp _fmemcpy _fmemicmp _fmemset These macros are also defined in string.h. ═══ Related Information ═══ o string.h o Include Files o #include ═══ 7.15. process.h ═══ The process.h include file contains definitions for the process control functions: abort _beginthread _cwait _endthread _execl _execle _execlp _execlpe _execv _execve _execvp _execvpe exit _exit _getpid _spawnl _spawnle _spawnlp _spawnlpe _spawnv _spawnve _spawnvp _spawnvpe system _wait The definitions of _beginthread and _endthread are also provided in stdlib.h, as are SAA definitions of abort, exit, and system. ═══ Related Information ═══ o stdlib.h o Include Files o #include ═══ 7.16. search.h ═══ The search.h include file contains the definitions for the following search functions: bsearch _lfind _lsearch qsort It also defines the type size_t. The SAA definitions for bsearch and qsort are provided in stdlib.h. ═══ Related Information ═══ o stdlib.h o Include Files o #include ═══ 7.17. setjmp.h ═══ The setjmp.h include file contains function declarations for the setjmp macro and longjmp function. It also defines a buffer type, jmp_buf, that the setjmp macro and longjmp function use to save and restore the program state. ═══ Related Information ═══ o Include Files o #include ═══ 7.18. share.h ═══ The share.h include file defines constants used by the following functions: _creat _fdopen _open _sopen The definitions for the above functions are included in io.h. Additional constants for _open and _sopen are provided in fcntl.h. ═══ Related Information ═══ o fcntl.h o io.h o Include Files o #include ═══ 7.19. signal.h ═══ The signal.h include file defines the values for signals. The signal and raise functions are declared in signal.h. signal.h also defines the following macros: SIG_DFL SIGILL SIG_ERR SIGINT SIG_IGN SIGSEGV SIGABRT SIGTERM SIGFPE SIGUSR1 SIGUSR2 SIGUSR3 signal.h also defines the type sig_atomic_t. ═══ Related Information ═══ o Include Files o #include ═══ 7.20. stdarg.h ═══ The stdarg.h include file defines macros that allow you access to arguments in functions with variable-length argument lists. The macros are: va_arg, va_start, and va_end. stdarg.h also defines the type va_list. ═══ Related Information ═══ o Include Files o #include ═══ 7.21. stddef.h ═══ The stddef.h include file contains definitions of the commonly used pointers, variables, and types, from typedef statements, as listed below: ptrdiff_t typedef for the type of the difference of two pointers size_t typedef for the type of the value returned by sizeof wchar_t typedef for a wide character constant. stddef.h also defines the macros NULL and offsetof. NULL is a pointer that is guaranteed not to point to a data object. NULL is also defined in locale.h. The offsetof macro expands to the number of bytes between a structure member and the start of the structure. The offsetof macro has the form: offsetof(structure_type, member) stddef.h also contains definitions of the global variables errno and _threadid. The extended definition of errno is also included in stdlib.h, while the SAA version is in errno.h. ═══ Related Information ═══ o errno.h o stdlib.h o stdio.h o Include Files o #include ═══ 7.22. stdio.h ═══ The stdio.h include file contains definitions of constants, macros, and types, along with function declarations for stream input and output functions. The stream I/O functions are: clearerr fclose feof ferror fflush fgetc fgetpos fgets fopen fprintf fputc fputs fread freopen fscanf fseek fsetpos ftell fwrite getc getchar gets perror printf putc putchar puts remove rename rewind scanf setbuf setvbuf sprintf sscanf tmpfile tmpnam ungetc vfprintf vprintf vsprintf In extended mode, stdio.h also contains definitions for the following extensions: _fcloseall _fgetchar _fileno _flushall _fputchar _rmtmp _set_crt_msg_handle _tempnam _unlink The _unlink function is also defined in io.h. The stdio.h file also defines the macros listed below. You can use these constants in your programs, but you should not alter their values. BUFSIZ Specifies the buffer size to be used by the setbuf library function when you are allocating buffers for stream I/O. This value establishes the size of system-allocated buffers and is used with setbuf. EOF The value returned by an I/O function when the end of the file (or in some cases, an error) is found. FOPEN_MAX The number of files that can be opened simultaneously. FILENAME_MAX The longest file name supported. If there is no reasonable limit, FILENAME_MAX will be the recommended size. L_tmpnam The size of the longest temporary name that can be generated by the tmpnam function. P_tmpdir Indicates the default directory to be used by the tempnam function. TMP_MAX The minimum number of unique file names that can be generated by the tmpnam function. NULL A pointer guaranteed not to point to a data object. NULL is also defined in locale.h. The FILE structure type is defined in stdio.h. Stream I/O functions use a pointer to the FILE type to get access to a given stream. The system uses the information in the FILE structure to maintain the stream. The C standard streams stdin, stdout, and stderr are also defined in stdio.h. The macros SEEK_CUR, SEEK_END, and SEEK_SET expand to integral constant expressions and can be used as the third argument to fseek. The macros _IOFBF, _IOLBF, and _IONBF expand to integral constant expressions with distinct values suitable for use as the third argument to the setvbuf function. The type fpos_t is defined in stdio.h for use with fgetpos and fsetpos. ═══ Related Information ═══ o stddef.h o stdlib.h o conio.h o io.h o Include Files o #include ═══ 7.23. stdlib.h ═══ The stdlib.h include file contains function declarations for the following functions: abort abs atexit atof atoi atol bsearch calloc div exit free getenv labs ldiv malloc mblen mbstowcs mbtowc qsort rand realloc srand strtod strtol strtoul system wctomb wcstombs In extended mode, stdlib.h also contains definitions for the following standard extensions: _alloca _atold _beginthread _debug_calloc _debug_free _debug_heapmin _debug_malloc _debug_realloc _dump_allocated _ecvt _endthread _exit _fcvt _freemod _fullpath _gcvt _heapmin _heap_check _itoa _loadmod _lrotl _lrotr _ltoa _makepath max min _onexit __parmdwords _putenv _rotl _rotr _searchenv _splitpath strtold _swab _threadstore _ultoa Note: 1. Note that you must also define the __DEBUG_ALLOC__ macro to use the _debug_calloc, _debug_free, _debug_malloc, _debug_realloc, _dump_allocated, _debug_heapmin, and _heap_check functions. For more information about these functions, see Debug Memory Management Functions. 2. If you define __DEBUG_ALLOC__ and __TILED__ at the same time, the tiled memory functions are provided, and the debug memory features are disabled. The stdlib.h file also contains definitions for the following macros: split=yes. NULL The NULL pointer value. The value of NULL is 0 when in extended mode; otherwise, its value is ((void*)0). NULL is also defined in locale.h. EXIT_SUCCESS Expands to 0; used by the atexit function. EXIT_FAILURE Expands to 8; used by the atexit function. RAND_MAX Expands to an integer representing the largest number that the RAND function can return. MB_CUR_MAX Expands to an integer representing the maximum number of bytes in a multibyte character for the current locale. For more information on NULL and the types size_t and wchar_t, see stddef.h. In extended mode, stdlib.h also defines the following global variables: _doserrno _environ errno onexit_t _osmajor _osminor _osmode The variable errno is also defined in stddef.h. The variable _doserrno and the SAA definition of errno are provided in errno.h. In addition, stdlib.h defines the following far and near pointer macros to the corresponding standard library function: _fcalloc _ffree _fmalloc _fheapmin _frealloc _ncalloc _nfree _nmalloc _nheapmin _nrealloc These macros are also defined in malloc.h. ═══ Related Information ═══ o errno.h o malloc.h o stddef.h o stdio.h o Include Files o #include ═══ 7.24. string.h ═══ The string.h include file declares the string manipulation functions: memchr memcmp memcpy memmove memset strcat strchr strcmp strcoll strcpy strcspn strerror strlen strncat strncmp strncpy strpbrk strrchr strspn strstr strtok strxfrm In extended mode, string.h also contains definitions for the following standard extensions: memccpy memicmp strcmpi strdup _strerror stricmp strlwr strnicmp strnset strrev strset strupr The memxxxx functions are also included in memory.h. The string.h include file also defines the macro NULL and the type size_t. These definitions are also provided in stddef.h. NULL is also defined in locale.h. string.h also defines the following far and near pointer macros to the corresponding standard library function: _fmemccpy _fmemchr _fmemcmp _fmemcpy _fmemicmp _fmemmove _fmemset _fstrcat _fstrchr _fstrcmp _fstrcpy _fstrcspn _fstrdup _fstricmp _fstrlen _fstrlwr _fstrncat _fstrncmp _fstrncpy _fstrnicmp _fstrnset _fstrpbrk _fstrrchr _fstrrev _fstrset _fstrspn _fstrstr _fstrtok _fstrupr _nstrdup These macros are also defined in memory.h. ═══ Related Information ═══ o stddef.h o memory.h o stdlib.h o stdio.h o Include Files o #include ═══ 7.25. sys\stat.h ═══ The sys\stat.h include file contains the definitions for the low-level input/output functions _fstat and _stat. It also defines the structure stat and the following types: dev_t ino_t off_t time_t These types are also defined in sys\types.h. Other low-level I/O functions are defined in io.h. ═══ Related Information ═══ o io.h o sys\types.h o Include Files o #include ═══ 7.26. sys\timeb.h ═══ The sys\timeb.h include file contains the definition for the _ftime function and also defines the type time_t and the structure timeb. ═══ Related Information ═══ o Include Files o #include ═══ 7.27. sys\types.h ═══ The sys\types.h include file contains the definitions for the following types: ino_t time_t dev_t off_t These types are also defined in sys\stat.h. ═══ Related Information ═══ o sys\stat.h o Include Files o #include ═══ 7.28. sys\utime.h ═══ The sys\utime.h include file contains the definitions for the _utime function, the structure utimbuf, and the type time_t. ═══ Related Information ═══ o Include Files o #include ═══ 7.29. time.h ═══ The time.h include file declares the time and date functions: asctime clock ctime difftime gmtime localtime mktime strftime time In extended mode, time.h also includes the definition for the standard extensions _strdate, _strtime, and _tzset. The time.h include file also provides: o A structure tm containing the components of a calendar time. See gmtime - Convert Time for a list of the members of the tm structure. o A macro CLOCKS_PER_SEC equal to the number per second of the value returned by the clock function. o Types clock_t, time_t, and size_t. o The NULL pointer value. For more information on NULL and the type size_t, see stddef.h. time.h also defines the global variables _daylight, _timezone, and _tzname. ═══ Related Information ═══ o stddef.h o Include Files o #include ═══ 7.30. wcstr.h ═══ The wcstr.h include file declares the multibyte functions: wcscat wcschr wcscmp wcscpy wcscspn wcslen wcsncat wcsncmp wcsncpy wcspbrk wcsspn wcsrchr wcswcs wcstr.h also defines the types size_t, NULL, and wchar_t. ═══ Related Information ═══ o Include Files o #include