═══ 1. About this Reference ═══ The VisualAge C++ C Library Reference describes the the VisualAge C++ implementation of the C runtime library. Use it to find information about what the different library functions do and how to declare and use them. This reference also provides code examples that you can copy to a file and paste into your own applications. This document is a reference rather than a tutorial. It assumes you are already familiar with C and C++ programming concepts. Information applies to the C language, but you can also call the functions and macros from C++ applications. For a list of other information that you might also find helpful, see Other Information You Might Find Helpful. Before you begin to use this information, it would be helpful to understand how to navigate through it. You can use the Table of Contents and Index facility to locate topics and the Search facility to search the text of this document. You can use hypertext links to acquire related information on the current topic. Hypertext links appear in a different color (which you can customize using the OS/2 Scheme Palette). For example, here is a link to another panel: Communicating Your Comments to IBM. By double-clicking on the text of the link or by pressing Enter on a highlighted link, you will open a panel of related information. When you open a panel, the first link has the focus; to shift the focus to other links, use the Tab key. You should also understand:  How to Use the Contents  How to Obtain Additional Information  How to Use Action Bar Choices  How to Cut and Paste Examples The following highlighting conventions are used in this reference: Bold Identifies commands and language keywords. Italics Identify parameters whose actual names or or values are to be supplied by the programmer. Example Identifies function names, examples of specific data values, examples of text similar to what you might see displayed, examples of portions of program code, messages from the system, or information that you should actually type. ═══ 1.1. Notices ═══ Copyright International Business Machines Corporation, 1992, 1995. 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. Third Edition, May 1995. This edition applies to Version 3.0 of IBM VisualAge C++ for OS/2 (30H1664, 30H1665, 30H1666) and to all subsequent releases and modifications until otherwise indicated in new editions. Make sure you are using the correct edition for the level of the product. 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. Any reference to an IBM licensed program in this publication is not intended to state or imply that only IBM's licensed program 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, except those expressly designated by IBM, is 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 Licensing, IBM Corporation, 500 Columbus Avenue, Thornwood, NY, 10594, USA. This publication contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental. ═══ 1.2. Programming Interface Information ═══ This book is intended to help you create programs using VisualAge C++ product. It primarily documents General-Use Programming Interface and Associated Guidance Information provided by VisualAge C++ product. General-Use programming interfaces allow the customer to write programs that obtain the services of VisualAge C++ compiler and debugger. However, this book also documents Diagnosis, Modification, and Tuning Information. Diagnosis, Modification, and Tuning Information is provided to help you debug your programs. Warning: Do not use this Diagnosis, Modification, and Tuning Information as a programming interface because it is subject to change. Diagnosis, Modification, and Tuning Information is identified where it occurs by an introductory statement to a chapter or section. ═══ 1.3. Trademarks and Service Marks ═══ The following terms used in this publication are trademarks or service marks of IBM Corporation in the United States or other countries: AIX BookManager C/2 C Set/2 C Set ++ IBM IBMLink Library Reader Operating System/2 OS/2 Personal System/2 Presentation Manager PS/2 PROFS SAA Systems Application Architecture VisualAge WorkFrame/2 Workplace Shell Other company, product, and service names, which may be denoted by a double asterisk (**), may be trademarks or service marks of others. ═══ 1.4. 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, How to Use the Contents 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). ═══ 1.5. 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. Certain words and phrases are highlighted in a different color from the surrounding text. 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. ═══ 1.6. How to Use Action Bar Choices ═══ Several choices are available for managing the information presented in this document. There are three 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: Placing Bookmarks You can set a placeholder so you can retrieve information of interest to you. Searching for Information You can find occurrences of a word or phrase in the current topic, selected topics, or all topics. Printing Information You can print one or more topics. You can also print a set of topics by first marking the topics in the Contents list. Copying Information to a File You can copy a topic that you are viewing to the System Clipboard or to a file that you can edit. This method is particularly useful for copying syntax definitions and program samples into the application that you are developing. Using the actions that are selectable from the Options menu, you can 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. The actions that are selectable from the Help menu allow you to select different types of help information. For information about any of the pull-down menu choices, highlight the choice in the menu and press F1. ═══ 1.6.1. Placing Bookmarks ═══ 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 menu. 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. ═══ 1.6.2. Searching for Information ═══ 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 menu. 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. ═══ 1.6.3. Printing Information ═══ You can print one or more topics, the index, or the table of contents. Make sure that your printer is connected to the serial port, configured correctly, and ready for input. To print: 1. Choose Print from the Services menu. 2. Select what you want to print. Note that the This section and Marked sections choices are only available if you are viewing a topic or if you have marked topics, respectively. To mark topics in the table of contents, press the Ctrl key and click on the topics, or use the arrow keys. 3. Select Print to print what you've chosen on your printer. ═══ 1.6.4. Copying Information to a File ═══ You can copy a topic that you are viewing in two ways:  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.  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 menu. 3. The system puts the text pertaining to that topic into the temporary file TEXT.TMP. ═══ 1.7. How to Cut and Paste Examples ═══ You can copy examples (or information) from this reference to compile, link, and run them, or to paste them into your own code. To copy an example or information: 1. Make the topic you want to copy the active window. 2. From the Services menu, select Copy to file. The text in that topic is placed in the temporary file TEXT.TMP, in the same directory as this reference. 3. You can then modify or use TEXT.TMP as you want. Note: Because the system copies the entire contents of the topic to the file, you may need to edit it to remove additional text. Most examples in this reference are ready to compile, link, and run as they appear, and do not require any editing. ═══ 1.8. Other Information You Might Find Helpful ═══ This product provides a number of online guides and references that we hope you'll find helpful as you develop applications. This information includes User's Guides, References, and How Do I help that gives you specific instructions for performing common tasks. You can get to this online information from the Information folder inside the main product folder. You can also get to it from the Help menu in any of the components of the product. You may want to use the following books with this Library Reference: Programming Guide Describes different programming and coding techniques. C/C++ Language Reference Describes the VisualAge C++ implementation of the C and C++ languages. Control Programming Guide and Reference Describes the OS/2 Dos APIs and how to use them. Presentation Manager Programming Guide and Reference Describes the PM APIs and how to use them. Graphics Programming Guide and Reference Describes the graphics APIs and how to use them. ═══ 1.9. Communicating Your Comments to IBM ═══ If there is something you like, or dislike, about this book, please let us know. You can use one of the methods listed below to send your comments to IBM. Please be sure to include the complete title of the publication that you are commenting on. The comments you send should only pertain to the information in this document and its presentation. To request additional publications or to ask questions or make comments about the functions of IBM products or systems, you should talk to your IBM representative or you authorized IBM remarketer. When you send comments to IBM, you grant IBM a nonexclusive right to use or distribute your comments in any way it believes appropriate without incurring any obligation to you. You can send your comments to IBM in the following ways:  By mail to the following address: IBM Canada Ltd. Laboratory Information Development 2G/345/1150/TOR 1150 EGLINTON AVENUE EAST NORTH YORK, ONTARIO CANADA M3C 1H7  By FAX to the following number: - United States and Canada: (416) 448-6161 - Other countries (+1) 416-448-6161  By electronic mail to one of the following IDs. Be sure to include your entire network address if you wish to get a reply. - Internet: torrcf@vnet.ibm.com - IBMLink: toribm(torrcf) - IBM/PROFS: torolab4(torrcf) - IBMMAIL: ibmmail(caibmwt9 ═══ 1.10. Changes to the C Library and this Document ═══ This section describes the changes made to the C runtime library for VisualAge C++ Version 3.0, and to this book, S25H-6964, from the previous version, S61G-1183. Changes to the C Library  The runtime library now supports locales and internationalization based on the IEEE POSIX P1003.2 and X/Open Portability Guide standards for global locales and coded character sets.  To support locales, including wide character sets, new functions, header files, and environment variables have been added. The functions include a number of multibyte functions defined in the 1993 proposed amendment to the ANSI/ISO C standard.  The memory management support has been completely redesigned to improve flexibility and performance. Enhancements include: - Functions for creating and using your own memory heaps. - Additional heap-checking functions. - Support for shared memory heaps. - A new environment variable, DDE4_HEAP_SKIP, that you can use to determine how often the heap is checked by debug memory management functions. - Debug versions of the tiled memory management functions. - Significantly reduced overhead per allocation from previous releases. Note: The new memory management design could surface memory problems in your applications that the previous version of C Set ++ did not catch. If exceptions or problems occur that did not occur with earlier versions: 1. Rebuild your application to generate debug information and enable memory debugging (/Ti /Tm compiler options). 2. Run your application and redirect stderr to a file (the memory debug messages are sent to stderr by default). 3. Use the memory debug messages (and the debugger) to correct your memory problem. Common problems are freeing an object twice, freeing an invalid object, writing to a freed object, or overwriting an allocated object beyond its requested size. You can simplify your debugging by using the debugger and setting appropriate breakpoints when the object is allocated, freed, or written to. You can also set a breakpoint on abort, which is called when a memory problem is detected. The Debugger also has a new feature you can use to automatically check all the memory heaps in your application each time your application stops running (for example, hits a breakpoint). See the User's Guide for more information about the Debugger.  Some VisualAge C++ extensions no longer begin with an underscore for compatibility with the X/Open standard: ┌───────────────────┬───────────────────┬───────────────────┬──────────────────┐ │ access │ execlp │ isatty │ stat │ │ chdir │ execv │ lfind │ swab │ │ chmod │ execve │ lsearch │ tempnam │ │ close │ execvp │ lseek │ tzset │ │ creat │ fdopen │ mkdir │ umask │ │ dup │ fileno │ open │ unlink │ │ dup2 │ fstat │ putenv │ utime │ │ execl │ getpid │ read │ wait │ │ execle │ isascii │ rmdir │ write │ └───────────────────┴───────────────────┴───────────────────┴──────────────────┘ To ensure compatibility with previous C Set ++ releases, VisualAge C++ maps the underscored name to the appropriate function name for you (for example, _access to access).  Functions to enable fast RAM semaphores have been added (__cxchg, __lxchg, and __sxchg).  The printf family of functions now prints (null) if you specify a null string for the %s or %ls format specifier. In previous releases, the printf functions produced no output for a null string.  The names of the runtime library files have changed. The new naming convention is: CPPpivvt where: p Is the platform or operating system. i Is the library identifier. vv Is the version number. t Is the type of library The resulting library names are: ┌──────┬──────┬──────┬──────┬──────┬───────────────────────────────────────────┐ │ CHARA│TPOSIT│ON │ │ │ SIGNIFICANCE │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ 1-3 │ 4 │ 5 │ 6-7 │ 8 │ │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ CPP │ │ │ │ │ Product prefix │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ O │ │ │ │ OS/2 platform │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ S │ │ │ Single-thread environment │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ M │ │ │ Multithread environment │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ N │ │ │ No runtime environment (subsystem) │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ │ 30 │ │ Version number 3.0 │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ │ │ I │ Import library │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ │ │ O │ Object library (contains initialization │ │ │ │ │ │ │ routines) │ ├──────┼──────┼──────┼──────┼──────┼───────────────────────────────────────────┤ │ │ │ │ │ │ Statically bound library (no eighth │ │ │ │ │ │ │ letter) │ └──────┴──────┴──────┴──────┴──────┴───────────────────────────────────────────┘ Changes to this Publication  The section on memory management functions has been expanded.  Information has been added for all new functions.  Information has been added for the DLL initialization and termination functions.  The order of chapters has been revised.  Minor technical and editorial changes have been made. ═══ 2. The C Library ═══ This section summarizes the available C library functions. It also briefly describes what the function does. Each library function is listed according to the type of function it performs.  Error Handling  Process Control  File and Directory Management  Searching and Sorting  Regular Expressions  Mathematical  Fast RAM Semaphores  Floating-Point Unit Control  Date, Time, and Monetary Manipulation  Type Conversion  Stream Input/Output  Low-Level Input/Output  Handling Argument Lists  Pseudorandom Numbers  Dynamic Memory Management  Memory Objects  Environment and Locale Interaction  String Operations  Character Testing  Case Mapping  Multibyte Character Manipulation ═══ 2.1. Error Handling Functions ═══  assert - Verify Condition  atexit - Record Program Termination Function  clearerr - Reset Error Indicators.  ferror - Test for Read/Write Errors  _matherr - Process Math Library Errors  perror - Print Error Message  raise - Send Signal  _set_crt_msg_handle - Change Runtime Message Output Destination  signal - Handle Interrupt Signals  strerror - Set Pointer to Runtime Error Message  _strerror - Set Pointer to System Error String ═══ 2.2. Process Control Functions ═══  _beginthread - Create New Thread  _cwait - Wait for Child Process  _disable - Disable Interrupts  _enable - Enable Interrupts  _endthread - Terminate Current Thread  execl - _execvpe - Load and Run Child Process  _exit - End Process  _freemod - Free User DLL  getpid - Get Process Identifier  _getTIBvalue - Get Thread Information Block Value  _interrupt - Call Interrupt Procedure  _loadmod - Load DLL  _onexit - Record Termination Function  putenv - Modify Environment Variables  _searchenv - Search for File  _spawnl - _spawnvpe - Start and Run Child Processes  _threadstore - Access Thread-Specific Storage ═══ 2.3. File and Directory Management Functions ═══  chdir - Change Current Working Directory  _chdrive - Change Current Working Drive  fstat - Information about Open File  _fullpath - Get Full Path Name of Partial Path  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  _getdrive - Get Current Working Drive  _makepath - Create Path  mkdir - Create New Directory  rmdir - Remove Directory  _splitpath - Decompose Path Name  stat - Get Information about File or Directory ═══ 2.4. Searching and Sorting Functions ═══  bsearch - Search Arrays  lfind - lsearch - Find Key in Array  lfind - lsearch - Find Key in Array  qsort - Sort Array ═══ 2.5. Regular Expression Functions ═══  regcomp - Compile Regular Expression  regerror - Return Error Message for Regular Expression  regexec - Execute Compiled Regular Expression  regfree - Free Memory for Regular Expression ═══ 2.6. Mathematical Functions ═══  abs - Calculate Integer Absolute Value  _cabs - Calculate Absolute Value of Complex Number  ceil - Find Integer >= Argument  div - Calculate Quotient and Remainder  erf - erfc - Calculate Error Functions  exp - Calculate Exponential Function  fabs - Calculate Floating-Point Absolute Value  floor - Integer <= Argument  fmod - Calculate Floating-Point Remainder  frexp - Separate Floating-Point Value  _fsqrt - Calculate Square Root  _fyl2x - Calculate y * log2(x)  _fyl2xp1 - Calculate y * log2(x + 1)  _f2xm1 - Calculate (2**x) - 1  gamma - Gamma Function  hypot - Calculate Hypotenuse  labs - Calculate Absolute Value of Long Integer  ldexp - Multiply by a Power of Two  ldiv - Perform Long Division  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  max - Return Larger of Two Values  min - Return Lesser of Two Values  modf - Separate Floating-Point Value  pow - Compute Power  sqrt - Calculate Square Root  Bessel Functions - Solve Differential Equations Trigonometric Functions  acos - Calculate Arccosine  asin - Calculate Arcsine  atan - atan2 - Calculate Arctangent  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fasin - Calculate Arcsine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fpatan - Calculate Arctangent  _fptan - Calculate Tangent  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent Bit Rotation  _crotl - _crotr - Rotate Bits of Character Value  _lrotl - _lrotr - Rotate Bits of Unsigned Long Value  _rotl - _rotr - Rotate Bits of Unsigned Integer  _srotl - _srotr - Rotate Bits of Unsigned Short Value ═══ 2.7. Fast RAM Semaphore Functions ═══  __cxchg - Exchange Character Value with Memory  __lxchg - Exchange Integer Value with Memory  __sxchg - Exchange Integer Value with Memory ═══ 2.8. Floating-Point Unit Control Functions ═══  _clear87 - Clear Floating-Point Status Word  _control87 - Set Floating-Point Control Word  _fpreset - Reset Floating-Point Unit  _status87 - Get Floating-Point Status Word ═══ 2.9. Date, Time, and Monetary Manipulation Functions ═══  asctime - Convert Time to Character String  clock - Determine Processor Time  ctime - Convert Time to Character String  difftime - Compute Time Difference  _ftime - Store Current Time  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  _strdate - Copy Current Date  strfmon - Convert Monetary Value to String  strftime - Convert to Formatted Time  strptime - Convert to Formatted Date and Time  _strtime - Copy Time  time - Determine Current Time  tzset - Assign Values to Locale Information  utime - Set Modification Time  wcsftime - Convert to Formatted Date and Time ═══ 2.10. Type Conversion Functions ═══  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  _itoa - Convert Integer to String  _ltoa - Convert Long Integer to String  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  strtoul - Convert String Segment to Unsigned Integer  _ultoa - Convert Unsigned Long Integer to String  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  wctob - Convert Wide Character to Byte Multibyte and Wide-Character Type Conversion  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  mbstowcs - Convert Multibyte String to Wide-Character String  mbtowc - Convert Multibyte Character to Wide Character  wcrtomb - Convert Wide Character to Multibyte Character  wcsrtombs - Convert Wide-Character String to Multibyte String  wcstombs - Convert Wide-Character String to Multibyte String  wctomb - Convert Wide Character to Multibyte Character ═══ 2.11. Stream Input/Output Functions ═══ Formatted Input/Output  fprintf - Write Formatted Data to a Stream  fscanf - Read Formatted Data  printf - Print Formatted Characters  scanf - Read Data  sprintf - Print Formatted Data to Buffer  sscanf - Read Data  swprintf - Format and Write Wide Characters to Buffer  swscanf - Read Wide Characters from Buffer  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer Character and String Input/Output  fgetc - Read a Character  _fgetchar - Read Single Character from stdin  fgets - Read a String  fputc - Write Character  _fputchar - Write Character  fputs - Write String  getc - getchar - Read a Character  gets - Read a Line  putc - putchar - Write a Character  puts - Write a String  ungetc - Push Character onto Input Stream Wide Character and String Input/Output  fgetwc - Read Wide Character from Stream  fgetwc - Read Wide Character from Stream  fputwc - Write Wide Character  fputws - Write Wide-Character String  getwc - Read Wide Character from Stream  getwchar - Get Wide Character from stdin  putwc - Write Wide Character  putwchar - Write Wide Character to stdout  ungetwc - Push Wide Character onto Input Stream Direct Input/Output  clearerr - Reset Error Indicators.  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fread - Read Items  fwrite - Write Items File Positioning  fgetpos - Get File Position  fseek - Reposition File Position  fsetpos - Set File Position  ftell - Get Current Position  lseek - Move File Pointer  rewind - Adjust Current File Position File Access  fclose - Close Stream  _fcloseall - Close All Open Streams  fdopen - Associates Input Or Output With File  fflush - Write Buffer to File  _flushall - Write Buffers to Files  fopen - Open Files  freopen - Redirect Open Files  setbuf - Control Buffering  _setmode - Set File Translation Mode  setvbuf - Control Buffering File Operations  fileno - Determine File Handle  remove - Delete File  rename - Rename File  _rmtmp - Remove Temporary Files  tempnam - Produce Temporary File Name  tmpfile - Create Temporary File  tmpnam - Produce Temporary File Name  unlink - Delete File ═══ 2.12. Low-Level Input/Output Functions ═══ Port Input/Output  _inp - Read Byte from Input Port  _inpd - Read Doubleword from Input Port  _inpw - Read Unsigned Short from Input Port  _outp - Write Byte to Output Port  _outpd - Write Double Word to Output Port  _outpw - Write Word to Output Port  umask - Sets File Mask of Current Process Character and String Input/Output  _cgets - Read String of Characters from Keyboard  _cprintf - Print Characters to Screen  _cputs - Write String to Screen  _cscanf - Read Data from Keyboard  _getch - _getche - Read Character from Keyboard  _kbhit - Test for Keystroke  _putch - Write Character to Screen  _ungetch - Push Character Back to Keyboard Direct Input/Output  read - Read Into Buffer  write - Writes from Buffer to File File Positioning  __eof - Determine End of File  _tell - Get Pointer Position File Access  access - Determine Access Mode  chmod - Change File Permission Setting  close - Close File Associated with Handle  creat - Create New File  dup - Associate Second Handle with Open File  dup2 - Associate Second Handle with Open File  isatty - Test Handle for Character Device  open - Open File  _sopen - Open Shared File File Operations  _chsize - Alter Length of File  _filelength - Determine File Length ═══ 2.13. Functions for Handling Argument Lists ═══  va_arg - va_end - va_start - Access Function Arguments  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer ═══ 2.14. Pseudorandom Number Functions ═══  rand - Generate Random Number  srand - Set Seed for rand Function ═══ 2.15. Dynamic Memory Management Functions ═══ Allocating and Freeing Memory  _alloca - Temporarily Reserve Storage Block  calloc - Reserve and Initialize Storage  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_heapmin - Release Unused Memory in the Default Heap  _debug_malloc - Allocate Memory  _debug_realloc - Reallocate Memory Block  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_theapmin - Release Unused Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  _debug_ucalloc - Reserve and Initialize Memory from User Heap  _debug_uheapmin - Release Unused Memory in User Heap  _debug_umalloc - Reserve Memory Blocks from User Heap  free - Release Storage Blocks  _heapmin - Release Unused Memory from Default Heap  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  _tcalloc - Reserve Tiled Storage Block  _tfree - Free Tiled Storage Block  _theapmin - Release Unused Tiled Memory  _tmalloc - Reserve Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block Heap Information and Checking  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heap_check - Validate Default Memory Heap  _heapchk - Validate Default Memory Heap  _heapset - Validate and Set Default Heap  _heap_walk - Return Information about Default Heap  _mheap - Query Memory Heap for Allocated Object  _msize - Return Number of Bytes Allocated  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _theap_check - Validate User Memory Heap  _udump_allocated - Get Information about Allocated Memory in Heap  _udump_allocated_delta - Get Information about Allocated Memory in Heap  _uheap_check - Validate User Memory Heap  _uheapchk - Validate Memory Heap  _uheapset - Validate and Set Memory Heap  _uheap_walk - Return Information about Memory Heap  _ustats - Get Information about Heap Heap Creation and Management  _uaddmem - Add Memory to a Heap  _uclose - Close Heap from Use  _ucreate - Create a Memory Heap  _udefault - Change the Default Heap  _udestroy - Destroy a Heap  _uopen - Open Heap for Use ═══ 2.16. Memory Object Functions ═══  memccpy - Copy Bytes  memchr - Search Buffer  memcmp - Compare Buffers  memcpy - Copy Bytes  memicmp - Compare Bytes  memmove - Copy Bytes  memset - Set Bytes to Value  swab - Swap Adjacent Bytes ═══ 2.17. Environment and Locale Interaction Functions ═══  abort - Stop a Program  exit - End Program  getenv - Search for Environment Variables  longjmp - Restore Stack Environment  __parmdwords - Get Number of dwords in Parameter List  setjmp - Preserve Environment  system - Invoke the Command Processor Setting and Querying Locale  csid - Determine Character Set ID for Multibyte Character  getsyntx - Return LC_SYNTAX Characters  iconv - Convert Characters to New Code Set  iconv_close - Remove Conversion Descriptor  iconv_open - Create Conversion Descriptor  localdtconv - Return Date and Time Formatting Convention  localeconv - Retrieve Information from the Environment  nl_langinfo - Retrieve Locale Information  setlocale - Set Locale  wcsid - Determine Character Set ID for Wide Character  wctype - Get Handle for Character Property Classification String and Character Collating  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strcoll - Compare Strings Using Collation Rules  strtocoll - Return Collating Element for String  wcscoll - Compare Wide-Character Strings ═══ 2.18. String Operation Functions ═══  strcat - Concatenate Strings  strchr - Search for Character  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  strcoll - Compare Strings Using Collation Rules  strcpy - Copy Strings  strcspn - Compare Strings for Substrings  strdup - Duplicate String  stricmp - Compare Strings as Lowercase  strlen - Determine String Length  strncat - Concatenate Strings  strncmp - Compare Strings  strncpy - Copy Strings  strnicmp - Compare Strings Without Case Sensitivity  strnset - strset - Set Characters in String  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strrev - Reverse String  strnset - strset - Set Characters in String  strspn - Search Strings  strstr - Locate Substring  strtok - Tokenize String  strxfrm - Transform String ═══ 2.19. Character Testing Functions ═══  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  isblank - Test for Blank Character Classification  _iscsym - _iscsymf - Test Integer  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  iswblank - Test for Wide Blank Character Classification  iswctype - Test for Character Property  wcwidth - Determine Display Width of Wide Character ═══ 2.20. Case Mapping Functions ═══  strlwr - Convert Uppercase to Lowercase  strupr - Convert Lowercase to Uppercase  tolower() - toupper() - Convert Character Case  tolower() - toupper() - Convert Character Case  _toascii - _tolower - _toupper - Convert Character  towlower - towupper - Convert Wide Character Case ═══ 2.21. Wide Character String Operation Functions ═══  mblen - Determine Length of Multibyte Character  wcscat - Concatenate Wide-Character Strings  wcschr - Search for Wide Character  wcscmp - Compare Wide-Character Strings  wcscoll - Compare Wide-Character Strings  wcscpy - Copy Wide-Character Strings  wcscspn - Find Offset of First Wide-Character Match  wcslen - Calculate Length of Wide-Character String  wcsncat - Concatenate Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  wcsncpy - Copy Wide-Character Strings  wcspbrk - Locate Wide Characters in String  wcsspn - Search Wide-Character Strings  wcsrchr - Locate Wide Character in String  wcsstr - Locate Wide-Character Substring  wcstok - Tokenize Wide-Character String  wcswcs - Locate Wide-Character Substring  wcswidth - Determine Display Width of Wide-Character String  wcsxfrm - Transform Wide-Character String ═══ 3. Additional VisualAge C++ Library Features ═══ Many of the functions in the VisualAge C++ runtime library are extensions to the ANSI standard. This section describes some of the additional support the VisualAge C++ library provides and the behavior of certain features.  Intrinsic Functions  Differentiating between the Memory Management Functions  Infinity and NaN Support  Using Low-Level I/O Functions ═══ 3.1. Intrinsic Functions ═══ The VisualAge C++ compiler inlines some functions instead of generating a function call for them. Some of these functions are always inlined; others are inlined only when you compile with the optimization option (/O or /Oc) on.  Functions that Are Inlined when Optimization Is On  Functions that Are Always Inlined ═══ 3.1.1. Functions that Are Inlined when Optimization Is On ═══ When optimization is on (/O+), VisualAge C++ compiler by default inlines (generates code instead of a function call) 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 The compiler inlines these functions when you include the appropriate header file that contains the function prototype and the #define and #pragma statements for the function. You can override the inlining 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 optimize-for-size compiler option (/Oc) also disables the inlining of intrinsic functions. ═══ 3.1.2. Functions that Are Always Inlined ═══ The following functions are built-in functions, meaning they do not have any backing library functions, and are always inlined: _alloca _crotl _crotr __cxchg _disable _enable _facos _fasin _fcos _fcossin _fpatan _fptan _fsin _fsincos _fsqrt _fyl2x _fyl2xp1 _f2xm1 _getTIBvalue _inp _inpd _inpw _interrupt _lrotl _lrotr __lxchg _outp _outpd _outpw __parmdwords _rotl _rotr _srotl _srotr __sxchg Do not parenthesize the names of these functions. The built-in functions are all defined in , in addition to the standard header definitions. ═══ Related Information ═══  Functions that Are Inlined when Optimization Is On  Functions that Are Always Inlined  #include in the Language Reference  #define in the Language Reference  #pragma in the Language Reference  /O option in the User's Guide  ═══ 3.2. Differentiating between Memory Management Functions ═══ The memory management functions defined by ANSI are calloc, malloc, realloc, and free. These regular functions allocate and free memory from the default runtime heap. (VisualAge C++ has added another function, _heapmin, to return unused memory to the system.) VisualAge C++ also provides different versions of each of these functions as extensions to the ANSI definition. All the versions actually work the same way; they differ only in what heap they allocate from, and in whether they save information to help you debug memory problems. The memory allocated by all of these functions is suitably aligned for storing any type of object. The following table summarizes the different versions of memory management functions, using malloc as an example of how the names of the functions change for each version. They are all described in greater detail in this section. ┌─────────────────────────┬──────────────────────────┬─────────────────────────┐ │ │ REGULAR VERSION │ DEBUG VERSION │ ├─────────────────────────┼──────────────────────────┼─────────────────────────┤ │ DEFAULT HEAP │ malloc │ _debug_malloc │ ├─────────────────────────┼──────────────────────────┼─────────────────────────┤ │ USER HEAP │ _umalloc │ _debug_umalloc │ ├─────────────────────────┼──────────────────────────┼─────────────────────────┤ │ TILED HEAP ("/Gt") │ _tmalloc │ _debug_tmalloc │ └─────────────────────────┴──────────────────────────┴─────────────────────────┘ To use these extensions, you must set the language level to extended, either with the /Se compiler option or the #pragma langlvl(extended) directive. ═══ Related Information ═══  Differentiating between Memory Management Functions  Heap-Specific Functions  Tiled Functions  Debug Functions  Heap-Specific Debug Functions  Tiled Debug Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide ═══ 3.2.1. Heap-Specific Functions ═══ Use the heap-specific versions to allocate and free memory from a user-created heap that you specify. (You can also explicitly use the runtime heap if you want.) Their names are prefixed by _u (for "user heaps"), for example, _umalloc, and they are defined in . The functions provided are:  _ucalloc  _umalloc  _uheapmin Notice there is no heap-specific version of realloc or free. Because they both always check what heap the memory was allocated from, you can always use the regular versions regardless of what heap the memory came from. For more information about creating your own heaps and using the heap-specific memory management functions, see Managing Memory with Multiple Heaps in the Programming Guide. ═══ 3.2.2. Tiled Functions ═══ Use the tiled memory management functions to allocate and free memory from the runtime's tiled memory heap. If you have objects that can be accessed by 16-bit code, you should store them in tiled memory. Tiled memory does not cross 64K boundaries, as long as the object is smaller than 64K. Objects larger than 64K are aligned on 64K boundaries, but will also cross 64K boundaries. When you use the tiled memory compiler option, /Gt, all calls to the regular memory management functions are mapped to their tiled versions. You can also call the tiled versions explicitly. Note: If you parenthesize the calls to the regular memory management functions, they are not mapped to their tiled versions. The names of the tiled versions are prefixed by _t (for "tiled"), for example, _tmalloc, and they are defined in and . The functions provided are:  _tcalloc  _tfree  _theapmin  _tmalloc  _trealloc You can also create your own heaps of tiled memory. Creating your own heaps is described in Managing Memory Using Multiple Heaps in the Programming Guide. For more information about sharing objects between 32-bit and 16-bit code, see Calling Between 32-Bit and 16-Bit Code in the Programming Guide. ═══ 3.2.3. Debug Functions ═══ Use these functions to allocate and free memory from the default runtime heap, just as you would use the regular versions. They also provide information that you can use to debug memory problems. 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. When you use the debug memory compiler option, /Tm, all calls to the regular memory management functions are mapped to their debug versions. You can also call the debug versions explicitly. Note: If you parenthesize the calls to the regular memory management functions, they are not mapped to their debug versions. We recommend you place a #pragma strings(readonly) directive at the top of each source file that will call debug functions, or in a common header file that each includes. This directive is not essential, but it ensures that the file name passed to the debug functions can't be overwritten, and that only one copy of the file name string is included in the object module. The names of the debug versions are prefixed by _debug_, for example, _debug_malloc, and they are defined in and . The functions provided are:  _debug_calloc  _debug_free  _debug_heapmin  _debug_malloc  _debug_realloc In addition to their usual behavior, these functions also store information (file name and line number) about each call made to them. Each call also automatically checks the heap by calling _heap_check (described below). Three additional debug memory management functions do not have regular counterparts:  _dump_allocated Prints information to file handle 2 (the usual destination of stderr) about each memory block currently allocated by the debug functions. You can change the destination of the information with the _set_crt_msg_handle function.  _dump_allocated_delta Prints information to file handle 2 about each memory block allocated by the debug functions since the last call to _dump_allocated or _dump_allocated_delta. Again, you can change the destination of the information with the _set_crt_msg_handle function.  _heap_check Checks all memory blocks allocated or freed by the debug functions to make sure that no overwriting has occurred outside the bounds of allocated blocks or in a free memory block. The debug functions call _heap_check automatically; you can also call it explicitly. To use _dump_allocated and _dump_allocated_delta, you must call them explicitly. In C Set ++ releases prior to VisualAge C++ Version 3.0, you could not mix debug and regular versions of the memory management functions. For example, you could not allocate memory with malloc and free it with _debug_free. This restriction no longer applies; realloc and free (debug or otherwise) can now handle memory allocated by any other allocation function. ═══ 3.2.4. Heap-Specific Debug Functions ═══ The heap-specific functions also have debug versions that work just like the regular debug versions. Use these functions to allocate and free memory from the user-created heap you specify, and also provide information that you can use to debug memory problems in your own heaps. 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. You can call them explicitly, or you can use the debug memory compiler option, /Tm, to map calls to the heap-specific functions to their debug counterparts. Note: If you parenthesize the calls to the heap-specific memory management functions, they are not mapped to their debug versions. The names of the heap-specific debug versions are prefixed by _debug_u, for example, _debug_umalloc, and they are defined in . The functions provided are:  _debug_ucalloc  _debug_uheapmin  _debug_umalloc  _udump_allocated  _udump_allocated_delta  _uheap_check Notice there is no heap-specific debug version of realloc or free. Because they both always check what heap the memory was allocated from, you always use the regular debug versions (_debug_realloc and _debug_free), regardless of what heap the memory came from. For more information about debugging memory problems in your own heaps, see "Debugging Your Heaps" in the Programming Guide. ═══ 3.2.5. Tiled Debug Functions ═══ The tiled functions also have debug versions that work just like the regular and heap-specific debug versions. Use these functions to allocate and free memory from the tiled VisualAge C++ runtime heap. They also provide information that you can use to debug memory problems with the tiled heap. 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. You can call them explicitly, or you can use the debug memory and tiled memory compiler options /Tm and /Gt, to map calls to the regular memory management functions to their tiled debug counterparts. Note: If you parenthesize the calls to the heap-specific memory management functions, they are not mapped to their debug versions. The names of the tiled debug versions are prefixed by _debug_t, for example, _debug_tmalloc, and they are defined in and . The functions provided are:  _debug_tcalloc  _debug_tfree  _debug_theapmin  _debug_tmalloc  _debug_trealloc  _tdump_allocated  _tdump_allocated_delta  _theap_check For more information about debugging memory problems, see "Debugging Your Heaps" in the Programming Guide. ═══ 3.3. Infinity and NaN Support ═══ VisualAge C++ 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. VisualAge C++ 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. You can get the corresponding negative values by using the unary minus operator (for example, -_INF). Note: The value of 0.0 can also be positive or negative. For example, 1.0 / (-0.0) results in -_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: Although 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 User's Guide. ═══ Related Information ═══  Infinity and NaN in Library Functions  Assignment Expression  Equality  Relational  ═══ 3.3.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:  scanf Family  printf Family  String Conversion Functions  Math Functions ═══ Related Information ═══  Infinity and NaN Support  scanf Family  printf Family  String Conversion Functions  Math Functions  #pragma langlvl  /Se option. ═══ 3.3.1.1. scanf Family ═══ The scanf family of functions includes the functions scanf, fscanf, sscanf, and swscanf. 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 ═══ /************************************************************************ * 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 ═══ Example  Infinity and NaN Support  fscanf - Read Formatted Data  scanf - Read Data  sscanf - Read Data  swscanf - Read Wide Characters from Buffer ═══ 3.3.1.2. printf Family ═══ The printf family of functions includes the functions printf, fprintf, sprintf, swprintf, vfprintf, vprintf, vsprintf, and vswprintf. 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 ═══ /************************************************************************ * 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 ═══ Example  Infinity and NaN Support  fprintf - Write Formatted Data to a Stream  printf - Print Formatted Characters  sprintf - Print Formatted Data to Buffer  swprintf - Format and Write Wide Characters to Buffer  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer ═══ 3.3.1.3. String Conversion Functions ═══ The string conversion functions that support infinity and NaN representations include the functions atof, _atold, _ecvt, _fcvt, _gcvt, strtod, strtold, and wcstod. The atof, _atold, strtod, strtold, and wcstod 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 ═══ /************************************************************************ * The following example uses atof to convert the strings "naN" and "inf" 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 ═══ Example  Infinity and NaN Support  atof - Convert Character String to Float  _atold - Convert Character String to Long Double  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  strtod - Convert Character String to Double  strtold - Convert String to Long Double ═══ 3.3.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 results 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 these two tables. ┌──────────────────────────────────────────────────────────────────────────────┐ │ Table 1. 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. ┌──────────────────────────────────────────────────────────────────────────────┐ │ Table 2. 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. ═══ 3.3.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 results 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 and in the size of your executable file. ═══ Related Information ═══  Infinity and NaN Support   acos - Calculate Arccosine  asin - Calculate Arcsine  atan - atan2 - Calculate Arctangent  ceil - Find Integer >= Argument  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  erf - erfc - Calculate Error Functions  exp - Calculate Exponential Function  fabs - Calculate Floating-Point Absolute Value  floor - Integer <= Argument  fmod - Calculate Floating-Point Remainder  frexp - Separate Floating-Point Value  gamma - Gamma Function  ldexp - Multiply by a Power of Two  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  modf - Separate Floating-Point Value  pow - Compute Power  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  sqrt - Calculate Square Root  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent ═══ 3.4. Using Low-Level I/O Functions ═══ The VisualAge C++ compiler supports both stream 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 you. 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 use the low-level I/O functions, you should be aware of the following:  A handle is a value that identifies a file. It is created by the system and used by low-level I/O functions. For VisualAge C++, the handle returned by low-level I/O functions like open (called the C_handle) is the same as that returned by DosOpen (called the API_handle). As a result, you can get a file handle using the low-level I/O functions, and then use it with OS/2 APIs. Portability Note Other compilers may map the file handle so that the C_handle and API_handle are different. If you will be compiling your programs with other compilers, do not write code that depends on the file handles being the same. You can pass handles between library environments without restriction. If you acquire a handle other than by using the VisualAge C++ library functions open, creat, _sopen, or fileno, you must run _setmode for that handle before you use it with other VisualAge C++ library functions.  The default open-sharing mode is SH_DENYWR. Use _sopen to obtain other sharing modes.  Text mode deletes '\r' characters on input and changes '\n' to '\r\n' on output.  In a multithread environment, you must 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.  If the file mode is text, the low-level I/O functions treat the character 'x1a' in the following ways: - If it is detected in a nonseekable file, 'x1a' is treated as end-of-file. In a seekable file, it is treated as end-of-file only if it is the last character. - 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 ═══  Low-Level Input/Output Functions  Performing I/O Operations in the Programming Guide  access - Determine Access Mode  chmod - Change File Permission Setting  _chsize - Alter Length of File  close - Close File Associated with Handle  creat - Create New File  dup - Associate Second Handle with Open File  dup2 - Associate Second Handle with Open File  __eof - Determine End of File  fdopen - Associates Input Or Output With File  _filelength - Determine File Length  fileno - Determine File Handle  fstat - Information about Open File  isatty - Test Handle for Character Device  lseek - Move File Pointer  open - Open File  read - Read Into Buffer  _setmode - Set File Translation Mode  _sopen - Open Shared File  stat - Get Information about File or Directory  _tell - Get Pointer Position  umask - Sets File Mask of Current Process  write - Writes from Buffer to File ═══ 4. Library Functions ═══ The VisualAge C++ libraries are divided into two parts:  Standard libraries, which define the SAA features and the VisualAge C++ standard extensions to SAA  Subsystem libraries, which are a subset of the standard libraries, and are used for subsystem development. The functions in these libraries do not require a runtime environment. This section lists alphabetically and describes all the functions that VisualAge C++ product offers, including the extensions to the ANSI/ISO 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. To include the declaration in your code, include the header file. Description A brief description of what the function does, what parameters it takes, and how to use the function. Language Level The C language standard that each function belongs to (some fall under more than one): ANSI ANSI/ISO 9899-1990[1992] C standard (commonly referred to as the ANSI C standard or ANSI/ISO C standard). ANSI 93 A subset of the ISO/IEC 9899:1990/Amendment 1:1993(E). POSIX ISO/IEC 9945-1:1990/IEEE POSIX 1003.1-1990 standard. XPG4 X/Open Common Applications Environment Specification, System Interfaces and Headers, Issue 4. SAA IBM Systems Application Architecture Common Programming Interface (SAA CPI) Level 2 definition. Extension Extensions to the conventional standards, often specific to VisualAge C++. (These include standard functions that have additional features under VisualAge C++.) Note: To use the library extensions, you must set the language level to extended (with the #pragma langlvl(extended) directive or the /Se option); note that this is the default. Example A short example of how to use the function. From the online C Library Reference, you can use the IPF Copy to File choice from the Services pull-down to copy a function example to a separate file (called TEXT.TMP by default). You can then compile, link, and run the example, or use the example code in your own source files. Related Information A list of other functions that are similar to or related to the function, and of other topics that provide additional information that help you use the function. ═══ 4.1. abort - Stop a Program ═══ ═══ Format ═══ #include void abort(void); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension abort causes an abnormal program termination and returns control to the host environment. It 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. Return Value There is no return value. ═══ Example of abort ═══ /************************************************************************ This example tests for successful opening of the file myfile.mjq. If an error occurs, an error message is printed and the program ends with a call to abort. ************************************************************************/ #include #include int main(void) { FILE *stream; if (NULL == (stream = fopen("myfile.mjq", "r"))) { perror("Could not open data file"); abort(); } return 0; /**************************************************************************** If myfile.mjq does'nt exist, the output should be: Could not open data file: The file cannot be found. ****************************************************************************/ } ═══ Related Information ═══ Example of abort  exit - End Program  _exit - End Process  signal - Handle Interrupt Signals  ═══ 4.2. abs - Calculate Integer Absolute Value ═══ ═══ Format ═══ #include int abs(int n); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension abs returns the absolute value of an integer argument n. Return Value 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_MAX in the include file. ═══ 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); /* y = 4 */ printf("abs( %d ) = %d\n", x, y); return 0; /**************************************************************************** The output should be: abs( -4 ) = 4 ****************************************************************************/ } ═══ Related Information ═══ Example of abs  _cabs - Calculate Absolute Value of Complex Number  fabs - Calculate Floating-Point Absolute Value  labs - Calculate Absolute Value of Long Integer   ═══ 4.3. access - Determine Access Mode ═══ ═══ Format ═══ #include int access(char *pathname, int mode); ═══ Description ═══ Language Level: POSIX, XPG4, Extension access determines whether the specified file exists and whether you can get access to it in the given mode. Possible values for the mode and their meaning in the access call are: 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. Note: In earlier releases of C Set ++, access began with an underscore (_access). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _access to access for you. Return Value access returns 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 ═══ /************************************************************************ 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: File sample.dat does not exist. Creating sample.dat. File sample.dat created. ****************************************************************************/ } ═══ Related Information ═══ Example of access  chmod - Change File Permission Setting  _sopen - Open Shared File  umask - Sets File Mask of Current Process  ═══ 4.4. acos - Calculate Arccosine ═══ ═══ Format ═══ #include double acos(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 acos calculates the arccosine of x, expressed in radians, in the range 0 to pi. Return Value acos returns the arccosine of x. 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 ═══ /************************************************************************ 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 #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); } return 0; /**************************************************************************** For the following input: 0.4 The output should be: Enter x acos( 0.400000 ) = 1.159279 ****************************************************************************/ } ═══ Related Information ═══ Example of acos  asin - Calculate Arcsine  atan - atan2 - Calculate Arctangent  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.5. _alloca - Temporarily Reserve Storage Block ═══ ═══ Format ═══ #include /* also in and */ void *_alloca(size_t size); ═══ Description ═══ Language Level: Extension _alloca 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: _alloca is faster than other allocation functions such as malloc, but it has several limitations:  Because it is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library: - You cannot take the address of _alloca. - You cannot parenthesize a call to _alloca. (Parentheses specify a call to the function's backing code, and _alloca has none).  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.  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. Return Value _alloca 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 ═══ /************************************************************************ 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 #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 "); printf("(each generated from 1 to 5):\n\n"); /* set seed for rand function using time in seconds */ srand((unsigned int)time(NULL)); 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 *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; /**************************************************************************** The output should be similar to : 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 ═══ Example  calloc - Reserve and Initialize Storage  free - Release Storage Blocks  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  /Gs option in the User's Guide   ═══ 4.6. asctime - Convert Time to Character String ═══ ═══ Format ═══ #include char *asctime(const struct tm *time); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 The asctime function converts time, stored as a structure pointed to by time, to a character string. You can obtain the time value 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 - Print Formatted Characters for a description of format specifications. The following are examples of the string returned: Sat Jul 16 02:03:55 1994\n\0 or Sat Jul 16 2:03:55 1994\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. Dates 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. Return Value The asctime function returns a pointer to the resulting character string. There is no error return value. Note: 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 ═══ /************************************************************************ 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)); return 0; /**************************************************************************** The output should be similar to : The current date and time are Fri Jun 28 13:51 1994 ****************************************************************************/ } ═══ Related Information ═══ Example of asctime  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  strftime - Convert to Formatted Time  time - Determine Current Time  printf - Print Formatted Characters  ═══ 4.7. asin - Calculate Arcsine ═══ ═══ Format ═══ #include double asin(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 asin calculates the arcsine of x, in the range -pi/2 to pi/2 radians. Return Value asin returns the arcsine of x. 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 ═══ /************************************************************************ 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 arcsine 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); } return 0; /**************************************************************************** For the following input: 0.2 The output should be: Enter x asin( 0.200000 ) = 0.201358 ****************************************************************************/ } ═══ Related Information ═══ Example of asin  acos - Calculate Arccosine  atan - atan2 - Calculate Arctangent  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _fasin - Calculate Arcsine  _fcossin - Calculate Cosine and Sine  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.8. assert - Verify Condition ═══ ═══ Format ═══ #include void assert(int expression); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 assert 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. assert takes no action if the expression is true (nonzero). Use assert 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: assert is implemented as a macro. Do not use the #undef directive with assert. ═══ Example of assert ═══ /************************************************************************ In this example, assert tests string for a null string and an empty string, and verifies that length is positive before processing these arguments. ************************************************************************/ #include #include void analyze(char *string,int length) { assert(string != NULL); /* cannot be NULL */ assert(*string != '\0'); /* cannot be empty */ assert(length > 0); /* must be positive */ return; } 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); return 0; /**************************************************************************** The output should be: The string ABC is not null or empty, and has length 3 ****************************************************************************/ } ═══ Related Information ═══ Example of assert  abort - Stop a Program   #define in the Language Reference  #undef in the Language Reference ═══ 4.9. atan - atan2 - Calculate Arctangent ═══ ═══ Format ═══ #include double atan(double x); double atan2(double y, double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 atan and atan2 calculate the arctangent of x and y/x, respectively. Return Value atan returns a value in the range -pi/2 to pi/2 radians. atan2 returns a value in the range -pi to pi radians. If both arguments of atan2 are zero, the function sets errno to EDOM, and returns a value of 0. ═══ Example of atan - atan2 ═══ /************************************************************************ This example calculates arctangents using the atan and atan2 functions. ************************************************************************/ #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); return 0; /**************************************************************************** The output should be: atan( 0.450000 ) = 0.422854 atan2( 0.450000, 0.230000 ) = 1.098299 ****************************************************************************/ } ═══ Related Information ═══ Example of atan - atan2  acos - Calculate Arccosine  asin - Calculate Arcsine  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _fpatan - Calculate Arctangent  _fptan - Calculate Tangent  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.10. atexit - Record Program Termination Function ═══ ═══ Format ═══ #include int atexit(void (*func)(void)); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 atexit 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. Return Value atexit returns 0 if it is successful, and nonzero if it fails. ═══ Example of atexit ═══ /************************************************************************ This example uses atexit to call the function goodbye at program termination. ************************************************************************/ #include #include void goodbye(void) { /* This function is called at normal program termination */ printf("The function goodbye was called at program termination\n"); } int main(void) { int rc; rc = atexit(goodbye); if (rc != 0) perror("Error in atexit"); return 0; /**************************************************************************** The output should be: The function goodbye was called at program termination ****************************************************************************/ } ═══ Related Information ═══ Example of atexit  exit - End Program  _exit - End Process  _onexit - Record Termination Function  signal - Handle Interrupt Signals  ═══ 4.11. atof - Convert Character String to Float ═══ ═══ Format ═══ #include double atof(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension atof 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. atof 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. atof ignores leading white-space characters. For atof, 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. Return Value atof 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 ═══ /************************************************************************ This example shows how to convert numbers stored as strings to numerical values using the atof function. ************************************************************************/ #include #include int main(void) { double x; char *s; s = " -2309.12E-15"; x = atof(s); /* x = -2309.12E-15 */ printf("atof( %s ) = %G\n", s, x); return 0; /**************************************************************************** The output should be: atof( -2309.12E-15 ) = -2.30912E-12 ****************************************************************************/ } ═══ Related Information ═══ Example of atof  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  Infinity and NaN Support  ═══ 4.12. atoi - Convert Character String to Integer ═══ ═══ Format ═══ #include int atoi(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 atoi 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 that ends the string. atoi 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. atoi ignores leading white-space characters. digits is one or more decimal digits. Return Value 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 ═══ /************************************************************************ This example shows how to convert numbers stored as strings to numerical values using the atoi function. ************************************************************************/ #include #include int main(void) { int i; char *s; s = " -9885"; i = atoi(s); /* i = -9885 */ printf("atoi( %s ) = %d\n", s, i); return 0; /**************************************************************************** The output should be: atoi( -9885 ) = -9885 ****************************************************************************/ } ═══ Related Information ═══ Example of atoi  atof - Convert Character String to Float  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  ═══ 4.13. atol - Convert Character String to Long Integer ═══ ═══ Format ═══ #include long int atol(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 atol 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. atol 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. atol ignores leading white-space characters. digits is one or more decimal digits. Return Value 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 ═══ /************************************************************************ This example shows how to convert numbers stored as strings to numerical values using the atol function. ************************************************************************/ #include #include int main(void) { long l; char *s; s = "98854 dollars"; l = atol(s); /* l = 98854 */ printf("atol( %s ) = %d\n", s, l); return 0; /**************************************************************************** The output should be similar to : atol( 98854 dollars ) = 98854 ****************************************************************************/ } ═══ Related Information ═══ Example of atol  atof - Convert Character String to Float  atoi - Convert Character String to Integer  _atold - Convert Character String to Long Double  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  ═══ 4.14. _atold - Convert Character String to Long Double ═══ ═══ Format ═══ #include /* also defined in */ long double _atold(const char *nptr); ═══ Description ═══ Language Level: Extension _atold 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 can 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 ─┘ ├─ + ─┤ │ │ └─ ┴ ─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ digits is 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. _atold ignores any white-space characters, as defined by the isspace function. Return Value _atold 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. It returns negative _LHUGE_VAL for a negative overflow. ═══ 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 output should be: _atold = -1.2345678000e+13 _atold = nan ****************************************************************************/ } ═══ Related Information ═══ Example of _atold  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double   ═══ 4.15. _beginthread - Create New Thread ═══ ═══ Format ═══ #include /* also in */ int _beginthread(void (*start_address) (void *), (void *)stack, unsigned stack_size, void *arglist); ═══ Description ═══ Language Level: Extension _beginthread 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, that 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 correctly. Using DosCreateThread requires that you use _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. Return Value If successful, _beginthread returns the thread ID number of the new thread. It returns -1 to indicate an error. ═══ 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 _Optlink 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) { int tid; tid = _beginthread(bonjour, NULL, 8192, NULL); if (-1 == tid) { printf("Unable to start thread.\n"); return EXIT_FAILURE; } else { printf("Thread started with thread identifier number %d.\n", tid); wait = 0; } DosWaitThread((PTID)&tid, DCWW_WAIT); /* wait for thread bonjourto end */ /* before ending main thread */ return 0; /**************************************************************************** The output should be similar to : Thread started with thread identifier number 2. Bonjour! Bonjour! Bonjour! Bonjour! Bonjour! ****************************************************************************/ } ═══ Related Information ═══ Example of _beginthread  _endthread - Terminate Current Thread  _threadstore - Access Thread-Specific Storage  /Gm+ option in the User's Guide   ═══ 4.16. Bessel Functions - Solve Differential Equations ═══ ═══ Format ═══ #include 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. Return Value 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 an overflow, the function sets errno to ERANGE and returns the value -HUGE_VAL. ═══ 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 #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 */ printf("j0( 4.27 ) = %5.4f\n", y); z = yn(3, x); /* z = -0.0875 is the order 3 bessel */ /* function of the second kind for x */ printf("yn( 3,4.27 ) = %5.4f\n", z); return 0; /**************************************************************************** The output should be: j0( 4.27 ) = -0.3660 yn( 3,4.27 ) = -0.0875 ****************************************************************************/ } ═══ Related Information ═══ Example of Bessel Functions  erf - erfc - Calculate Error Functions  gamma - Gamma Function  ═══ 4.17. bsearch - Search Arrays ═══ ═══ Format ═══ #include /* also in */ void *bsearch(const void *key, const void *base, size_t num, size_t size, int (*compare)(const void *key, const void *element)); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG, Extension bsearch 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 argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. bsearch calls this function one or more times during the search. The function must compare the key and the element and return one of the following values: Value Meaning Less than 0 key less than element 0 key identical to element Greater than 0 key greater than element Return Value bsearch returns a pointer to key in the array to which base points. If two keys are equal, the element that key will point to is unspecified. If bsearch cannot find the key, it returns NULL. ═══ 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 /* ------------------------------------------------------------------ */ /* Note: Library always calls functions internally with _Optlink */ /* linkage convention. Ensure that compare1() and compare2 */ /* are always _Optlink. */ /* ------------------------------------------------------------------ */ int _Optlink compare1(const void *arg1,const void *arg2) { return (strcmp(*(char **)arg1, *(char **)arg2)); } int _Optlink compare2(const void *arg1,const void *arg2) { return (strcmp((char *)arg1, *(char **)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"); return 0; /**************************************************************************** If the program name is progname and you enter: progname where is PATH in this phrase? The output should be: result = ****************************************************************************/ } ═══ Related Information ═══ Example of bsearch  lfind - lsearch - Find Key in Array  qsort - Sort Array  ═══ 4.18. _cabs - Calculate Absolute Value of Complex Number ═══ ═══ Format ═══ #include double _cabs(struct complex z); ═══ Description ═══ Language Level: Extension _cabs 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 across SAA systems, use the SAA function hypot. to replace _cabs. Return Value _cabs 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 ═══ /************************************************************************ 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; /**************************************************************************** The output should be: The complex absolute value of 3.000000 and 4.000000 is 5.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of _cabs  abs - Calculate Integer Absolute Value  fabs - Calculate Floating-Point Absolute Value  hypot - Calculate Hypotenuse  labs - Calculate Absolute Value of Long Integer  _matherr - Process Math Library Errors  sqrt - Calculate Square Root  ═══ 4.19. calloc - Reserve and Initialize Storage ═══ ═══ Format ═══ #include /* also in */ void *calloc(size_t num, size_t size); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 calloc reserves storage space for an array of num elements, each of length size bytes. calloc then gives all the bits of each element an initial value of 0. Heap-specific and tiled versions of this function (_ucalloc and _tcalloc) are also available. calloc always allocates memory from the default heap. You can also use the debug version of calloc, _debug_calloc, to debug memory problems. Return Value calloc returns a pointer to the reserved space. The storage space to which the return value points is 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 ═══ /************************************************************************ 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(); } return 0; /**************************************************************************** The output should be similar to : Enter the size of the array 3 array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2 ****************************************************************************/ } ═══ Related Information ═══ Example of calloc  _alloca - Temporarily Reserve Storage Block  _debug_calloc - Allocate and Initialize Memory  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_ucalloc - Reserve and Initialize Memory from User Heap  free - Release Storage Blocks  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  _tcalloc - Reserve Tiled Storage Block  _ucalloc - Reserve and Initialize Memory from User Heap    Managing Memory in the Programming Guide ═══ 4.20. cclass - Return Characters in Character Class ═══ ═══ Format ═══ #include int cclass(char *class, collel_t **list); ═══ Description ═══ Language Level: Extension cclass finds all the collating elements of the character class, and stores them in an array. It then updates the list to point to the first element of the array of found collating elements. The list is valid until the next call to setlocale. cclass supports POSIX.2 character classes and user-defined character classes. Return Value cclass returns the number of elements in the list and sets a pointer to point to the list. If the class does not exist in the LC_CTYPE category of the current locale, cclass returns -1. ═══ Example of cclass ═══ /************************************************************************ This example finds all the collating elements that belong to the digit class. It then prints how many elements were found in that class and the weight (collating value) of each element. ************************************************************************/ #include #include int main(void) { collel_t *list; /* ptr to the digit class collation weights */ int weights; /* no. of class collation weights found */ int i; weights = cclass("digit", &list); printf("weights = %d\n", weights); for (i = 0; i < weights; i++) printf(" *(list + %d) = %d\n", i, *(list + i)); return 0; /**************************************************************************** The output should be similar to : weights = 10 *(list + 0) = 48 *(list + 1) = 49 *(list + 2) = 50 *(list + 3) = 51 *(list + 4) = 52 *(list + 5) = 53 *(list + 6) = 54 *(list + 7) = 55 *(list + 8) = 56 *(list + 9) = 57 ****************************************************************************/ } ═══ Related Information ═══ Example of cclass  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  setlocale - Set Locale  strtocoll - Return Collating Element for String  wctype - Get Handle for Character Property Classification   ═══ 4.21. ceil - Find Integer >= Argument ═══ ═══ Format ═══ #include double ceil(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ceil computes the smallest integer that is greater than or equal to x. Return Value ceil returns the integer as a double value. ═══ 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.0 and -1.0, respectively. ************************************************************************/ #include #include int main(void) { double y,z; y = ceil(1.05); /* y = 2.0 */ printf("ceil( 1.05 ) = %5.f\n", y); z = ceil(-1.05); /* z = -1.0 */ printf("ceil( -1.05 ) = %5.f\n", z); return 0; /**************************************************************************** The output should be: ceil( 1.05 ) = 2 ceil( -1.05 ) = -1 ****************************************************************************/ } ═══ Related Information ═══ Example of ceil  floor - Integer <= Argument  fmod - Calculate Floating-Point Remainder  ═══ 4.22. _cgets - Read String of Characters from Keyboard ═══ ═══ Format ═══ #include char *_cgets(char *str); ═══ Description ═══ Language Level: Extension _cgets reads a string of characters directly from the keyboard and stores the string and its length in the location pointed to by str. _cgets 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. _cgets 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. Return Value If successful, _cgets returns a pointer to the actual start of the string, str[2]. Otherwise, _cgets returns NULL. ═══ 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 _cgets and displays the size and text of that string. ************************************************************************/ #include #include void nothing(void) { } int main(void) { char buffer[82] = { 84,0 }; char *buffer2; int i; _cputs("\nPress any key to continue."); printf("\n"); while (0 == _kbhit()) { nothing(); } _getch(); _cputs("\nEnter a line of text:"); printf("\n"); buffer2 = _cgets(buffer); printf("\nText entered was: %s", buffer2); return 0; /**************************************************************************** The output should be similar to: Press any key to continue. Enter a line of text: This is a simple test. Text entered was: This is a simple test. ****************************************************************************/ } ═══ Related Information ═══ Example of _cgets  _cputs - Write String to Screen  fgets - Read a String  gets - Read a Line  _getch - _getche - Read Character from Keyboard  ═══ 4.23. chdir - Change Current Working Directory ═══ ═══ Format ═══ #include int chdir(char *pathname); ═══ Description ═══ Language Level: XPG4, Extension chdir 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. Note: In earlier releases of C Set ++, chdir began with an underscore (_chdir). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _chdir to chdir for you. Return Value chdir returns a value of 0 if the working directory was successfully changed. A return value of -1 indicates an error; 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 ═══ /************************************************************************ 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; /**************************************************************************** If directory \red\green\blue exists, the output should be: Changing to the root directory. Changed to the root directory. Changing to directory '\red\green\blue'. Changed to directory '\red\green\blue'. ****************************************************************************/ } ═══ Related Information ═══ Example of chdir  _chdrive - Change Current Working Drive  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  _getdrive - Get Current Working Drive  system - Invoke the Command Processor  mkdir - Create New Directory  rmdir - Remove Directory  system - Invoke the Command Processor  ═══ 4.24. _chdrive - Change Current Working Drive ═══ ═══ Format ═══ #include int _chdrive(int drive); ═══ Description ═══ Language Level: Extension _chdrive 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 Control Program Guide and Reference. Return Value _chdrive returns 0 if it is successful in changing the working drive. A return value of -1 indicates an error; _chdrive sets errno to EOS2ERR. ═══ 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 ═══ Example of _chdrive  chdir - Change Current Working Directory  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  _getdrive - Get Current Working Drive  mkdir - Create New Directory  rmdir - Remove Directory  ═══ 4.25. chmod - Change File Permission Setting ═══ ═══ Format ═══ #include #include int chmod(char *pathname, int pmode); ═══ Description ═══ Language Level: XPG4, Extension chmod changes the permission setting of the file specified by pathname. The permission setting controls access to the file for reading or writing. You can use chmod only if the file is closed. The pmode expression contains one or both of the constants S_IWRITE and S_IREAD, defined in . The meanings of the values of pmode 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, chmod 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. Note: In earlier releases of C Set ++, chmod began with an underscore (_chmod). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _chmod to chmod for you. Return Value chmod returns the value 0 if it successfully changes the permission setting. A return value of -1 shows an error; chmod sets 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 ═══ /************************************************************************ 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 : 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 ═══ Example of chmod  access - Determine Access Mode  _sopen - Open Shared File  umask - Sets File Mask of Current Process   ═══ 4.26. _chsize - Alter Length of File ═══ ═══ Format ═══ #include int _chsize(int handle, long size); ═══ Description ═══ Language Level: Extension _chsize 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. _chsize 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. Return Value _chsize returns the value 0 if it successfully changes the file size. A return value of -1 shows an error; _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 ═══ /************************************************************************ 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 EXIT_FAILURE; } if (-1 == (length = filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return EXIT_FAILURE; } 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 EXIT_FAILURE; } if (-1 == (length = _filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return EXIT_FAILURE; } 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 ═══ Example of _chsize  _filelength - Determine File Length  lseek - Move File Pointer  ═══ 4.27. clearerr - Reset Error Indicators. ═══ ═══ Format ═══ #include void clearerr (FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 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. fseek also clears the end-of-file indicator. Return Value There is no return value. ═══ 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 (NULL != (stream = fopen("file.dat", "r"))) { if (EOF == (c = getc(stream))) { if (feof(stream)) { perror("Read error"); clearerr(stream); } } } return 0; /**************************************************************************** If file.dat is an empty file, the output should be: Read error: Attempted to read past end-of-file. ****************************************************************************/ } ═══ Related Information ═══ Example of clearerr  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  perror - Print Error Message  rewind - Adjust Current File Position  strerror - Set Pointer to Runtime Error Message  _strerror - Set Pointer to System Error String  ═══ 4.28. _clear87 - Clear Floating-Point Status Word ═══ ═══ Format ═══ #include /* also in */ unsigned int _clear87(void); ═══ Description ═══ Language Level: Extension _clear87 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. _clear87 affects only the current thread. It does not affect any other threads that may be processing. Return Value The bits in the value returned reflect the floating-point status before the call to _clear87 was made. ═══ 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. _clear87 gets the current floating-point status word and then clears it, and printf 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, _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 output should be: floating-point status = 0x0030 after underflow cleared floating-point status word = 0x0000 floating-point status = 0x0002 for denormal ****************************************************************************/ } ═══ Related Information ═══ Example of _clear87  _control87 - Set Floating-Point Control Word  _status87 - Get Floating-Point Status Word  _fpreset - Reset Floating-Point Unit  ═══ 4.29. clock - Determine Processor Time ═══ ═══ Format ═══ #include clock_t clock(void); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 clock 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. Return Value 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 clock at the start of the program, and subtract its return value from the value returned by subsequent calls to clock. ═══ Example of clock ═══ /************************************************************************ This example prints the time elapsed since the program was invoked. ************************************************************************/ #include #include double time1,time2,timedif; /* use doubles to show small values */ int i; int main(void) { time1 = (double)clock(); /* get initial time in seconds */ time1 = time1/CLOCKS_PER_SEC; /* use some CPU time */ for (i = 0; i < 5000000; i++) { int j; j = i; } time2 = (double)clock(); /* call clock a second time */ time2 = time2/CLOCKS_PER_SEC; timedif = time2-time1; printf("The elapsed time is %f seconds\n", timedif); return 0; /**************************************************************************** The output should be similar to: The elapsed time is 0.969000 seconds ****************************************************************************/ } ═══ Related Information ═══ Example of clock  difftime - Compute Time Difference  time - Determine Current Time  ═══ 4.30. close - Close File Associated with Handle ═══ ═══ Format ═══ #include int close(int handle); ═══ Description ═══ Language Level: XPG4, Extension close 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. Note: In earlier releases of C Set ++, close began with an underscore (_close). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _close to close for you. Return Value close 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 ═══ /************************************************************************ This example opens the file edclose.dat and then closes it using the close function. ************************************************************************/ #include #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 EXIT_FAILURE; } printf("File was successfully opened.\n"); if (-1 == close(fh)) { perror("Unable to close edclose.dat"); return EXIT_FAILURE; } printf("File was successfully closed.\n"); return 0; /**************************************************************************** The output should be: Creating edclose.dat. File was successfully opened. File was successfully closed. ****************************************************************************/ } ═══ Related Information ═══ Example of close  fclose - Close Stream  creat - Create New File  open - Open File  _sopen - Open Shared File  ═══ 4.31. collequiv - Return List of Equivalent Collating Elements ═══ ═══ Format ═══ #include int collequiv(collel_t c, collel_t **list); ═══ Description ═══ Language Level: Extension collequiv finds all the collating elements that have the same primary weight as c, and stores them in an array. (The primary weight is the initial value used to determine how the character is collated or ordered.) It then updates the list to point to the first element of the array of found collating elements. The list of elements is valid until the next call to setlocale with categories LC_ALL, LC_COLLATE, or LC_CTYPE. Another call to collequiv could override the current list. Note: 1. If c has the weight IGNORE in the LC_COLLATE category, the list created contains all the characters specified as IGNORE. 2. The list contains only characters defined in the charmap file in the current locale. 3. The list is built statically in the locale, and is freed when the locale is deleted. Return Value collequiv returns the number of collating elements with the equivalent weight. If the value of c is not in the valid range of collating elements in the current locale, collequiv returns -1. ═══ Example of collequiv ═══ /************************************************************************ This example prints the collating elements that have an equivalent weight as the collating element passed in argv[1]. ************************************************************************/ #include #include #include #include int main(int argc, char *argv[]) { collel_t e, *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); if ((collel_t)-1 == (e = strtocoll(argv[1]))) { printf("'%s' collating element not defined\n", argv[1]); exit(1); } if (-1 == (i = collequiv(e, &rp))) { printf("Invalid collating element '%s'\n", argv[1]); exit(1); } for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** Assuming you compile this example as collequi.exe and invoke it as: collequi * The output should be: '*' 'Du ' 'Des ' 'De ' 'D'' 'Les ' 'Le ' 'La ' 'L'' 'du ' 'des ' 'de ' 'd'' 'les ' 'le ' 'la ' 'l'' ****************************************************************************/ } ═══ Related Information ═══ Exampleof collequiv  cclass - Return Characters in Character Class  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.32. collorder - Return List of Collating Elements ═══ ═══ Format ═══ #include int collorder(collel_t **list); ═══ Description ═══ Language Level: Extension collorder finds the number of collating elements in the collate order list and sets list to point to the collate order list. The list returned is valid until another call to setlocale. Note: 1. Collating elements specified with the weight of IGNORE in the LC_COLLATE category are defined as having the lowest weight. 2. The list contains only characters defined in the charmap file in the current locale. 3. The list is built statically in the locale, and is freed when the locale is deleted. Return Value collorder returns the number of collating elements in the collate order list. ═══ Example of collorder ═══ /************************************************************************ This example uses collorder to create a list of all the collating elements. ************************************************************************/ #include #include #include #include int main(void) { collel_t *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); i = collorder(&rp); for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** The output should be similar to : : : ' ' '!' '"' '#' '$' '%' '&' '(' ''' ')' '-' '*' 'Du ' 'Des ' 'De ' 'D'' 'Les ' 'Le ' 'La ' 'L'' 'du ' 'des ' 'de ' 'd'' 'les ' 'le ' 'la ' 'l'' '+' ',' '.' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' '>' '?' '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '[' '\' ']' '^' '_' : ****************************************************************************/ } ═══ Related Information ═══ Example  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.33. collrange - Calculate Range of Collating Elements ═══ ═══ Format ═══ #include int collrange(collel_t start, collel_t end, collel_t **list); ═══ Description ═══ Language Level: Extension collrange finds the collating elements whose primary weights are between the start and end elements, inclusive, and stores them in an array. It then updates list to point to the array of found collating elements. The list is valid until the next call to setlocale. Note: 1. Collating elements specified with the weight of IGNORE in the LC_COLLATE category are defined as having the lowest weight. Therefore, such elements can only be specified as the starting collating element. 2. The list contains only characters defined in the charmap file in the current locale. 3. The list is built statically in the locale and is freed when the locale is deleted. Return Value collrange returns the number of elements that fall between the range of weights. If the end point collates earlier than the start point, collrange returns 0. If either start or end are out of range, collrange returns -1. It does not set errno. ═══ Example of collrange ═══ /************************************************************************ This example uses collrange to print the collating elements in the range passed in argv[1] and argv[2]. ************************************************************************/ #include #include #include #include int main(int argc, char *argv[]) { collel_t s, e, *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); if ((collel_t)-1 == (s = strtocoll(argv[1]))) { printf("'%s' collating element not defined\n", argv[1]); exit(1); } if ((collel_t)-1 == (e = strtocoll(argv[2]))) { printf("'%s' collating element not defined\n", argv[2]); exit(1); } if (-1 == (i = collrange(s, e, &rp))) { printf("Invalid range for '%s' to '%s'\n", argv[1], argv[2]); exit(1); } for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** Assuming you compile this example as collrang.exe and invoke it as: collrang A z The output should be: 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '[' '\' ']' '^' '_' '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' ****************************************************************************/ } ═══ Related Information ═══ Example  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.34. colltostr - Return String for Collating Element ═══ ═══ Format ═══ #include char *colltostr(collel_t c); ═══ Description ═══ Language Level: Extension colltostr is the inverse of strtocoll; it converts the collating element c to the string for that collating element. You could use the returned array from collrange or collequiv and call ismccollel for each element, only calling colltostr if ismccollel is true for the element. The string returned is valid until another call to setlocale. Note: The string is built statically in the locale and is freed when the locale is deleted. Return Value colltostr returns the string for the collating element. If c is a single character or out of range, colltostr returns NULL. ═══ Example of colltostr ═══ /************************************************************************ This example prints all the collating elements in the collating sequence, using colltostr to get the string for the multi-character collating elements. ************************************************************************/ #include #include #include #include int main(void) { collel_t *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); i = collorder(&rp); for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** The output should be similar to : : : ' ' '!' '"' '#' '$' '%' '&' '(' ''' ')' '-' '*' 'Du ' 'Des ' 'De ' 'D'' 'Les ' 'Le ' 'La ' 'L'' 'du ' 'des ' 'de ' 'd'' 'les ' 'le ' 'la ' 'l'' '+' ',' '.' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' '>' '?' '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '[' '\' ']' '^' '_' : ****************************************************************************/ } ═══ Related Information ═══ Example  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.35. _control87 - Set Floating-Point Control Word ═══ ═══ Format ═══ #include /* also in */ unsigned int _control87(unsigned int new, unsigned int mask); ═══ Description ═══ Language Level: Extension _control87 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 _control87. 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. _control87 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:  The behavior of the math functions with regard to domain and range errors may be undefined.  Math functions may not handle infinity and NaN values correctly.  Some floating-point exceptions may not occur, while other new ones may occur.  Resetting the EM_INEXACT bit may cause SIG_FPE exceptions, which decrease performance.  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 User's Guide. Return Value The bits in the returned value reflect the floating-point control word before the call. ═══ 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; /**************************************************************************** The output should be similar to: control = 0x0362 a*a = .0169 = 1.690000000000000e-02 a*a = .0169 (rounded to 24 bits) = 1.690000057220459e-02 a*a = .0169 = 1.690000000000000e-02 ****************************************************************************/ } ═══ Related Information ═══ Example of _control87  _clear87 - Clear Floating-Point Status Word  _status87 - Get Floating-Point Status Word  _fpreset - Reset Floating-Point Unit  Floating Point Variables  signal - Handle Interrupt Signals  ═══ 4.36. cos - Calculate Cosine ═══ ═══ Format ═══ #include double cos(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 cos 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. Return Value cos returns the cosine of x. ═══ Example of cos ═══ /************************************************************************ This example calculates y to be the cosine of x. ************************************************************************/ #include int main(void) { double x,y; x = 7.2; y = cos(x); printf("cos( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be: cos( 7.200000 ) = 0.608351 ****************************************************************************/ } ═══ Related Information ═══ Example of cos  acos - Calculate Arccosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.37. cosh - Calculate Hyperbolic Cosine ═══ ═══ Format ═══ #include double cosh(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 cosh calculates the hyperbolic cosine of x. The value x is expressed in radians. Return Value cosh returns the hyperbolic cosine of x. If the result is too large, cosh returns the value HUGE_VAL and sets errno to ERANGE. ═══ Example of cosh ═══ /************************************************************************ This example calculates y to be the hyperbolic cosine of x. ************************************************************************/ #include int main(void) { double x,y; x = 7.2; y = cosh(x); printf("cosh( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be: cosh( 7.200000 ) = 669.715755 ****************************************************************************/ } ═══ Related Information ═══ Example of cosh  acos - Calculate Arccosine  cos - Calculate Cosine  _facos - Calculate Arccosine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.38. _cprintf - Print Characters to Screen ═══ ═══ Format ═══ #include int _cprintf(char *format-string, argument-list); ═══ Description ═══ Language Level: Extension _cprintf 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. Return Value _cprintf returns the number of characters printed. ═══ 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 filename:\n"); _cscanf("%23s", buffer); _cprintf("\nThe file name you entered was %23s.", buffer); return 0; /**************************************************************************** The output should be similar to : Please enter a filename: file.dat The filename you entered was file.dat. ****************************************************************************/ } ═══ Related Information ═══ Example of _cprintf  _cscanf - Read Data from Keyboard  fprintf - Write Formatted Data to a Stream  printf - Print Formatted Characters  _putch - Write Character to Screen  sprintf - Print Formatted Data to Buffer  ═══ 4.39. _cputs - Write String to Screen ═══ ═══ Format ═══ #include int _cputs(char *str); ═══ Description ═══ Language Level: Extension _cputs writes the string that str points to directly to the screen. 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. Return Value If successful, _cputs returns 0. Otherwise, it returns a nonzero value. ═══ Example of _cputs ═══ /************************************************************************ This example outputs a prompt 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: Insert data disk in drive a: ****************************************************************************/ } ═══ Related Information ═══ Example of _cputs  _cgets - Read String of Characters from Keyboard  fputs - Write String  _putch - Write Character to Screen  puts - Write a String  ═══ 4.40. creat - Create New File ═══ ═══ Format ═══ #include #include int creat(char *pathname, int pmode); ═══ Description ═══ Language Level: XPG4, Extension creat 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 it 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 action destroys the previous contents of the file and opens it for writing in text mode. creat 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, it 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. Note: In earlier releases of C Set ++, creat began with an underscore (_creat). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _creat to creat for you. Return Value creat 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 ═══ /************************************************************************ This example creates the file sample.dat so it can be read from and written to. ************************************************************************/ #include #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 EXIT_FAILURE; } else printf("Successfully created sample.dat.\n"); close(fh); return 0; /**************************************************************************** The output should: Successfully created sample.dat. ****************************************************************************/ } ═══ Related Information ═══ Example of creat  chmod - Change File Permission Setting  close - Close File Associated with Handle  open - Open File  fdopen - Associates Input Or Output With File  _sopen - Open Shared File  umask - Sets File Mask of Current Process   ═══ 4.41. _crotl - _crotr - Rotate Bits of Character Value ═══ ═══ Format ═══ #include /* also in */ unsigned char _crotl(unsigned char value, int shift); unsigned char _crotr(unsigned char value, int shift); ═══ Description ═══ Language Level: Extension The _crotl and _crotr functions rotate the character value by shift bits. The _crotl function rotates to the left, and _crotr to the right. Note: Both _crotl and _crotr are built-in functions, which means they are implemented as inline instructions and have no backing code in the library. For this reason:  You cannot take the address of these functions.  You cannot parenthesize a call to either function. (Parentheses specify a call to the function's backing code, and these functions have none.) Return Value Both functions return the rotated value. There is no error return value. ═══ Example of _crotl - _crotr ═══ /************************************************************************ This example uses _crotl and _crotr with different shift values to rotate the character value: ************************************************************************/ #include #include int main(void) { unsigned char val = 0X01; printf("The value of 0x%2.2x rotated 4 bits to the left is 0x%2.2x\n", val, _crotl(val, 4)); printf("The value of 0x%2.2x rotated 2 bits to the right is 0x%2.2x\n", val, _crotr(val, 2)); return 0; /**************************************************************************** The output should be: The value of 0x01 rotated 4 bits to the left is 0x10 The value of 0x01 rotated 2 bits to the right is 0x40 ****************************************************************************/ } ═══ Related Information ═══ Example of _crotl - _crotr  _lrotl - _lrotr - Rotate Bits of Unsigned Long Value  _rotl - _rotr - Rotate Bits of Unsigned Integer  _srotl - _srotr - Rotate Bits of Unsigned Short Value   ═══ 4.42. _CRT_init - Initialize DLL Runtime Environment ═══ ═══ Format ═══ int _CRT_init(void); /* no header file - defined in the runtime startup code */ ═══ Description ═══ Language Level: Extension _CRT_init initializes the VisualAge C++ runtime environment for a DLL. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn calls _CRT_init for you. However, if you are writing your own _DLL_InitTerm function (for example, to perform actions other than runtime initialization and termination), you must call _CRT_init from your version of _DLL_InitTerm before you can call any other runtime functions. If your DLL contains C++ code, you must also call __ctordtorInit after _CRT_init to ensure that static constructors and destructors are initialized properly. __ctordtorInit is defined in the runtime startup code as: void __ctordtorInit(void); Note: If you are providing your own version of the _matherr function to be used in your DLL, you must also 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. _exception_dllinit is defined in the runtime startup code as: void _Optlink _exception_dllinit( int (*)(struct exception *) ); The parameter required is the address of your _matherr function. Return Value 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. ═══ Example of _CRT_init ═══ /************************************************************************ This example shows the _DLL_InitTerm function from the VisualAge C++ sample program for building DLLs, which calls _CRT_init to initialize the library environment. ************************************************************************/ #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 ═══ Related Information ═══ Example of _CRT_init  Building Dynamic Link Libraries in the Programming Guide  _CRT_term - Terminate DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.43. _CRT_term - Terminate DLL Runtime Environment ═══ ═══ Format ═══ void _CRT_term(void); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _CRT_term terminates the VisualAge C++ runtime environment. It is only needed for DLLs where the C runtime functions are statically linked. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn calls _CRT_term for you. However, if you are writing your own _DLL_InitTerm function (for example, to perform actions other than runtime initialization and termination), and your DLL statically links to the C runtime libraries, you need to call _CRT_term from your _DLL_InitTerm function. 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. __ctordtorTerm is defined in the runtime startup code as: 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. Return Value There is no return value for _CRT_term. ═══ Example of _CRT_term ═══ /************************************************************************ This example shows the _DLL_InitTerm function from the VisualAge C++ sample program for building DLLs, which calls _CRT_term to terminate the library environment. ************************************************************************/ #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 ═══ Related Information ═══ Example of _CRT_term  Building Dynamic Link Libraries in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.44. csid - Determine Character Set ID for Multibyte Character ═══ ═══ Format ═══ #include int csid(const char *c); ═══ Description ═══ Language Level: Extension csid queries the locale and determines the character-set identifier for the specified character c. Return Value csid returns the character-set identifier, or -1 if the character is not valid. ═══ Example of csid ═══ /************************************************************************ This example checks the character-set ID for a character. ************************************************************************/ #include #include #include int main(void) { char *string = "A"; int rc; rc = csid(string); printf("character '%s' is in character set id %i\n", string, rc); return 0; /**************************************************************************** The output should be similar to : character 'A' is in character set id 0 ****************************************************************************/ } ═══ Related Information ═══ Example of csid  wcsid - Determine Character Set ID for Wide Character  ═══ 4.45. _cscanf - Read Data from Keyboard ═══ ═══ Format ═══ #include int _cscanf(char *format-string, argument-list); ═══ Description ═══ Language Level: Extension _cscanf 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. Return Value _cscanf 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 ═══ /************************************************************************ This example uses _cscanf to read strings from the screen. ************************************************************************/ #include int main(void) { char buffer[24]; _cprintf("\nPlease enter a filename:\n"); _cscanf("%23s", buffer); _cprintf("\nThe file name you entered was %23s.", buffer); return 0; /**************************************************************************** The output should be similar to : Please enter a filename: file.dat The filename you entered was file.dat. ****************************************************************************/ } ═══ Related Information ═══ Example of _cscanf  fscanf - Read Formatted Data  _getch - _getche - Read Character from Keyboard  scanf - Read Data  sscanf - Read Data  _ungetch - Push Character Back to Keyboard  ═══ 4.46. ctime - Convert Time to Character String ═══ ═══ Format ═══ #include char *ctime(const time_t *time); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ctime 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 ctime 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 with 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. Return Value ctime returns a pointer to the character string result. There is no error return value. A call to ctime is equivalent to: asctime(localtime(&anytime)) 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. ═══ Example of ctime ═══ /************************************************************************ This example polls the system clock using ctime. 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)); return 0; /**************************************************************************** The output should be similar to : The time is Thu Dec 15 18:10:23 1994 ****************************************************************************/ } ═══ Related Information ═══ Example of ctime  asctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  strftime - Convert to Formatted Time  time - Determine Current Time  ═══ 4.47. _cwait - Wait for Child Process ═══ ═══ Format ═══ #include int _cwait(int *stat_loc, int process_id, int action_code); ═══ Description ═══ Language Level: Extension _cwait 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, _cwait 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 pointed to by stat_loc. 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. Return Value 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 ═══ /************************************************************************ 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 (0 == errno) { 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"); return 0; } 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 ═══ Example of cwait  exit - End Program  _exit - End Process  _spawnl - _spawnvpe - Start and Run Child Processes  wait - Wait for Child Process  return  ═══ 4.48. __cxchg - Exchange Character Value with Memory ═══ ═══ Format ═══ #include signed char _Builtin __cxchg(volatile signed char *lockptr, signed char value); ═══ Description ═══ Language Level: Extension __cxchg puts the specified value in the memory location pointed to by lockptr, and returns the value that was previously in that location. Use this function to implement fast-RAM semaphores to serialize access to a critical resource (so that only one thread can use it at a time). You can also use OS/2 semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and an OS/2 semaphore for the resource. For more details about OS/2 semaphores and how to use them, see the Control Program Guide and Reference. To implement a fast-RAM semaphore, allocate a volatile memory location (for __cxchg, it must be a signed char), and statically initialize it to 0 to indicate that the resource is free (not being used). To give a thread access to the resource, call __cxchg from the thread to exchange a nonzero value with that memory location. If __cxchg returns 0, the thread can access the resource; it has also set the memory location so that other threads can tell the resource is in use. When your thread no longer needs the resource, call __cxchg again to reset the memory location to 0. If __cxchg returns a nonzero value, another thread is already using the resource, and the calling thread must wait for access. You could then use the OS/2 semaphore to inform your waiting thread when the resource is unlocked by the thread currently using it. It is important that you set the memory to a nonzero value when you are using the resource. You can use the same nonzero value for all threads, or a unique value for each. Note: __cxchg is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of __cxchg.  You cannot parenthesize a call to __cxchg. (Parentheses specify a call to the function's backing code, and __cxchg has none.) Return Value __cxchg returns the previous value stored in the memory location pointed to by lockptr. ═══ Example of __cxchg ═══ /************************************************************************ This example creates five separate threads, each associated with a State. At most two threads can have a State of Eating at the same time. When a thread calls PickUpChopSticks, that function checks the states of the preceding threads to make sure they are not already Eating, If the call to __cxchg is successful, the thread has locked the Lock semaphore and can change its State to Eating. It then calls __cxchg a second time to unlock the semaphore, and returns. If __cxchg cannot lock the semaphore, another thread has it locked. The current thread then suspends itself briefly with DosSleep and tries again. The semaphore is used to ensure that two threads cannot simultaneously change their State to Eating, which would cause a deadlock. (Note that although the semaphore solves the problem of deadlock, it is not an optimal solution; some threads may never get the semaphore or the State of Eating.) Note: You must compile this example with the multithread (/Gm) option. The example runs in an infinite loop; press Ctrl-C to end it. ************************************************************************/ #pragma strings(readonly) #define INCL_DOS #include #include #include #include typedef enum { Thinking, Eating, Hungry } States; #define UNLOCKED 0 #define LOCKED 1 #define NUM_PHILOSOPHERS 5 static volatile signed char Lock; static States State[NUM_PHILOSOPHERS]; static const int NameMap[NUM_PHILOSOPHERS] = {0, 1, 2, 3, 4}; static const char * const Names[NUM_PHILOSOPHERS] = {"Plato", "Socrates", "Kant", "Hegel", "Nietsche"}; void PickUpChopSticks(int Ident); void PutDownChopSticks(int Ident); void Think(int Ident); void Eat(int Ident); void _Optlink StartPhilosopher(void *pIdent); void _Optlink StartPhilosopher(void *pIdent) { int Ident = *(int *)pIdent; while (1) { State[Ident] = Hungry; printf("%s hungry.\n", Names[Ident]); PickUpChopSticks(Ident); Eat(Ident); PutDownChopSticks(Ident); Think(Ident); } } int main(int argc, char *argv[], char *envp[]) { int i; unsigned long tid; for (i = 0; i < NUM_PHILOSOPHERS; i++) { tid = _beginthread(StartPhilosopher, NULL, 8192, (void *)&NameMap[i]); if (tid == -1) { printf("Unable to start %s.\n", Names[i]); } else { printf("%s started with Thread Id = %d.\n", Names[i], tid); } } DosWaitThread(&tid, DCWW_WAIT); return 0; } void PickUpChopSticks(int Ident) { while (1) { if (State[(Ident + NUM_PHILOSOPHERS - 1) % NUM_PHILOSOPHERS] != Eating && State[(Ident + 1) % NUM_PHILOSOPHERS] != Eating && !__cxchg(&Lock, LOCKED)) { State[Ident] = Eating; __cxchg(&Lock, UNLOCKED); return; } else { DosSleep(1); } } } void PutDownChopSticks(int Ident) { State[Ident] = Thinking; } void Eat(int Ident) { printf("%s eating.\n", Names[Ident]); DosSleep(1); } void Think(int Ident) { printf("%s thinking.\n", Names[Ident]); DosSleep(1); } /**************************************************************************** The output should be similar to : Plato started with Thread Id = 2. Socrates started with Thread Id = 3. Kant started with Thread Id = 4. Hegel started with Thread Id = 5. Nietsche started with Thread Id = 6. Plato hungry. Plato eating. Socrates hungry. Kant hungry. Kant eating. Hegel hungry. Nietsche hungry. Kant thinking. Plato thinking. Plato hungry. Plato eating. Kant hungry. Kant eating. : ****************************************************************************/ ═══ Related Information ═══ Exampleof __cxchg  __lxchg - Exchange Integer Value with Memory  __sxchg - Exchange Integer Value with Memory  ═══ 4.49. _debug_calloc - Allocate and Initialize Memory ═══ ═══ Format ═══ #include /* also in */ void *_debug_calloc(size_t num, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_calloc is the debug version of calloc. Like calloc, it allocates memory from the default heap for an array of num elements, each of length size bytes. It then initializes all bits of each element to 0. In addition, _debug_calloc makes an implicit call to _heap_check, and stores the name of the file file and the line number line where the storage is allocated. This information can be used later by the _heap_check and _dump_allocated or _dump_allocated_delta functions. To use _debug_calloc, you must compile with the debug memory (/Tm) compiler option. This option maps all calloc calls to _debug_calloc (you can also call _debug_calloc explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. To reallocate or free memory allocated by _debug_calloc, use _debug_realloc and _debug_free; you can also use realloc and free if you do not want debug information about the operation. Heap-specific and tiled versions of this function (_debug_ucalloc and _debug_tcalloc) are also available. _debug_calloc always allocates memory from the default heap. Return Value _debug_calloc returns a pointer to the reserved space. If not enough memory is available, or if num or size is 0, _debug_calloc returns NULL. ═══ Example of _debug_calloc ═══ /************************************************************************ This example reserves storage of 100 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: You must compile this example with the /Tm option to map the calloc calls to _debug_calloc. ************************************************************************/ #include #include #include int main(void) { char *ptr1, *ptr2; if (NULL == (ptr1 = calloc(1, 100))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr1, 'a', 105); /* overwrites storage that was not allocated */ ptr2 = calloc(2, 20); /* this call to calloc invokes _heap_check */ puts("_debug_calloc did not detect that a memory block was overwritten."); return 0; /**************************************************************************** The output should be similar to: End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 6161616161616161. This memory block was (re)allocated at line number 9 in _debug_callo.c. Heap state was valid at line 9 of _debug_callo.c. Memory error detected at line 14 of _debug_callo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_calloc  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions    calloc - Reserve and Initialize Storage  _debug_ucalloc - Reserve and Initialize Memory from User Heap  _debug_free - Release Memory  _debug_malloc - Allocate Memory  _debug_realloc - Reallocate Memory Block  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heap_check - Validate Default Memory Heap ═══ 4.50. _debug_free - Release Memory ═══ ═══ Format ═══ #include /* also in */ void _debug_free(void *ptr, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_free is the debug version of free. Like free, it frees the block of memory pointed to by ptr. _debug_free also sets each block of freed memory to 0xFB, so you can easily locate instances where your program uses the data in freed memory. In addition, _debug_free makes an implicit call to the _heap_check, and stores the file name file and the line number line where the memory is freed. This information can be used later by the _heap_check and _dump_allocated or _dump_allocated_delta functions. To use _debug_free, you must compile with the debug memory (/Tm) compiler option. This option maps all free calls to _debug_free (you can also call _debug_free explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Because _debug_free always checks what heap the memory was allocated from, you can use _debug_free to free memory blocks allocated by the regular, tiled, heap-specific, or debug versions of the memory management functions. However, if the memory was not allocated by the memory management functions, or was previously freed, _debug_free generates an error message and the program ends. A tiled version of this function, _debug_tfree, is also available. Return Value There is no return value. ═══ Example of _debug_free ═══ /************************************************************************ This example reserves two blocks, one of 10 bytes and the other of 20 bytes. 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: You must compile this example with the /Tm option to map the free calls to _debug_free. ************************************************************************/ #include #include int main(void) { char *ptr1, *ptr2; if (NULL == (ptr1 = malloc(10)) || NULL == (ptr2 = malloc(20))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } free(ptr1); memset(ptr1, 'a', 5); /* overwrites storage that has been freed */ free(ptr2); /* this call to free invokes _heap_check */ puts("_debug_free did not detect that a freed memory block was overwritten."); return 0; /**************************************************************************** The output should be similar to: Free heap was overwritten at 0x00073890. Heap state was valid at line 12 of _debug_free.c. Memory error detected at line 14 of _debug_free.c. ****************************************************************************/ } ═══ Information ═══ Example of _debug_free  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_malloc - Allocate Memory  _debug_realloc - Reallocate Memory Block  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  free - Release Storage Blocks  _heap_check - Validate Default Memory Heap   ═══ 4.51. _debug_heapmin - Release Unused Memory in the Default Heap ═══ ═══ Format ═══ #include /* also in */ int _debug_heapmin(const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_heapmin is the debug version of _heapmin. Like _heapmin, It returns all unused memory from the default runtime heap to the operating system. In addition, _debug_heapmin makes an implicit call to _heap_check, and stores the file name file and the line number line where the memory is returned. This information can be used later by the _heap_check function. To use _debug_heapmin, you must compile with the debug memory (/Tm) compiler option. This option maps all _heapmin calls to _debug_heapmin (you can also call _debug_heapmin explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Heap-specific and tiled versions of this function (_debug_uheapmin and _debug_theapmin) are also available. _debug_heapmin always operates on the default heap. Return Value If successful, _debug_heapmin returns 0; otherwise, it returns -1. ═══ Example of _debug_heapmin ═══ /************************************************************************ This example allocates 10000 bytes of storage, changes the storage size to 10 bytes, and then uses _debug_heapmin to return the unused memory to the operating system. The program then attempts to overwrite memory that was not allocated. When _debug_heapmin is called again, _heap_check detects the error, generates several messages, and stops the program. Note: You must compile this example with the /Tm option to map the _heapmin calls to _debug_heapmin. ************************************************************************/ #include #include int main(void) { char *ptr; /* Allocate a large object from the system */ if (NULL == (ptr = malloc(100000))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } ptr = realloc(ptr, 10); _heapmin(); /* No allocation problems to detect */ *(ptr - 1) = 'a'; /* Overwrite memory that was not allocated */ _heapmin(); /* This call to _heapmin invokes _heap_check */ puts("_debug_heapmin did not detect that a non-allocated memory block" "was overwritten."); return 0; /**************************************************************************** Possible output is: Header information of object 0x000738b0 was overwritten at 0x000738ac. The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA. This memory block was (re)allocated at line number 13 in _debug_heapm.c. Heap state was valid at line 14 of _debug_heapm.c. Memory error detected at line 17 of _debug_heapm.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_heapmin  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_heapmin - Release Unused Memory in the Default Heap  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heapmin - Release Unused Memory from Default Heap  _heap_check - Validate Default Memory Heap   ═══ 4.52. _debug_malloc - Allocate Memory ═══ ═══ Format ═══ #include /* also in */ void *_debug_malloc(size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_malloc is the debug version of malloc. Like malloc, it reserves a block of storage of size bytes from the default heap. _debug_malloc also sets all the memory it allocates to 0xAA, so you can easily locate instances where your program uses the data in the memory without initializing it first. In addition, _debug_malloc makes an implicit call to _heap_check, and stores the file name file and the line number line where the storage is allocated. This information can later be used by the _heap_check and _dump_allocated or _dump_allocated_delta functions. To use _debug_malloc, you must compile with the debug memory (/Tm) compiler option. This option maps all malloc calls to _debug_malloc (you can also call _debug_malloc explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. To reallocate or free memory allocated by _debug_malloc, use _debug_realloc and _debug_free; you can also use realloc and free if you do not want debug information about the operation. Heap-specific and tiled versions of this function (_debug_umalloc and _debug_tmalloc) are also available. _debug_malloc always allocates memory from the default heap. Return Value _debug_malloc returns a pointer to the reserved space. If not enough memory is available or if size is 0, _debug_malloc returns NULL. ═══ Example of _debug_malloc ═══ /************************************************************************ This example allocates 100 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: You must compile this example with the /Tm option to map the malloc calls to _debug_malloc. ************************************************************************/ #include #include int main(void) { char *ptr1, *ptr2; if (NULL == (ptr1 = malloc(100))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } *(ptr1 - 1) = 'a'; /* overwrites storage that was not allocated */ ptr2 = malloc(10); /* this call to malloc invokes _heap_check */ puts("_debug_malloc did not detect that a memory block was overwritten."); return 0; /**************************************************************************** Possible output is: Header information of object 0x00073890 was overwritten at 0x0007388c. The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA. This memory block was (re)allocated at line number 8 in _debug_mallo.c. Heap state was valid at line 8 of _debug_mallo.c. Memory error detected at line 13 of _debug_mallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_malloc  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_realloc - Reallocate Memory Block  _debug_umalloc - Reserve Memory Blocks from User Heap  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heap_check - Validate Default Memory Heap  malloc - Reserve Storage Block   ═══ 4.53. _debug_realloc - Reallocate Memory Block ═══ ═══ Format ═══ #include /* also in */ void *_debug_realloc(void *ptr, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_realloc is the debug version of realloc. Like realloc, it reallocates the block of memory pointed to by ptr to a new size, specified in bytes. It also sets any new memory it allocates to 0xAA, so you can easily locate instances where your program tries to use the data in that memory without initializing it first. In addition, _debug_realloc makes an implicit call to _heap_check, and stores the file name file and the line number line where the storage is reallocated. This information can be used later by the _heap_check and _dump_allocated or _dump_allocated_delta functions. If ptr is NULL, _debug_realloc behaves like _debug_malloc (or malloc) and allocates the block of memory. To use _debug_realloc, you must compile with the debug memory (/Tm) compiler option. This option maps all realloc calls to _debug_realloc (you can also call _debug_realloc explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Because _debug_realloc always checks what heap the memory was allocated from, you can use _debug_realloc to reallocate memory blocks allocated by the regular, tiled heap-specific, or debug versions of the memory management functions. However, if the memory was not allocated by the memory management functions, or was previously freed, _debug_realloc generates an error message and the program ends. A tiled version of this function, _debug_trealloc, is also available. Return Value _debug_realloc returns a pointer to the reallocated memory block. The ptr argument to _debug_realloc is not the same as the return value; _debug_realloc always changes the memory location to help you locate references to the memory that were not freed before the memory was reallocated. If size is 0, _debug_realloc returns NULL. If not enough memory is available to expand the block to the given size, the original block is unchanged and NULL is returned. ═══ Example of _debug_realloc ═══ /************************************************************************ This example uses _debug_realloc to allocate 100 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: You must compile this example with the /Tm option to map the realloc calls to _debug_realloc. ************************************************************************/ #include #include int main(void) { char *ptr; if (NULL == (ptr = realloc(NULL, 100))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr, 'a', 105); /* overwrites storage that was not allocated */ ptr = realloc(ptr, 200); /* this call to realloc invokes _heap_check */ puts("_debug_realloc did not detect that a memory block was overwritten." ); return 0; /**************************************************************************** The output should be similar to: End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 6161616161616161. This memory block was (re)allocated at line number 8 in _debug_reall.c. Heap state was valid at line 8 of _debug_reall.c. Memory error detected at line 13 of _debug_reall.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_realloc  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_malloc - Allocate Memory  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heap_check - Validate Default Memory Heap  realloc - Change Reserved Storage Block Size   ═══ 4.54. _debug_tcalloc - Reserve and Initialize Tiled Memory ═══ ═══ Format ═══ #include /* also in */ void *_debug_tcalloc(size_t num, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_tcalloc is the debug version of _tcalloc. Like _tcalloc, it allocates tiled memory from the tiled runtime heap for an array of num elements, each of length size bytes. It then initializes all bits of each element to 0. In addition, _debug_tcalloc makes an implicit call to _theap_check, and stores the name of the file file and the line number line where the storage is allocated. This information can be used later by the _theap_check and _tdump_allocated or _tdump_allocated_delta functions. To use _debug_tcalloc, you must compile with the debug memory and tiled memory compiler options (/Tm /Gt). These options map all calloc calls to _debug_tcalloc (you can also call _debug_tcalloc explicitly). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. To reallocate or free memory allocated with _debug_tcalloc, use _debug_trealloc and _debug_tfree; you can also use _trealloc and _tfree if you don't want debug information about the operation. _debug_tcalloc works just like _debug_calloc except that it allocates tiled memory instead of regular memory. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory is guaranteed not to cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. You can also create your own heaps of tiled memory. See "Managing Memory" in the Programming Guide for more information. Return Value _debug_tcalloc returns a pointer to the reserved space. If size or num was specified as zero, _debug_tcalloc returns NULL. ═══ Example of _debug_tcalloc ═══ /************************************************************************ This example reserves 100 bytes of tiled memory. It then attempts to write to storage that was not allocated. The second _debug_tcalloc call invokes _theap_check, which detects the error, generates several messages, and stops the program. Note: You must compile this program with the /Tm /Gt options to map the calloc calls to _debug_tcalloc *********************************************************************** / #include #include #include int main(void) { char *ptr; /* calloc is mapped to _debug_tcalloc */ if (NULL == (ptr = calloc(1, 100))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } memset (ptr, 'x', 105); /* Overwrites storage that was not allocated */ free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00080120 was overwritten at 0x00080184. The first eight bytes of the memory block (in hex) are: 7878787878787878. This memory block was (re)allocated at line number 10 in _debug_tcallo.c. Heap state was valid at line 10 of _debug_tcallo.c. Memory error detected at line 15 of _debug_tcallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_tcalloc  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Tiled Debug Functions  calloc - Reserve and Initialize Storage  _debug_calloc - Allocate and Initialize Memory  _debug_tfree - Release Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _theap_check - Validate User Memory Heap   ═══ 4.55. _debug_tfree - Release Tiled Memory ═══ ═══ Format ═══ #include /* also in */ void _debug_tfree(void *ptr, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_tfree is the debug version of _tfree. Like _tfree, it frees the block of tiled memory pointed to by ptr. _debug_tfree also sets each block of freed memory to 0xFB, so you can easily locate instances where your program uses the data in freed memory. In addition, _debug_tfree makes an implicit call to the _theap_check, and stores the file name file and the line number line where the memory is freed. This information can be used later by the _theap_check and _tdump_allocated or _tdump_allocated_delta functions. To use _debug_tfree, you must compile with the debug memory and tiled memory compiler options (/Tm /Gt). These options map all free calls to _debug_tfree (you can also call _debug_tfree explicitly). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. _debug_tfree works just like _debug_free except that it frees tiled memory instead of regular memory. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory is guaranteed not to cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. You can also create your own heaps of tiled memory. See "Managing Memory" in the Programming Guide for more information. Return Value There is no return value. ═══ Example of _debug_tfree ═══ /************************************************************************ This example allocates a 100-byte block of memory. It then frees the block twice. The second _debug_tfree call invokes _theap_check, which detects the error, generates several messages, and stops the program. Note: You must compile this example with the /Tm /Gt options to map the free calls to _debug_tfree. *********************************************************************** / #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(100))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } free(ptr); /* free the object */ free(ptr); /* free the object again should cause an error */ return 0; /**************************************************************************** The output should be similar to : Object 0x00080120 provided is either invalid or was overwritten at 0x0008011c. Memory error detected at line 13 of _debug_tfree.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_tfree  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Tiled Debug Functions  _debug_free - Release Memory  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  free - Release Storage Blocks  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _tfree - Free Tiled Storage Block  _theap_check - Validate User Memory Heap   ═══ 4.56. _debug_theapmin - Release Unused Tiled Memory ═══ ═══ Format ═══ #include /* also in */ int _debug_theapmin(const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_theapmin is the debug version of _theapmin. Like _theapmin, it returns all unused blocks of tiled memory to the tiled runtime heap. In addition, _debug_theapmin makes an implicit call to _theap_check to validate the heap. To use _debug_theapmin, you must compile with the debug memory and tiled memory compiler options (/Tm /Gt). These options map all _heapmin calls to _debug_theapmin (you can also call _debug_theapmin explicitly). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. _debug_theapmin works just like _debug_heapmin except that it releases only memory allocated with the tiled memory management functions. Return Value If successful, _debug_theapmin returns 0. A non-zero return value indicates failure. If the heap specified is not valid, _debug_theapmin generates an error message with the file name and line number where the call to _debug_theapmin was made. ═══ Example of _debug_theapmin ═══ /************************************************************************ This example allocates 60000 bytes of memory, then frees it. The freed memory is kept in the default runtime heap until the call to _debug_theapmin returns it to the operating system. Because no errors are detected by _theap_check, no messages are generated. Note: You must compile this example with the /Tm /Gt options to map the _heapmin calls to _debug_theapmin. *********************************************************************** / #include #include int main(void) { char *ptr; /* Allocate a large object from the system. */ if (NULL == (ptr = malloc(60000))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } memset(ptr, 'x', 60000); /* The free will keep large object in runtime. */ free(ptr); /* _debug_theapmin will attempt to return the freed object to the system. */ if (0 != _heapmin()) { puts("_debug_theapmin returns failed.\n"); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _debug_theapmin  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Tiled Debug Functions  _debug_heapmin - Release Unused Memory in the Default Heap  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _heapmin - Release Unused Memory from Default Heap  _theap_check - Validate User Memory Heap   ═══ 4.57. _debug_tmalloc - Reserve Tiled Memory ═══ ═══ Format ═══ #include /* also in */ void *_debug_tmalloc(size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_tmalloc is the debug version of _tmalloc. Like _tmalloc, it allocates tiled memory from the tiled runtime heap for an object of length size bytes. _debug_tmalloc also sets all the memory it allocates to 0xAA, so you can easily locate instances where your program uses the data in the memory without initializing it first. In addition, _debug_tmalloc makes an implicit call to _theap_check, and stores the name of the file file and the line number line where the storage is allocated. This information can be used later by the _theap_check and _tdump_allocated or _tdump_allocated_delta functions. To use _debug_tmalloc, you must compile with the debug memory and tiled memory compiler options (/Tm /Gt). These options map all malloc calls to _debug_tmalloc (you can also call _debug_tmalloc explicitly). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. _debug_tmalloc works just like _debug_malloc except that it allocates tiled memory instead of regular memory. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory is guaranteed not to cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. You can also create your own heaps of tiled memory. See "Managing Memory" in the Programming Guide for more information. To reallocate or free memory allocated with _debug_tmalloc, use _debug_trealloc and _debug_tfree; you can also use _trealloc and _tfree if you don't want debug information about the operation. Return Value _debug_tmalloc returns a pointer to the reserved space. If size was specified as zero, _debug_tmalloc returns NULL. ═══ Example of _debug_tmalloc ═══ /************************************************************************ This example allocates 100 bytes of memory, then tries to write to memory that was not allocated. The call to _debug_tfree invokes _theap_check, which detects the error, generates several messages, and stops the program. Note: You must compile this example with the /Tm /Gt options to map the free calls to _debug_tfree. *********************************************************************** / #include #include #include int main(void) { char *ptr; /* malloc is mapped to _debug_tmalloc */ if (NULL == (ptr = malloc(100))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } memset (ptr, 'x', 105); /* Overwrites storage that was not allocated */ free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00080120 was overwritten at 0x00080184. The first eight bytes of the memory block (in hex) are: 7878787878787878. This memory block was (re)allocated at line number 10 in _debug_tmallo.c. Heap state was valid at line 10 of _debug_tmallo.c. Memory error detected at line 15 of _debug_tmallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_tmalloc  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Tiled Debug Functions  _debug_malloc - Allocate Memory  _debug_tfree - Release Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  malloc - Reserve Storage Block  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _theap_check - Validate User Memory Heap   ═══ 4.58. _debug_trealloc - Reallocate Tiled Memory Block ═══ ═══ Format ═══ #include /* also in */ void *_debug_trealloc(void *ptr, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension The _debug_trealloc function is the debug version of _trealloc. Like _trealloc, it reallocates the block of tiled memory pointed to by ptr to a new size, specified in bytes. The block of memory must have been allocated using a tiled memory management function. _debug_trealloc also sets any new memory it allocates to 0xAA, so you can easily locate instances where your program tries to use the data in memory without initializing it first. In addition, _debug_trealloc makes an implicit call to _theap_check, and stores the file name file and the line number line where the storage is reallocated. This information can be used later by the _theap_check and _tdump_allocated or _tdump_allocated_delta functions. If ptr is NULL, _debug_trealloc behaves like _debug_tmalloc (or malloc) and allocates the block of memory. To use _debug_trealloc, you must compile with the debug memory and tiled memory compiler options (/Tm /Gt). These options map all realloc calls to _debug_trealloc (you can also call _debug_trealloc explicitly). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. _debug_trealloc works just like _debug_realloc except that it reallocates tiled memory instead of regular memory. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory is guaranteed not to cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. Tiled memory from the VisualAge C++ runtime heap is limited to 512 MB per process. You can also create your own heaps of tiled memory, which can be larger in size. See "Managing Memory" in the Programming Guide for more information. Return Value _debug_trealloc returns a pointer to the reallocated memory block. The ptr argument to _debug_trealloc is not necessarily the same as the return value, because the _debug_trealloc might change the memory location. If size is 0, _debug_trealloc returns NULL. If not enough memory is available to expand the block to the given size, the original block is unchanged and NULL is returned. ═══ Example of _debug_trealloc ═══ /************************************************************************ This example uses _debug_tmalloc to allocate 5 bytes of storage, then attempts to write to storage that was not allocated. The call to _debug_trealloc invokes _theap_check, which detects the error, generates several messages, and stops the program. Note: You must compile this example with the /Tm /Gt options to map the realloc calls to _debug_trealloc. *********************************************************************** / #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(5))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } memset (ptr, 'x', 7); /* Overwrites storage that was not allocated */ /* realloc is mapped to _debug_trealloc */ if (NULL == (ptr = realloc(ptr, 10))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00080120 was overwritten at 0x00080125. The first eight bytes of the memory block (in hex) are: 78787878787878DD. This memory block was (re)allocated at line number 8 in _debug_treallo.c. Heap state was valid at line 8 of _debug_treallo.c. Memory error detected at line 15 of _debug_treallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_trealloc  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Tiled Debug Functions  _debug_realloc - Reallocate Memory Block  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_theapmin - Release Unused Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _theap_check - Validate User Memory Heap  _trealloc - Reallocate Tiled Storage Block   ═══ 4.59. _debug_ucalloc - Reserve and Initialize Memory from User Heap ═══ ═══ Format ═══ #include void *_debug_ucalloc(Heap_t heap, size_t num, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_ucalloc is the debug version of _ucalloc. Like _ucalloc, it allocates memory from the heap you specify for an array of num elements, each of length size bytes. It then initializes all bits of each element to 0. In addition, _debug_ucalloc makes an implicit call to _uheap_check, and stores the name of the file file and the line number line where the storage is allocated. This information can be used later by the _uheap_check and _udump_allocated or _udump_allocated_delta functions. To use _debug_ucalloc, you must compile with the debug memory (/Tm) compiler option. the /Tm compiler option. This option maps all _ucalloc calls to _debug_ucalloc (you can also call _debug_ucalloc explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. _debug_ucalloc works just like _debug_calloc except that you specify the heap to use; _debug_calloc always allocates from the default heap. If the heap does not have enough memory for the request, _debug_ucalloc calls the getmore_fn that you specified when you created the heap with _ucreate. To reallocate or free memory allocated with _debug_ucalloc, use the non-heap-specific _debug_realloc and _debug_free. These functions always check what heap the memory was allocated from. Return Value _debug_ucalloc returns a pointer to the reserved space. If size or num was specified as zero, or if your getmore_fn cannot provide enough memory, _debug_ucalloc returns NULL. Passing _debug_ucalloc a heap that is not valid results in undefined behavior. ═══ Example of _debug_ucalloc ═══ /************************************************************************ This example creates a user heap and allocates memory from it with _debug_ucalloc. It then attempts to write to memory that was not allocated. When _debug_free is called, _uheap_check detects the error, generates several messages, and stops the program. Note: You must compile this example with the /Tm option to map the _ucalloc calls to _debug_ucalloc and free to _debug_free. *********************************************************************** / #include #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _ucalloc(myheap, 100, 1))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } memset(ptr, 'x', 105); /* Overwrites storage that was not allocated */ free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 7878787878787878. This memory block was (re)allocated at line number 14 in _debug_ucallo.c. Heap state was valid at line 14 of _debug_ucallo.c. Memory error detected at line 19 of _debug_ucallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_ucalloc  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Differentiating between Memory Management Functions  calloc - Reserve and Initialize Storage  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_umalloc - Reserve Memory Blocks from User Heap  _ucalloc - Reserve and Initialize Memory from User Heap  _ucreate - Create a Memory Heap  _udump_allocated - Get Information about Allocated Memory in Heap  _uheap_check - Validate User Memory Heap  ═══ 4.60. _debug_uheapmin - Release Unused Memory in User Heap ═══ ═══ Format ═══ #include int _debug_uheapmin(Heap_t heap, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_uheapmin is the debug version of _uheapmin. Like _uheapmin, it returns all unused memory blocks from the specified heap to the operating system. To return the memory, _debug_uheapmin calls the release_fn you supplied when you created the heap with _ucreate. If you do not supply a release_fn, _debug_uheapmin has no effect and returns 0. In addition, _debug_uheapmin makes an implicit call to _uheap_check to validate the heap. _debug_uheapmin works just like _debug_heapmin except that you specify the heap to use; _debug_heapmin always uses the default heap. To use _debug_uheapmin, you must compile with the debug memory (/Tm) compiler option. This option maps all _uheapmin calls to _debug_uheapmin (you can also call _debug_uheapmin explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Return Value If successful, _debug_uheapmin returns 0. A nonzero return value indicates failure. If the heap specified is not valid, _debug_uheapmin generates an error message with the file name and line number where the call to _debug_uheapmin was made. ═══ Example of _debug_uheapmin ═══ /************************************************************************ This example creates a heap and allocates memory from it, then uses _debug_heapmin to release the memory. Note: You must compile this example with the /Tm option to map the _uheapmin calls to _debug_uheapmin. *********************************************************************** / #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); /* Allocate a large object */ if (NULL == (ptr = _umalloc(myheap, 60000))) { puts("Cannot allocate memory from user heap.\n"); exit(EXIT_FAILURE); } memset(ptr, 'x', 60000); free(ptr); /* _debug_uheapmin will attempt to return the freed object to the system */ if (0 != _uheapmin(myheap)) { puts("_debug_uheapmin returns failed.\n"); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _debug_uheapmin  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Differentiating between Memory Management Functions  _heapmin - Release Unused Memory from Default Heap  _ucreate - Create a Memory Heap  _udump_allocated - Get Information about Allocated Memory in Heap  _uheap_check - Validate User Memory Heap  _uheapmin - Release Unused Memory in User Heap  ═══ 4.61. _debug_umalloc - Reserve Memory Blocks from User Heap ═══ ═══ Format ═══ #include void *_debug_umalloc(Heap_t heap, size_t size, const char *file, size_t line); ═══ Description ═══ Language Level: Extension _debug_umalloc is the debug version of _umalloc. Like _umalloc, it reserves storage space from the heap you specify for a block of size bytes. _debug_umalloc also sets all the memory it allocates to 0xAA, so you can easily locate instances where your program uses the data in the memory without initializing it first. In addition, _debug_umalloc makes an implicit call to _uheap_check, and stores the name of the file file and the line number line where the storage is allocated. This information can be used later by the _uheap_check and _udump_allocated or _udump_allocated_delta functions. _debug_umalloc also sets all the memory it allocates to 0xAA; this can help you debug problems where your program uses the data in the memory without initializing it. _debug_umalloc works just like _debug_malloc except that you specify the heap to use; _debug_malloc always allocates from the default heap. If the heap does not have enough memory for the request, _debug_umalloc calls the getmore_fn that you specified when you created the heap with _ucreate. To use _debug_umalloc, you must compile with the debug memory (/Tm) compiler option. This option maps all _umalloc calls to _debug_umalloc (you can also call _debug_umalloc explicitly). Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. To reallocate or free memory allocated with _debug_umalloc, use the non-heap-specific _debug_realloc and _debug_free. These functions always check what heap the memory was allocated from. Return Value: _debug_umalloc returns a pointer to the reserved space. If size was specified as zero, or the getmore_fn cannot provide enough memory, _debug_umalloc returns NULL. Passing _debug_umalloc a heap that is not valid results in undefined behavior. ═══ Example of _debug_umalloc ═══ /************************************************************************ This example creates a heap myheap and uses _debug_umalloc to allocate 100 bytes from it. It then attempts to overwrite storage that was not allocated. The call to _debug_free invokes _uheap_check, which detects the error, generates messages, and ends the program. Note: You must compile this example with the /Tm option to map _umalloc to _debug_umalloc and free to _debug_free. *********************************************************************** #include #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _umalloc(myheap, 100))) { puts("Cannot allocate memory from user heap.\n"); exit(EXIT_FAILURE); } memset(ptr, 'x', 105); /* Overwrites storage that was not allocated */ free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 7878787878787878. This memory block was (re)allocated at line number 14 in _debug_umallo.c. Heap state was valid at line 14 of _debug_umallo.c. Memory error detected at line 19 of _debug_umallo.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _debug_umalloc  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  Differentiating between Memory Management Functions  _debug_free - Release Memory  _debug_malloc - Allocate Memory  _debug_ucalloc - Reserve and Initialize Memory from User Heap  malloc - Reserve Storage Block  _ucreate - Create a Memory Heap  _udump_allocated - Get Information about Allocated Memory in Heap  _umalloc - Reserve Memory Blocks from User Heap  _uheap_check - Validate User Memory Heap  ═══ 4.62. difftime - Compute Time Difference ═══ ═══ Format ═══ #include double difftime(time_t time2, time_t time1); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 difftime computes the difference in seconds between time2 and time1. Return Value 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be similar to : Program takes an average of 0.106000 seconds to find 1229 primes. ****************************************************************************/ } ═══ Related Information ═══ Example of difftime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  strftime - Convert to Formatted Time  time - Determine Current Time  ═══ 4.63. _disable - Disable Interrupts ═══ ═══ Format ═══ #include void _disable( void ); ═══ Description ═══ Language Level: Extension _disable disables interrupts by executing the CLI machine instruction. It disables interrupts until the instruction after a call to _enable has been executed. Note: _disable is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _disable.  You cannot parenthesize a call to _disable. (Parentheses specify a call to the function's backing code, and _disable has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value This function has no return value. ═══ Example of _disable ═══ /************************************************************************ In this example, _disable disables interrupts by executing a CLI instruction. ************************************************************************/ #include int main(void) { /* ------------------------------------------------------ */ /* The expected assembler instruction looks like this : */ /* CLI */ /* -------------------------------------------------------*/ _disable(); return 0; } ═══ Related Information ═══ Example of disable  _enable - Enable Interrupts  _interrupt - Call Interrupt Procedure  ═══ 4.64. div - Calculate Quotient and Remainder ═══ ═══ Format ═══ #include div_t div(int numerator, int denominator); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 div calculates the quotient and remainder of the division of numerator by denominator. Return Value div 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 ═══ /************************************************************************ This example uses div 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); } return 0; /**************************************************************************** The output should be: 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 ═══ Example of div  ldiv - Perform Long Division  ═══ 4.65. _DLL_InitTerm - Initialize and Terminate DLL Environment ═══ ═══ Format ═══ unsigned long _System _DLL_InitTerm(unsigned long modhandle, unsigned long flag); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _DLL_InitTerm is the initialization and termination entry point for a DLL. When each new process gains access to the DLL, _DLL_InitTerm initializes the necessary environment for the DLL, including storage, semaphores, and variables. When each process frees its access to the DLL, _DLL_InitTerm terminates the DLL environment created for that process. The default _DLL_InitTerm function supplied by VisualAge C++ performs the actions required to initialize and terminate the runtime environment, or for subsystem DLLs, to initialize and terminate memory functions. It is called automatically when you link to the DLL. If your DLL requires initialization or termination actions in addition to the actions performed in the default function, 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. You can use the module handle as a parameter to various OS/2 API calls. For example, you can call DosQueryModuleName with the module handle to return the fully-qualified path name of the DLL, which tells you where the DLL was loaded from. Because it is called by the operating system loader, you must compile your _DLL_InitTerm function with _System linkage. For more information on creating your own _DLL_InitTerm function, see the chapter Building Dynamic Link Libraries in the Programming Guide. 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. For more information on building subsystem DLLs, see the section Building a Subsystem DLL in the Programming Guide. Return Value 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. ═══ Example of _DLL_Initterm ═══ /************************************************************************ This example shows the _DLL_InitTerm function from the VisualAge C++ sample program for building DLLs. ************************************************************************/ #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 VisualAge C++ sample for building subsystem DLLs. ************************************************************************/ /* _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 ) { _rmem_init(); /* 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; _rmem_term(); break; default: return 0; } /* Indicate success. Non-zero means success!!! */ return 1; } ═══ Related Information ═══ Example of _DLL_Initterm Example of _DLL_Initterm for a Subsystem  Building a Dynamic Link Library in the Programming Guide  Building a Subsystem DLL in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _CRT_term - Terminate DLL Runtime Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.66. _dump_allocated - Get Information about Allocated Memory ═══ ═══ Format ═══ #include /* also in */ void _dump_allocated(int nbytes); ═══ Description ═══ Language Level: Extension _dump_allocated prints information to stderr about each memory block that is currently allocated and was allocated using the debug memory management functions (_debug_calloc, _debug_malloc, and so on). Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is a: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. Call _dump_allocated at points in your code where you want 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 at the end of a program. _dump_allocated prints the information to stderr, but you can change the destination with the _set_crt_msg_handle function. You can also use _dump_allocated_delta to display information only about the memory that was allocated since the previous call to _dump_allocated or _dump_allocated_delta. To use _dump_allocated and the debug memory management functions, you must compile with the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Heap-specific and tiled versions of this function (_udump_allocated and _tdump_allocated) are also available. _dump_allocated always prints information about memory allocated from the default heap. Return Value There is no return value. ═══ 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. Note: You must compile this example with the /Tm option to map the memory management functions to their debug versions. ************************************************************************/ rules=none. #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 (NULL == (pBlock1 = malloc(35))) { /* 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 (NULL == (pBlock2 = calloc(2, 120))) { /* 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 (NULL == (pBlock3 = realloc(NULL, 2235))) {/* 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 (NULL == (pBlock3 = realloc(pBlock3, 300))) { /* 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; /**************************************************************************** The output should be similar to: ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00074310 Size: 0x0000012C (300) This memory block was (re)allocated at line number 32 in _dump_alloc.c. Memory contents: 49740077 6F726B73 [It.works ] ------------------------------------------------------------------------------- Address: 0x000738F0 Size: 0x000000F0 (240) This memory block was (re)allocated at line number 19 in _dump_alloc.c. Memory contents: 49740077 6F726B73 [It.works ] ------------------------------------------------------------------------------- Address: 0x00073890 Size: 0x00000023 (35) This memory block was (re)allocated at line number 13 in _dump_alloc.c. Memory contents: 49740077 6F726B73 [It.works ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _dump_allocated  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_malloc - Allocate Memory  _debug_realloc - Reallocate Memory Block  _dump_allocated_delta - Get Information about Allocated Memory  _heap_check - Validate Default Memory Heap  _udump_allocated - Get Information about Allocated Memory in Heap   ═══ 4.67. _dump_allocated_delta - Get Information about Allocated Memory ═══ ═══ Format ═══ #include /* also in */ void _dump_allocated_delta(int nbytes); ═══ Description ═══ Language Level: Extension _dump_allocated_delta prints information to stderr about each memory block allocated by a debug memory management function (_debug_malloc and so on) since the last call to _dump_allocated_delta or _dump_allocated. _dump_allocated_delta and _dump_allocated print the same type of information to stderr, but _dump_allocated displays information about all blocks that have been allocated since the start of your program. Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is a: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. _dump_allocated_delta prints the information to stderr, but you can change the destination with the _set_crt_msg_handle function. A heap-specific version of this function, _udump_allocated_delta, is also available. _dump_allocated_delta always displays information about the default heap. To use _dump_allocated_delta and the debug versions of the memory management functions, specify the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) are mapped to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Return Value: There is no return value. ═══ Example of _dump_allocated_delta ═══ /************************************************************************ This example allocates some memory and calls _dump_allocated to print information about the allocated blocks. It then allocates more memory, and calls _dump_allocated_delta again to print information about the allocations since the previous call. Note: You must compile this example with the /Tm option to map the memory management functions to their debug versions. ************************************************************************/ #include #include #include int main(void) { char *ptr1, *ptr2; if (NULL == (ptr1 = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr1, 'a', 5); _dump_allocated(10); if (NULL == (ptr2 = malloc(20))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr2, 'b', 5); _dump_allocated_delta(10); free(ptr1); free(ptr2); return 0; /**************************************************************************** The output should be similar to : ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00073890 Size: 0x0000000A (10) This memory block was (re)allocated at line number 9 in _dump_alloc_d.c. Memory contents: 61616161 61AAAAAA AAAA [aaaaaИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x000738D0 Size: 0x00000014 (20) This memory block was (re)allocated at line number 16 in _dump_alloc_d.c. Memory contents: 62626262 62AAAAAA AAAA [bbbbbИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _dump_allocated_delta  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_malloc - Allocate Memory  _dump_allocated - Get Information about Allocated Memory  _debug_realloc - Reallocate Memory Block  _set_crt_msg_handle - Change Runtime Message Output Destination  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _udump_allocated_delta - Get Information about Allocated Memory in Heap   ═══ 4.68. dup - Associate Second Handle with Open File ═══ ═══ Format ═══ #include int dup(int handle); ═══ Description ═══ Language Level: XPG4, Extension dup 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. 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. Note: In earlier releases of C Set ++, dup began with an underscore (_dup). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _dup to dup for you. Return Value dup returns the next available file handle for the given file. 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 ═══ /************************************************************************ 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 dup2. ************************************************************************/ #include #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 EXIT_FAILURE; } if (-1 == (fh3 = dup(fh1))) { /* fh3 refers to the sample file as fh1 */ perror("Unable to dup"); close(fh1); return EXIT_FAILURE; } 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 EXIT_FAILURE; } 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 output should be: Successfully performed dup handle. Successfully performed dup2 handle. ****************************************************************************/ } ═══ Related Information ═══ Example of dup  close - Close File Associated with Handle  creat - Create New File  dup2 - Associate Second Handle with Open File  open - Open File  _sopen - Open Shared File  ═══ 4.69. dup2 - Associate Second Handle with Open File ═══ ═══ Format ═══ #include int dup2(int handle1, int handle2); ═══ Description ═══ Language Level: XPG4, Extension dup2 makes handle2 refer to the currently open file associated with handle1. 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. 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. If handle2 is associated with an open file at the time of the call, that file is closed. Warning: Both handles share a single file position. 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. Note: In earlier releases of C Set ++, dup2 began with an underscore (_dup2). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _dup2 to dup2 for you. Return Value dup2 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 ═══ /************************************************************************ 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 #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 EXIT_FAILURE; } if (-1 == (fh3 = dup(fh1))) { /* fh3 refers to the sample file as fh1 */ perror("Unable to dup"); close(fh1); return EXIT_FAILURE; } 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 EXIT_FAILURE; } 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 output should be: Successfully performed dup handle. Successfully performed dup2 handle. ****************************************************************************/ } ═══ Related Information ═══ Example of dup2  close - Close File Associated with Handle  creat - Create New File  dup - Associate Second Handle with Open File  open - Open File  _sopen - Open Shared File  ═══ 4.70. _ecvt - Convert Floating-Point to Character ═══ ═══ Format ═══ #include char *_ecvt(double value, int ndigits, int *decptr, int *signptr); ═══ Description ═══ Language Level: Extension _ecvt converts the floating-point number value to a character string. _ecvt 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. 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. 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. _ecvt 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. Return Value _ecvt returns a pointer to the string of digits. Because of the limited precision of the double type, no more than 16 decimal digits are significant in any conversion. If it cannot allocate memory to perform the conversion. _ecvt returns NULL and sets errno to ENOMEM. ═══ 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 (2 != scanf("%e %e", &x, &y)) { printf("input error...\n"); return EXIT_FAILURE; } z = x *y; printf("Their product is %g\n", z); w = log10(fabs(z))+1.; buffer = _ecvt(z, w, &decimal, &sign); 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; /**************************************************************************** For the following input: 1000000 3000 The output should be: Enter two floating-point numbers: 1000000 3000 Their product is 3e+09 The billions digit of their product is 3. ****************************************************************************/ } ═══ Related Information ═══ Example of _ecvt  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  Infinity and NaN Support  ═══ 4.71. _enable - Enable Interrupts ═══ ═══ Format ═══ #include /* also defined in */ void _enable( void ); ═══ Description ═══ Language Level: Extension _enable 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:  You cannot take the address of _enable.  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. Return Value There is no return value. ═══ Example of _enable ═══ /************************************************************************ In this example, _enable enables interrupts by executing an STI instruction. ************************************************************************/ #include int main(void) { /* ------------------------------------------------------ */ /* The expected assembler instruction looks like this : */ /* STI */ /* ------------------------------------------------------ */ _enable(); return 0; } ═══ Related Information ═══ Example of _enable  _disable - Disable Interrupts  _interrupt - Call Interrupt Procedure  ═══ 4.72. _endthread - Terminate Current Thread ═══ ═══ Format ═══ #include /* also in */ void _endthread(void); ═══ Description ═══ Language Level: Extension _endthread ends a thread that you previously created with _beginthread. When the thread has finished, it automatically ends itself with an implicit call to _endthread. You can also call _endthread explicitly to end the thread before it has completed its function, for example, if some error condition occurs. 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. Return Value There is no return value. ═══ 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: You must compile this example with the /Gm+ 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 (-1 == tid1 || -1 == tid2) { printf("Unable to start threads.\n"); return EXIT_FAILURE; } DosWaitThread(&tid2, DCWW_WAIT); /* wait until threads 1 and 2 */ DosWaitThread(&tid1, DCWW_WAIT); /* have been completed */ return 0; /**************************************************************************** The output should be similar to: Au revoir! Au revoir! Au revoir! Au revoir! Au revoir! Bonjour! Bonjour! Bonjour! Bonjour! Bonjour! ****************************************************************************/ } ═══ Related Information ═══ Example of _endthread  _beginthread - Create New Thread  /Gm+ option. in the User's Guide   ═══ 4.73. __eof - Determine End of File ═══ ═══ Format ═══ #include int __eof (int handle); ═══ Description ═══ Language Level: Extension __eof 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. Return Value __eof 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 ═══ /************************************************************************ 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 #include int main(void) { int fh,returnValue; fh = creat("sample.dat", S_IREAD|S_IWRITE); if (-1 == fh) { perror("Error creating sample.dat"); return EXIT_FAILURE; } if (-1 == (returnValue = __eof(fh))) { perror("eof function error"); return EXIT_FAILURE; } if (1 == returnValue) 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 output should be: File pointer is at end-of-file position. ****************************************************************************/ } ═══ Related Information ═══ Example of __eof  _chsize - Alter Length of File  creat - Create New File  _filelength - Determine File Length  _sopen - Open Shared File  open - Open File  ═══ 4.74. erf - erfc - Calculate Error Functions ═══ ═══ Format ═══ #include double erf(double x); double erfc(double x); ═══ Description ═══ Language Level: SAA, XPG4 erf calculates the error function. erfc computes the value of 1.0 - erf(x). erfc is used in place of erf for large values of x. Return Value erf returns a double value that represents the error function. erfc returns a double value representing 1.0 - erf. ═══ Example of erf - erfc ═══ /************************************************************************ This example uses erf and erfc 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); return 0; /**************************************************************************** The output should be: Error value for 0.1: 0.112463 Error value for 10.0: 2.088488e-45 ****************************************************************************/ } ═══ Related Information ═══ Example of erf - erfc  Bessel Functions - Solve Differential Equations  gamma - Gamma Function  ═══ 4.75. execl - _execvpe - 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: XPG4 (except _execlpe and _execvpe), 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. Note: In earlier releases of C Set ++, all of the exec functions began with an underscore (_getpid). Because they are defined by the X/Open standard, the underscore has been removed. _execlpe and _execvpe retain the initial underscore because they are not included in the X/Open standard. For compatibility, VisualAge C++ will map the _exec functions to the correct exec function. 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. Return Value 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:  Not enough storage is available to run the child process.  Not enough storage is available for the argument or environment strings. ═══ Example of exec Functions ═══ /************************************************************************ 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"); return 55; /* 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 ═══ Example of exec Functions  abort - Stop a Program  _cwait - Wait for Child Process  exit - End Program  _exit - End Process  _spawnl - _spawnvpe - Start and Run Child Processes  system - Invoke the Command Processor  wait - Wait for Child Process  "envp Parameter to main" in the Programming Guide  ═══ 4.76. exit - End Program ═══ ═══ Format ═══ #include /* also in */ void exit(int status); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension exit 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. All files opened with tmpfile are deleted. 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. Return Value exit returns both control and the value of status to the operating system. ═══ Example of exit ═══ /************************************************************************ This example ends the program after flushing buffers and closing any open files if it cannot open the file myfile.mjq. ************************************************************************/ #include #include FILE *stream; int main(void) { if (NULL == (stream = fopen("myfile.mjq", "r"))) { perror("Could not open data file"); exit(EXIT_FAILURE); } return 0; /**************************************************************************** The output should be: Could not open data file: The file cannot be found. ****************************************************************************/ } ═══ Related Information ═══ Example of exit  abort - Stop a Program  atexit - Record Program Termination Function  _onexit - Record Termination Function  _exit - End Process  signal - Handle Interrupt Signals  tmpfile - Create Temporary File  ═══ 4.77. _exit - End Process ═══ ═══ Format ═══ #include /* also in */ void _exit(int status); ═══ Description ═══ Language Level: Extension _exit 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. Return Value 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 ═══ /************************************************************************ 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 (0 != setvbuf(stdout, buf, _IOLBF, 50)) printf("The buffering was not set correctly.\n"); printf("This will print out but ...\n"); printf("this will not!"); _exit(EXIT_FAILURE); return 0; /**************************************************************************** The output should be: This will print out but ... ****************************************************************************/ } ═══ Related Information ═══ Example of _exit  abort - Stop a Program  atexit - Record Program Termination Function  execl - _execvpe - Load and Run Child Process  exit - End Program  _onexit - Record Termination Function   ═══ 4.78. exp - Calculate Exponential Function ═══ ═══ Format ═══ #include double exp(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 exp calculates the exponential function of a floating-point argument x (e to the exponent x, where e equals 2.17128128...). Return Value If an overflow occurs, exp returns HUGE_VAL. If an underflow occurs, it returns 0. Both overflow and underflow set errno to ERANGE. ═══ Example of exp ═══ /************************************************************************ This example calculates y as the exponential function of x: ************************************************************************/ #include int main(void) { double x,y; x = 5.0; y = exp(x); printf("exp( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be: exp( 5.000000 ) = 148.413159 ****************************************************************************/ } ═══ Related Information ═══ Example of exp  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  ═══ 4.79. fabs - Calculate Floating-Point Absolute Value ═══ ═══ Format ═══ #include double fabs(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fabs calculates the absolute value of the floating-point argument x. Return Value fabs returns the absolute value. There is no error return value. ═══ Example of fabs ═══ /************************************************************************ This example calculates y as the absolute value of x: ************************************************************************/ #include int main(void) { double x,y; x = -5.6798; y = fabs(x); printf("fabs( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be similar to : fabs( -5.679800 ) = 5.679800 ****************************************************************************/ } ═══ Related Information ═══ Example of fabs  abs - Calculate Integer Absolute Value  _cabs - Calculate Absolute Value of Complex Number  labs - Calculate Absolute Value of Long Integer  ═══ 4.80. _facos - Calculate Arccosine ═══ ═══ Format ═══ #include double _facos(double x); ═══ Description ═══ Language Level: Extension _facos 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:  You cannot take the address of _facos.  You cannot parenthesize a _facos function call, because parentheses specify a call to the backing code for the function. Return Value _facos returns the arccosine of x. ═══ 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 #define MAX 1.0 #define MIN -1.0 int main(void) { double x; printf("Enter x:\n"); scanf("%lf", &x); /* Output error if not in range */ if (MAX < x) printf("Error: %lf too large for acos.\n", x); else if (MIN > x) printf("Error: %lf too small for acos.\n", x); else printf("The arccossine of %lf is %lf.\n", x, _facos(x)); return 0; /**************************************************************************** Assuming you enter: -1.0 The output should be: The arccossine of -1.000000 is 3.141593. ****************************************************************************/ } ═══ Related Information ═══ Example of _facos  acos - Calculate Arccosine  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  ═══ 4.81. _fasin - Calculate Arcsine ═══ ═══ Format ═══ #include double _fasin(double x); ═══ Description ═══ Language Level: Extension _fasin 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:  You cannot take the address of _fasin.  You cannot parenthesize a _fasin function call, because parentheses specify a call to the backing code for the function. Return Value _facos returns the arcsine of x. ═══ 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 #define MAX 1.0 #define MIN -1.0 int main(void) { double x; printf("Enter x:\n"); scanf("%lf", &x); /* Output error if not in range */ if (MAX < x) printf("Error: %lf too large for asin.\n", x); else if (MIN > x) printf("Error: %lf too small for asin.\n", x); else printf("The arcsine of %lf is %lf.\n", x, _fasin(x)); return 0; /**************************************************************************** Assuming you enter: 1.0 The ouput should be: The arcsine of 1.000000 is 1.570796. ****************************************************************************/ } ═══ Related Information ═══ Example of _fasin  asin - Calculate Arcsine  _fcossin - Calculate Cosine and Sine  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  ═══ 4.82. fclose - Close Stream ═══ ═══ Format ═══ #include int fclose(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fclose 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. When a binary stream is closed, the last record in the file is padded with null characters (\0) to the end of the record. Return Value fclose returns 0 if it successfully closes the stream, or EOF if any errors were detected. Note: Once you close a stream with fclose, you must open it again before you can use it. ═══ Example of fclose ═══ /************************************************************************ This example opens a file fclose.dat for reading as a stream; then it closes this file. ************************************************************************/ #include int main(void) { FILE *stream; stream = fopen("fclose.dat", "r"); if (0 != fclose(stream)) /* Close the stream.*/ perror("fclose error"); else printf("File closed successfully.\n"); return 0; /**************************************************************************** The output should be: File closed successfully. ****************************************************************************/ } ═══ Related Information ═══ Example of fclose  close - Close File Associated with Handle  _fcloseall - Close All Open Streams  fflush - Write Buffer to File  fopen - Open Files  freopen - Redirect Open Files  ═══ 4.83. _fcloseall - Close All Open Streams ═══ ═══ Format ═══ #include int _fcloseall(void); ═══ Description ═══ Language Level: Extension _fcloseall closes all open streams, except stdin, stdout, and stderr. It also closes and deletes any temporary files created by tmpfile. _fcloseall 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. Return Value _fcloseall returns the total number of streams closed, or EOF if an error occurs. ═══ 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 #define OUTFILE "temp.out" int main(void) { FILE *stream; int numclosed; stream = fopen(OUTFILE, "w"); numclosed = _fcloseall(); printf("Number of files closed = %d\n", numclosed); remove(OUTFILE); return 0; /**************************************************************************** The output should be: Number of files closed = 1 ****************************************************************************/ } ═══ Related Information ═══ Example of _fcloseall  close - Close File Associated with Handle  fclose - Close Stream  fflush - Write Buffer to File  fopen - Open Files  freopen - Redirect Open Files  tmpfile - Create Temporary File  ═══ 4.84. _fcos - Calculate Cosine ═══ ═══ Format ═══ #include double _fcos( double x); ═══ Description ═══ Language Level: Extension _fcos 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 appropriate 80387 instruction and return only the cosine. Because it is a built-in function and has no backing code in the library:  You cannot take the address of _fcos.  You cannot parenthesize a _fcos function call, because parentheses specify a call to the backing code for the function in the library. Return Value _fcos returns the cosine expressed in radians. ═══ Example of _fcos ═══ /************************************************************************ This example calculates y to be the cosine of x. ************************************************************************/ #include #include int main(void) { double x; x = 7.2; printf("The cosine of %lf is %lf.\n", x, _fcos(x)); return 0; /**************************************************************************** The output should be similar to : The cosine of 7.200000 is 0.608351. ****************************************************************************/ } ═══ Related Information ═══ Example of _fcos  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  ═══ 4.85. _fcossin - Calculate Cosine and Sine ═══ ═══ Format ═══ #include double _fcossin(double x, double *y); ═══ Description ═══ Language Level: Extension _fcossin calculates the cosine of x, and stores the sine of x in *y. This is faster than separately calculating the sine and cosine. Use _fcossin 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:  You cannot take the address of _fcossin.  You cannot parenthesize a _fcossin function call, because parentheses specify a call to the backing code for the function in the library. Return Value _fcossin returns the cosine of x. ═══ Example of _fcossin ═══ /************************************************************************ This example calculates the cosine of x and stores it in z, and stores the sine of x in *y. ************************************************************************/ #include #include int main(void) { double x, y, z; printf("Enter x:\n"); scanf("%lf", &x); z = _fcossin(x, &y); printf("The cosine of %lf is %lf.\n", x, z); printf("The sine of %lf is %lf.\n", x, y); return 0; /**************************************************************************** Assuming you enter : 1.0 The output should be : The cosine of 1.000000 is 0.540302. The sine of 1.000000 is 0.841471. ****************************************************************************/ } ═══ Related Information ═══ Example of _fcossin  acos - Calculate Arccosine  asin - Calculate Arcsine  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fasin - Calculate Arcsine  _fcos - Calculate Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  ═══ 4.86. _fcvt - Convert Floating-Point to String ═══ ═══ Format ═══ #include char *_fcvt(double value, int ndec, int *decptr, int *signptr); ═══ Description ═══ Language Level: Extension _fcvt converts the floating-point number value to a character string. _fcvt 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─┘ │ │ └─┴─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ _fcvt 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. decptr 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. signptr points to an integer showing the sign of value. _fcvt sets the integer to 0 if value is positive and to a nonzero number if value is negative. _fcvt 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. Return Value _fcvt returns a pointer to the string of digits. Because of the limited precision of the double type, no more than 16 decimal digits are significant in any conversion. If it cannot allocate memory to perform the conversion, _fcvt returns NULL and sets errno to ENOMEM. ═══ 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 = 2000000; float y = 3000; double z; int w,b,decimal,sign; char *buffer; z = x *y; printf("The product of %e and %e is %g.\n", x, y, z); w = log10(fabs(z))+1.; buffer = _fcvt(z, w, &decimal, &sign); b = decimal-10; if (b < 0) printf("Their product does not exceed one billion.\n"); if (b > 15) printf("The billions digit of their product is insignificant.\n"); if ((b > -1) && (b < 16)) printf("The billions digit of their product is %c.\n", buffer[b]); return 0; /**************************************************************************** The output should be: The product of 2.000000e+06 and 3.000000e+03 is 6e+09. The billions digit of their product is 6. ****************************************************************************/ } ═══ Related Information ═══ Example of _fcvt  _ecvt - Convert Floating-Point to Character  _gcvt - Convert Floating-Point to String  Infinity and NaN Support  ═══ 4.87. fdopen - Associates Input Or Output With File ═══ ═══ Format ═══ #include FILE *fdopen(int handle, char *type); ═══ Description ═══ Language Level: XPG4, Extension fdopen 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+ Create a stream for reading and writing a binary file. The file pointer is set to the beginning of the file. 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 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 "Stream Processing" in the Programming Guide for the differences between text and binary streams.) If fdopen returns NULL, use close to close the file. If fdopen is successful, you must use fclose to close the stream and file. Note: In earlier releases of C Set ++, fdopen began with an underscore (_fdopen). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _fdopen to fdopen for you. Return Value fdopen 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 ═══ /************************************************************************ 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 EXIT_FAILURE; } if (NULL == (fp = fdopen(fh, "r"))) { perror("fdopen failed"); close(fh); return EXIT_FAILURE; } if (7 != fread(buffer, 1, 7, fp)) { perror("fread failed"); fclose(fp); return EXIT_FAILURE; } printf("Successfully read from the stream the following:\n%s.\n", buffer); fclose(fp); return 0; /**************************************************************************** The output should be: Creating sample.dat. Successfully read from the stream the following: Sample . ****************************************************************************/ } ═══ Related Information ═══ Example of fdopen  close - Close File Associated with Handle  creat - Create New File  fclose - Close Stream  fopen - Open Files  fseek - Reposition File Position  fsetpos - Set File Position  open - Open File  rewind - Adjust Current File Position  _sopen - Open Shared File  ═══ 4.88. feof - Test End-of-File Indicator ═══ ═══ Format ═══ #include int feof(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 feof 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. Return Value feof returns a nonzero value if and only if the EOF flag is set; otherwise, it returns 0. ═══ Example of feof ═══ /************************************************************************ This example scans the input stream until it reads an end-of-file character. ************************************************************************/ #include int main(void) { char inp_char; FILE *stream; stream = fopen("feof.dat", "r"); /* scan an input stream until an end-of-file character is read */ while (0 == feof(stream)) { fscanf(stream, "%c", &inp_char); printf(" ", inp_char); } fclose(stream); return 0; /**************************************************************************** If feof.dat contains : abc defgh The output should be: ****************************************************************************/ } ═══ Related Information ═══ Example of feof  clearerr - Reset Error Indicators.  ferror - Test for Read/Write Errors  fseek - Reposition File Position  fsetpos - Set File Position  perror - Print Error Message  rewind - Adjust Current File Position  ═══ 4.89. ferror - Test for Read/Write Errors ═══ ═══ Format ═══ #include int ferror(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ferror 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. Return Value 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. ═══ Example of ferror ═══ /************************************************************************ This example puts data out to a stream and then checks that a write error has not occurred. ************************************************************************/ #include #include int main(void) { FILE *stream; char *string = "Important information"; stream = fopen("ferror.dat", "w"); fprintf(stream, "%s\n", string); if (ferror(stream)) { printf("write error\n"); clearerr(stream); return EXIT_FAILURE; } else printf("Data written to a file successfully.\n"); if (fclose(stream)) perror("fclose error"); return 0; /**************************************************************************** The output should be: Data written to a file successfully. ****************************************************************************/ } ═══ Related Information ═══ Example of ferror  clearerr - Reset Error Indicators.  feof - Test End-of-File Indicator  fopen - Open Files  perror - Print Error Message  strerror - Set Pointer to Runtime Error Message  _strerror - Set Pointer to System Error String  ═══ 4.90. fflush - Write Buffer to File ═══ ═══ Format ═══ #include int fflush(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fflush 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. Note: The system automatically flushes buffers when you close the stream, or when a program ends normally without closing the stream. Return Value fflush returns the value 0 if it successfully flushes the buffer. It returns EOF if an error occurs. ═══ Example of fflush ═══ /************************************************************************ This example flushes a stream buffer. ************************************************************************/ #include int main(void) { FILE *stream; stream = fopen("myfile.dat", "w"); fprintf(stream, "Hello world"); fflush(stream); fclose(stream); return 0; } ═══ Related Information ═══ Example of fflush  fclose - Close Stream  _flushall - Write Buffers to Files  setbuf - Control Buffering  ungetc - Push Character onto Input Stream  ═══ 4.91. fgetc - Read a Character ═══ ═══ Format ═══ #include int fgetc(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fgetc 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. Note: fgetc is identical to getc but is always implemented as a function call; it is never replaced by a macro. Return Value fgetc 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. ═══ 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"); printf("The input line was : %s\n", buffer); return 0; /**************************************************************************** If myfile.dat contains: one two three The output should be: The input line was : one two three ****************************************************************************/ } ═══ Related Information ═══ Example of fgetc  _fgetchar - Read Single Character from stdin  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fputc - Write Character  getc - getchar - Read a Character  _getch - _getche - Read Character from Keyboard  ═══ 4.92. _fgetchar - Read Single Character from stdin ═══ ═══ Format ═══ #include int _fgetchar(void); ═══ Description ═══ Language Level: Extension _fgetchar reads a single character from the stdin stream. It is equivalent to the following fgetc call: fgetc(c, stdin); For portability, use the ANSI/ISO fgetc function instead of _fgetchar. Return Value _fgetchar 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 ═══ /************************************************************************ 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; /**************************************************************************** The output should be: Please input a line of characters... This is a simple program. The input line was : This is a simple program. ****************************************************************************/ } ═══ Related Information ═══ Example of _fgetchar  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fgetc - Read a Character  _fputchar - Write Character  getc - getchar - Read a Character  _getch - _getche - Read Character from Keyboard  ═══ 4.93. fgetpos - Get File Position ═══ ═══ Format ═══ #include int fgetpos(FILE *stream, fpos_t *pos); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 fgetpos 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. Note: For buffered text streams, fgetpos returns an incorrect file position if the file contains new-line characters instead of carriage-return line-feed combinations. Your file would only contain new-line characters if you previously used it as a binary stream. To avoid this problem, either continue to process the file as a binary stream, or use unbuffered I/O operations. Return Value fgetpos returns 0 if successful. On error, fgetpos returns nonzero and sets errno to a nonzero value. ═══ Example of fgetpos ═══ /************************************************************************ This example opens the file myfile.dat for reading and stores the current file pointer position 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 ( 0 == (retcode = fgetpos(stream, &pos)) ) printf("Current position of file pointer found.\n"); fclose(stream); return 0; /**************************************************************************** If myfile.dat exists, the output should be: Current position of file pointer found. ****************************************************************************/ } ═══ Related Information ═══ Example of fgetpos  fseek - Reposition File Position  fsetpos - Set File Position  ftell - Get Current Position  ═══ 4.94. fgets - Read a String ═══ ═══ Format ═══ #include char *fgets (char *string, int n, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fgets 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. fgets 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. Return Value fgets 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 ═══ /************************************************************************ 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"); return 0; /**************************************************************************** If myfile.dat contains: This is my data file. The output should be: The string is This is my data file. ****************************************************************************/ } ═══ Related Information ═══ Example of fgets  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fputs - Write String  gets - Read a Line  puts - Write a String  ═══ 4.95. fgetwc - Read Wide Character from Stream ═══ ═══ Format ═══ #include #include wint_t fgetwc(FILE *stream); ═══ Description ═══ Language Level: ANSI 93 fgetwc reads the next multibyte character from the input stream pointed to by stream, converts it to a wide character, and advances the associated file position indicator for the stream (if defined). The behavior of fgetwc is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent read operations on the same stream, undefined results can occur. Using non-wide-character functions with fgetwc on the same stream results in undefined behavior. After calling fgetwc, flush the buffer or reposition the stream pointer before calling a write function for the stream, unless EOF has been reached. After a write operation on the stream, flush the buffer or reposition the stream pointer before calling fgetwc. Return Value fgetwc returns the next wide character that corresponds to the multibyte character from the input stream pointed to by stream. If the stream is at EOF, the EOF indicator for the stream is set and fgetwc returns WEOF. If a read error occurs, the error indicator for the stream is set and fgetwc returns WEOF. If an encoding error occurs (an error converting the multibyte character into a wide character), fgetwc sets errno to EILSEQ and returns WEOF. Use ferror and feof to distinguish between a read error and an EOF. EOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator. ═══ Example of fgetwc ═══ /************************************************************************ This example opens a file, reads in each wide character using fgetwc, and prints out the characters. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wint_t wc; if (NULL == (stream = fopen("fgetwc.dat", "r"))) { printf("Unable to open: \"fgetwc.dat\"\n"); exit(1); } errno = 0; while (WEOF != (wc = fgetwc(stream))) printf("wc = %lc\n", wc); if (EILSEQ == errno) { printf("An invalid wide character was encountered.\n"); exit(1); } fclose(stream); return 0; /**************************************************************************** Assuming the file fgetwc.dat contains: Hello world! The output should be similar to: wc = H wc = e wc = l wc = l wc = o : ****************************************************************************/ } ═══ Related Information ═══ Example of fgetwc  fgetc - Read a Character  _fgetchar - Read Single Character from stdin  fgetws - Read Wide-Character String from Stream  fputwc - Write Wide Character  _getch - _getche - Read Character from Keyboard   ═══ 4.96. fgetws - Read Wide-Character String from Stream ═══ ═══ Format ═══ #include #include wchar_t *fgetws(wchar_t *wcs, int n, FILE *stream); ═══ Description ═══ Language Level: ANSI 93, XPG4 fgetws reads wide characters from the stream into the array pointed to by wcs. At most, n - 1 wide characters are read. fgetws stops reading characters after WEOF, or after it reads a new-line wide character (which is retained). It adds a null wide character immediately after the last wide character read into the array. fgetws advances the file position unless there is an error. If an error occurs, the file position is undefined. The behavior of fgetws is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent read operations on the same stream, undefined results can occur. Using non-wide-character functions with fgetws on the same stream results in undefined behavior. After calling fgetws, flush the buffer or reposition the stream pointer before calling a write function for the stream, unless WEOF has been reached. After a write operation on the stream, flush the buffer or reposition the stream pointer before calling fgetws. Return Value If successful, fgetws returns a pointer to the wide-character string wcs. If WEOF is encountered before any wide characters have been read into wcs, the contents of wcs remain unchanged and fgetws returns a null pointer. If WEOF is reached after data has already been read into the string buffer, fgetws returns a pointer to the string buffer to indicate success. A subsequent call would return NULL because WEOF would be reached without any data being read. If a read error occurs, the contents of wcs are indeterminate and fgetws returns NULL. If an encoding error occurs (in converting a wide character to a multibyte character), fgetws sets errno to EILSEQ and returns NULL. If n equals 1, the wcs buffer has only room for the terminating null character and nothing is read from the stream. (Such an operation is still considered a read operation, so it cannot immediately follow a write operation unless the buffer is flushed or the stream pointer repositioned first.) If n is greater than 1, fgetws fails only if an I/O error occurs or if WEOF is reached before data is read from the stream. Use ferror and feof to distinguish between a read error and a WEOF. WEOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the WEOF indicator. ═══ Example of fgetws ═══ /************************************************************************ This example opens a file, reads in the file contents using fgetws, then prints the file contents. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wchar_t wcs[100]; if (NULL == (stream = fopen("fgetws.dat", "r"))) { printf("Unable to open: \"fgetws.dat\"\n"); exit(1); } errno = 0; if (NULL == fgetws(wcs, 100, stream)) { if (EILSEQ == errno) { printf("An invalid wide character was encountered.\n"); exit(1); } else if (feof(stream)) printf("End of file reached.\n"); else perror("Read error.\n"); } printf("wcs = \"%ls\"\n", wcs); fclose(stream); return 0; /**************************************************************************** Assuming the file fgetws.dat contains: This test string should not return -1 The output should be similar to: wcs = "This test string should not return -1" ****************************************************************************/ } ═══ Related Information ═══ Example of fgetws  fgets - Read a String  fgetwc - Read Wide Character from Stream  fputws - Write Wide-Character String.   ═══ 4.97. _filelength - Determine File Length ═══ ═══ Format ═══ #include long _filelength(int handle); ═══ Description ═══ Language Level: Extension _filelength 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. Return Value 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 ═══ /************************************************************************ 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 EXIT_FAILURE; } if (-1 == (length = _filelength(fh))) { printf("Unable to determine length of sample.dat.\n"); return EXIT_FAILURE; } printf("Current length of sample.dat is %d.\n", length); close(fh); return 0; /**************************************************************************** The output should be: Creating sample.dat. Current length of sample.dat is 17. ****************************************************************************/ } ═══ Related Information ═══ Example of _filelength  _chsize - Alter Length of File  __eof - Determine End of File  ═══ 4.98. fileno - Determine File Handle ═══ ═══ Format ═══ #include int fileno(FILE *stream); ═══ Description ═══ Language Level: XPG4, Extension fileno determines the file handle currently associated with stream. Note: In earlier releases of C Set ++, fileno began with an underscore (_fileno). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _fileno to fileno for you. Return Value fileno 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 ═══ /************************************************************************ 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: The file handle associated with stderr is 2. ****************************************************************************/ } ═══ Related Information ═══ Example of fileno  dup - Associate Second Handle with Open File  dup2 - Associate Second Handle with Open File  fopen - Open Files  freopen - Redirect Open Files  isatty - Test Handle for Character Device  open - Open File  ═══ 4.99. floor - Integer <= Argument ═══ ═══ Format ═══ #include double floor(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 floor calculates the largest integer that is less than or equal to x. Return Value floor returns the floating-point result as a double value. The result of floor cannot have a range error. ═══ 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 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); return 0; /**************************************************************************** The output should be: floor( 2.8 ) = 2.000000 floor( -2.8 ) = -3.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of floor  ceil - Find Integer >= Argument  fmod - Calculate Floating-Point Remainder  ═══ 4.100. _flushall - Write Buffers to Files ═══ ═══ Format ═══ #include int _flushall(void); ═══ Description ═══ Language Level: Extension _flushall 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 ANSI/ISO function fflush instead of _flushall. Return Value _flushall returns the number of open streams of input and output. If an error occurs, _flushall returns EOF. ═══ 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: Number of files flushed = 5 ****************************************************************************/ } ═══ Related Information ═══ Example of _flushall  close - Close File Associated with Handle  fclose - Close Stream  fflush - Write Buffer to File  ═══ 4.101. fmod - Calculate Floating-Point Remainder ═══ ═══ Format ═══ #include double fmod(double x, double y); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fmod 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. Return Value fmod returns the floating-point remainder of x/y. If y is zero or if x/y causes an overflow, fmod returns 0. ═══ 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); return 0; /**************************************************************************** The output should be: fmod( -10.000000, 3.000000) = -1.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of fmod  ceil - Find Integer >= Argument  fabs - Calculate Floating-Point Absolute Value  floor - Integer <= Argument  ═══ 4.102. fopen - Open Files ═══ ═══ Format ═══ #include FILE *fopen(const char *filename, const char *mode); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fopen opens the file specified by filename. mode 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 VisualAge C++ 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 VisualAge C++ compiler does not support record I/O. fopen 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. Return Value fopen 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 ═══ /************************************************************************ This example attempts to open a file for reading. ************************************************************************/ #include int main(void) { FILE *stream; if (NULL == (stream = fopen("myfile.dat", "r"))) printf("Could not open data file\n"); else fclose(stream); /* The following call opens a fixed record length file */ /* for reading and writing in record mode. */ if (NULL == (stream = fopen("myfile.dat", "rb+, lrecl=80, blksize=240, recfm=f, type=record"))) printf("Could not open data file\n"); else fclose(stream); return 0; /**************************************************************************** The output should be: Could not open data file ****************************************************************************/ } ═══ Related Information ═══ Example of fopen  creat - Create New File  fclose - Close Stream  fflush - Write Buffer to File  fread - Read Items  freopen - Redirect Open Files  open - Open File  _sopen - Open Shared File  fseek - Reposition File Position  fsetpos - Set File Position  fwrite - Write Items  rewind - Adjust Current File Position  ═══ 4.103. _fpatan - Calculate Arctangent ═══ ═══ Format ═══ #include double _fpatan(double x); ═══ Description ═══ Language Level: Extension _fpatan calculates the arctangent of x, which is a value in radians between -pi/2 and pi/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:  You cannot take the address of _fpatan.  You cannot parenthesize a _fpatan function call, because parentheses specify a call to the backing code for the function. Return Value This function returns the arctangent of x. ═══ Example of _fpatan ═══ /************************************************************************ This example calculates the arctangent of x. ************************************************************************/ #include #include int main(void) { double x; x = 0.45; printf("The arctangent of %lf is %lf.\n", x, _fpatan(x)); return 0; /**************************************************************************** The output should be : The arctangent of 0.450000 is 0.422854. ****************************************************************************/ } ═══ Related Information ═══ Example of _fpatan  atan - atan2 - Calculate Arctangent  _fptan - Calculate Tangent  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.104. _fpreset - Reset Floating-Point Unit ═══ ═══ Format ═══ #include void _fpreset(void); ═══ Description ═══ Language Level: Extension _fpreset resets the floating-point unit to the default state that the math library requires to function correctly. The value of this default state may change between releases of VisualAge C++. You can determine the default state by calling _fpreset and then calling _control87 with 0 as the parameter. This function is often used within signal handlers. If a program traps floating-point error signals (SIGFPE) with signal, the program can safely recover from floating-point errors by calling longjmp. For more information on signal handlers, see "Signal and OS/2 Exception Handling" the Programming Guide. _fpreset resets the floating-point unit of the current thread only. It does not affect any other threads that may be processing. Return Value There is no return value. ═══ 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 #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 (SIG_ERR == signal(SIGFPE, fphandler)) return EXIT_FAILURE; if (0 == setjmp(mark)) { c = a/b; /* generate floating-point error */ printf("Should never get here\n"); } printf("Recovered from floating-point error\n"); return 0; /**************************************************************************** The output should be: Floating point signal = 3 Recovered from floating-point error ****************************************************************************/ } ═══ Related Information ═══ Example of _fpreset  _clear87 - Clear Floating-Point Status Word  _control87 - Set Floating-Point Control Word  longjmp - Restore Stack Environment  signal - Handle Interrupt Signals  _status87 - Get Floating-Point Status Word  ═══ 4.105. fprintf - Write Formatted Data to a Stream ═══ ═══ Format ═══ #include int fprintf(FILE *stream, const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension fprintf formats and writes a series of characters and values to the output stream. fprintf 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 printf. See printf - Print Formatted Characters for a description of the format-string and the argument list. 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. If you specify a null string for the %s or %ls format specifier, fprintf prints (null). (In previous releases of C Set ++, printf produced no output for a null string.) Return Value fprintf returns the number of bytes printed or a negative value if an output error occurs. ═══ 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); return 0; /**************************************************************************** The output data file myfile.dat should contain: * ***** ******** *** *** ***** ****** ******** ********** ****************************************************************************/ } ═══ Related Information ═══ Example of fprintf  _cprintf - Print Characters to Screen  fscanf - Read Formatted Data  printf - Print Formatted Characters  sprintf - Print Formatted Data to Buffer  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer  Infinity and NaN Support  ═══ 4.106. _fptan - Calculate Tangent ═══ ═══ Format ═══ #include double _fptan(double x); ═══ Description ═══ Language Level: Extension _fptan 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:  You cannot take the address of _fptan.  You cannot parenthesize a _fptan function call, because parentheses specify a call to the backing code for the function in the library. Return Value _fptan returns the tangent of x expressed in radians. ═══ Example of _fptan ═══ /************************************************************************ This example calculates the tangent of pi/4. ************************************************************************/ #include #include int main(void) { double pi; pi = 3.1415926; printf("The tangent of %lf is %lf.\n", pi/4.0, _fptan(pi/4.0)); return 0; /**************************************************************************** The output should be : The tangent of 0.785398 is 1.000000. ****************************************************************************/ } ═══ Related Information ═══ Example of _fptan  atan - atan2 - Calculate Arctangent  _fpatan - Calculate Arctangent  tan - Calculate Tangent  tanh - Calculate Hyperbolic Tangent  ═══ 4.107. fputc - Write Character ═══ ═══ Format ═══ #include int fputc(int c, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fputc 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. fputc is identical to putc is always implemented as a function call; it is never replaced by a macro. Return Value fputc returns the character written. A return value of EOF indicates an error. ═══ Example of fputc ═══ /************************************************************************ This example writes the contents of buffer to a file called myfile.dat. Note: Because the output occurs as a side effect within the second expression of the for statement, the statement body is null. ************************************************************************/ #include #include #define NUM_ALPHA 26 int main(void) { FILE *stream; int i; int ch; /* Don't forget the NULL char at the end of the string! */ 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); return 0; } else perror("Error opening myfile.dat"); return EXIT_FAILURE; /**************************************************************************** The output data file myfile.dat should contain: abcdefghijklmnopqrstuvwxyz ****************************************************************************/ } ═══ Related Information ═══ Example of fputc  fgetc - Read a Character  _fputchar - Write Character  putc - putchar - Write a Character  _putch - Write Character to Screen  ═══ 4.108. _fputchar - Write Character ═══ ═══ Format ═══ #include int _fputchar(int c); ═══ Description ═══ Language Level: Extension _fputchar writes the single character c to the stdout stream at the current position. It is equivalent to the following fputc call: fputc(c, stdout); For portability, use the ANSI/ISO fputc function instead of _fputchar. Return Value _fputchar 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 ═══ /************************************************************************ 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: ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc ****************************************************************************/ } ═══ Related Information ═══ Example of _fputchar  _fgetchar - Read Single Character from stdin  fputc - Write Character  putc - putchar - Write a Character  _putch - Write Character to Screen  ═══ 4.109. fputs - Write String ═══ ═══ Format ═══ #include int fputs(const char *string, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fputs copies string to the output stream at the current position. It does not copy the null character (\0) at the end of the string. Return Value fputs returns EOF if an error occurs; otherwise, it returns a non-negative value. ═══ 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.dat"); return 0; /**************************************************************************** The output should be: Total number of characters written to file = 26 ****************************************************************************/ } ═══ Related Information ═══ Example of fputs  _cputs - Write String to Screen  fgets - Read a String  gets - Read a Line  puts - Write a String  ═══ 4.110. fputwc - Write Wide Character ═══ ═══ Format ═══ #include #include wint_t fputwc(wint_t wc, FILE *stream); ═══ Description ═══ Language Level: ANSI 93, XPG4 fputwc converts the wide character wc to a multibyte character and writes it to the output stream pointed to by stream at the current position. It also advances the file position indicator appropriately. If the file cannot support positioning requests, or if the stream was opened with append mode, the character is appended to the stream. The behavior of fputwc is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent operations on the same stream, undefined results can occur. Using non-wide-character functions with fputwc on the same stream results in undefined behavior. After calling fputwc, flush the buffer or reposition the stream pointer before calling a read function for the stream. After reading from the stream, flush the buffer or reposition the stream pointer before calling fputwc, unless EOF has been reached. Return Value fputwc returns the wide character written. If a write error occurs, the error indicator for the stream is set and fputwc returns WEOF. If an encoding error occurs during conversion from wide character to a multibyte character, fputwc sets errno to EILSEQ and returns WEOF. ═══ Example of fputwc ═══ /************************************************************************ This example opens a file and uses fputwc to write wide characters to the file. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wchar_t *wcs = L"A character string."; int i; if (NULL == (stream = fopen("fputwc.out", "w"))) { printf("Unable to open: \"fputwc.out\".\n"); exit(1); } for (i = 0; wcs[i] != L'\0'; i++) { errno = 0; if (WEOF == fputwc(wcs[i], stream)) { printf("Unable to fputwc() the wide character.\n" "wcs[%d] = 0x%lx\n", i, wcs[i]); if (EILSEQ == errno) printf("An invalid wide character was encountered.\n"); exit(1); } } fclose(stream); return 0; /**************************************************************************** The output file fputwc.out should contain : A character string. ****************************************************************************/ } ═══ Related Information ═══ Example of fputwc  fgetwc - Read Wide Character from Stream  fputc - Write Character  _fputchar - Write Character  fputws - Write Wide-Character String  _putch - Write Character to Screen   ═══ 4.111. fputws - Write Wide-Character String ═══ ═══ Format ═══ #include #include int fputws(const wchar_t *wcs, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 fputws converts the wide-character string wcs to a multibyte-character string and writes it to stream as a multibyte character string. It does not write the terminating null byte. The behavior of fputws is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent operations on the same stream, undefined results can occur. Using non-wide-character functions with fputws on the same stream results in undefined behavior. After calling fputws, flush the buffer or reposition the stream pointer before calling a read function for the stream. After a read operation, flush the buffer or reposition the stream pointer before calling fputws, unless EOF has been reached. Return Value fputws returns a non-negative value if successful. If a write error occurs, the error indicator for the stream is set and fputws returns -1. If an encoding error occurs in converting the wide characters to multibyte characters, fputws sets errno to EILSEQ and returns -1. ═══ Example of fputws ═══ /************************************************************************ This example opens a file and writes a wide-character string to the file using fgetws. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wchar_t *wcs = L"This test string should not return -1"; if (NULL == (stream = fopen("fputws.out", "w"))) { printf("Unable to open: \"fputws.out\".\n"); exit(1); } errno = 0; if (EOF == fputws(wcs, stream)) { printf("Unable to complete fputws() function.\n"); if (EILSEQ == errno) printf("An invalid wide character was encountered.\n"); exit(1); } fclose(stream); return 0; /**************************************************************************** The output file fputws.out should contain : This test string should not return -1 ****************************************************************************/ } ═══ Related Information ═══ Example of fputws  fgetws - Read Wide-Character String from Stream  fputs - Write String  fputwc - Write Wide Character   ═══ 4.112. fread - Read Items ═══ ═══ Format ═══ #include size_t fread(void *buffer, size_t size, size_t count, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fread 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. Return Value fread 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. Use ferror and feof to distinguish between a read error and an end-of-file. ═══ Example of fread ═══ /************************************************************************ This example attempts to read NUM_ALPHA characters from the file myfile.dat. 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); buffer[num] = '\0'; printf("buffer = %s\n", buffer); fclose(stream); } else { /* fread failed */ if (ferror(stream)) /* possibility 1 */ perror("Error reading myfile.dat"); else if (feof(stream)) /* possibility 2 */ perror("EOF found"); } } else perror("Error opening myfile.dat"); return 0; /**************************************************************************** The output should be: Number of characters has been read = 26 buffer = abcdefghijklmnopqrstuvwxyz ****************************************************************************/ } ═══ Related Information ═══ Example of fread  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fopen - Open Files  fwrite - Write Items  read - Read Into Buffer  ═══ 4.113. free - Release Storage Blocks ═══ ═══ Format ═══ #include /* also in */ void free(void *ptr); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension free frees a block of storage. ptr points to a block previously reserved with a call to one of the memory allocation functions (such as calloc, _umalloc, or _trealloc). 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. Note: Attempting to free a block of storage not allocated with a C memory management function or a block that was previously freed can affect the subsequent reserving of storage and lead to undefined results. Return Value There is no return value. ═══ 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 = 100; /* number of entries of the array */ printf("Allocating memory for %d long integers.\n", 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(); } return 0; /**************************************************************************** The output should be: Allocating memory for 100 long integers. ****************************************************************************/ } ═══ Related Information ═══ Example of free  Managing Memory in the Programming Guide  _alloca - Temporarily Reserve Storage Block  calloc - Reserve and Initialize Storage  _debug_free - Release Memory  _debug_tfree - Release Tiled Memory  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  _tfree - Free Tiled Storage Block   ═══ 4.114. _freemod - Free User DLL ═══ ═══ Format ═══ #include int _freemod(unsigned long module_handle); ═══ Description ═══ Language Level: Extension _freemod frees all references to a 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. Note: _loadmod and _freemod perform exactly the same function as the OS/2 APIs DosLoadModule and DosFreeModule. They are provided for compatibility with earlier VisualAge C++ releases only, and will not be supported in future versions. Use DosLoadModule and DosFreeModule instead. For more details on these APIs, see the Control Program Guide and Reference. Return Value _freemod returns 0 if successful. If not, _freemod returns -1 and sets errno to EOS2ERR. ═══ 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); return EXIT_FAILURE; } /* get function address from DLL */ rc = DosQueryProcAddr(handle, 0, fname, &faddr); if (0 == rc) { 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); return EXIT_FAILURE; } if (_freemod(handle)) { printf("Error in freeing the %s DLL module\n", modname); return EXIT_FAILURE; } printf("Reference to the %s DLL module has been freed\n", modname); return 0; /**************************************************************************** The output should be: Calling the function from the MARK 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 ═══ Example of _freemod  "Building Dynamic Link Libraries" in the Programming Guide  _loadmod - Load DLL  ═══ 4.115. freopen - Redirect Open Files ═══ ═══ Format ═══ #include FILE *freopen(const char *filename, const char *mode, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 freopen 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. Portability Note This method is included in the SAA C definition, but not in the ANSI/ISO C standard. See fopen. for a description of the mode parameter. Return Value freopen returns a pointer to the newly opened stream. If an error occurs, freopen closes the original file and returns a NULL pointer value. ═══ Example of freopen ═══ /************************************************************************ This example closes the stream1 data stream and reassigns its stream pointer. Note that stream1 and stream2 will have the same value, but they will not necessarily have the same value as stream. ************************************************************************/ #include #include int main(void) { FILE *stream,*stream1,*stream2; stream = fopen("myfile.dat", "r"); stream1 = stream; if (NULL == (stream2 = freopen("", "w+", stream1))) return EXIT_FAILURE; fclose(stream2); return 0; } ═══ Related Information ═══ Example of freopen  close - Close File Associated with Handle  fclose - Close Stream  _fcloseall - Close All Open Streams  fopen - Open Files  open - Open File  _sopen - Open Shared File  ═══ 4.116. frexp - Separate Floating-Point Value ═══ ═══ Format ═══ #include double frexp(double x, int *expptr); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 frexp breaks down the floating-point value x into a term m for the mantissa and another term n for the exponent, such that x = m * (2**n), and the absolute value of m is greater than or equal to 0.5 and less than 1.0 or equal to 0. frexp stores the integer exponent n at the location to which expptr points. Return Value frexp returns the mantissa term m. If x is 0, frexp 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 ═══ /************************************************************************ 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 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); return 0; /**************************************************************************** The output should be: The mantissa is 0.512500 and the exponent is 5 ****************************************************************************/ } ═══ Related Information ═══ Example of frexp  ldexp - Multiply by a Power of Two  modf - Separate Floating-Point Value  ═══ 4.117. fscanf - Read Formatted Data ═══ ═══ Format ═══ #include int fscanf (FILE *stream, const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension fscanf 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. Return Value fscanf 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 ═══ /************************************************************************ This example opens the file myfile.dat 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); return 0; /**************************************************************************** If myfile.dat contains: abcdefghijklmnopqrstuvwxyz 343.2. The output should be: string = abcdefghijklmnopqrstuvwxyz long double = 343 char = . float = 2.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of fscanf  Infinity and NaN Support  _cscanf - Read Data from Keyboard  fprintf - Write Formatted Data to a Stream  scanf - Read Data  sscanf - Read Data  ═══ 4.118. fseek - Reposition File Position ═══ ═══ Format ═══ #include int fseek(FILE *stream, long int offset, int origin); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 fseek 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, fseek 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. 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 chapter "Performing I/O Operations" in the Programming Guide for more information. Return Value fseek returns 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. ═══ Example of fseek ═══ /************************************************************************ This example opens a file myfile.dat for reading. After performing input operations (not shown), fseek moves the file pointer to the beginning of the file. ************************************************************************/ #include #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 */ if (result) /* fail to move the pointer to the */ return EXIT_FAILURE; /* beginning of the file */ fclose(stream); return 0; } ═══ Related Information ═══ Example of fseek  fgetpos - Get File Position  fsetpos - Set File Position  ftell - Get Current Position  rewind - Adjust Current File Position  ungetc - Push Character onto Input Stream  ═══ 4.119. fsetpos - Set File Position ═══ ═══ Format ═══ #include int fsetpos(FILE *stream, const fpos_t *pos); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 fsetpos 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 successful, fsetpos clears the end-of-file indicator, and undoes the effect of any previous ungetc function on the same stream. After the fsetpos call, the next operation on a stream in update mode may be input or output. Return Value If fsetpos successfully changes the current position of the file, it returns 0. A nonzero return value indicates an error. ═══ Example of fsetpos ═══ /************************************************************************ This example opens a file myfile.dat for reading. After performing input operations (not shown), fsetpos 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); return 0; } ═══ Related Information ═══ Example of fsetpos  fgetpos - Get File Position  fseek - Reposition File Position  ftell - Get Current Position  rewind - Adjust Current File Position  ungetc - Push Character onto Input Stream  ═══ 4.120. _fsin - Calculate Sine ═══ ═══ Format ═══ #include double _fsin( double x); ═══ Description ═══ Language Level: Extension _fsin 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:  You cannot take the address of _fsin.  You cannot parenthesize a _fsin function call, because parentheses specify a call to the backing code for the function in the library. Return Value This function returns the sine of a variable x expressed in radians. ═══ Example of _fsin ═══ /************************************************************************ This example calculates y as the sine of pi/2. ************************************************************************/ #include #include int main(void) { double pi; pi = 3.1415926535; printf("The sine of %lf is %lf.\n", pi/2.0, _fsin(pi/2.0)); return 0; /**************************************************************************** The output should be : The sine of 1.570796 is 1.000000. ****************************************************************************/ } ═══ Related Information ═══ Example of _fsin  _fasin - Calculate Arcsine  _fcossin - Calculate Cosine and Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  ═══ 4.121. _fsincos - Calculate Sine and Cosine ═══ ═══ Format ═══ #include double _fsincos(double x, double *y); ═══ Description ═══ Language Level: Extension _fsincos 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:  You cannot take the address of _fsincos.  You cannot parenthesize a _fsincos function call because parentheses specify a call to the backing code for the function. Return Value This function returns the sine of x. ═══ Example of _fsincos ═══ /************************************************************************ This example calculates the sine of x and stores it in z, and stores the cosine of x in y. ************************************************************************/ #include #include int main(void) { double x, y, z; printf("Enter x:\n"); scanf("%lf", &x); z = _fsincos(x, &y); printf("The sine of %lf is %lf.\n", x, z); printf("The cosine of %lf is %lf.\n", x, y); return 0; /**************************************************************************** Assuming you enter : 1.0 The output should be : The sine of 1.000000 is 0.841471. The cosine of 1.000000 is 0.540302. ****************************************************************************/ } ═══ Related Information ═══ Example of _fsincos  acos - Calculate Arccosine  asin - Calculate Arcsine  cos - Calculate Cosine  cosh - Calculate Hyperbolic Cosine  _facos - Calculate Arccosine  _fasin - Calculate Arcsine  _fcos - Calculate Cosine  _fcossin - Calculate Cosine and Sine  _fsin - Calculate Sine  sin - Calculate Sine  sinh - Calculate Hyperbolic Sine  ═══ 4.122. _fsqrt - Calculate Square Root ═══ ═══ Format ═══ #include double _fsqrt(double x); ═══ Description ═══ Language Level: Extension _fsqrt 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. Note: _fsqrt is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _fsqrt.  You cannot parenthesize a call to _fsqrt. (Parentheses specify a call to the function's backing code, and _fsqrt has none.) Return Value _fsqrt returns the value of the square root of x. ═══ Example of _fsqrt ═══ /************************************************************************ This example calculates the square root of 4. ************************************************************************/ #include #include int main(void) { double x; x = 4.0; printf("The square root of %lf is %lf.\n", x, _fsqrt(x)); return 0; /**************************************************************************** The output should be : The square root of 4.000000 is 2.000000. ****************************************************************************/ } ═══ Related Information ═══ Example of _fsqrt  sqrt - Calculate Square Root  ═══ 4.123. fstat - Information about Open File ═══ ═══ Format ═══ #include #include int fstat(int handle, struct stat *buffer); ═══ Description ═══ Language Level: XPG4, Extension fstat 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. fstat 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. 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 access of file. st_mtime Time of last modification of file. st_ctime Time of file creation. There are three additional fields in the stat structure for portability to other operating systems; they have no meaning under the OS/2 operating system. Note: 1. If the given handle refers to a device, the size and time fields in the stat structure are not meaningful. 2. In earlier releases of C Set ++, fstat began with an underscore (_fstat). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _fstat to fstat for you. Return Value If it obtains the file status information, fstat returns 0. A return value of -1 indicates an error, and fstat sets errno to EBADF, showing an incorrect file handle. ═══ 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 (0 == fstat(fileno(fp), &buf)) { 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 Thu May 16 16:08:14 1995 ****************************************************************************/ } ═══ Related Information ═══ Example of fstat  stat - Get Information about File or Directory   ═══ 4.124. ftell - Get Current Position ═══ ═══ Format ═══ #include long int ftell(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ftell finds 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. Note: For buffered text streams, ftell returns an incorrect file position if the file contains new-line characters instead of carriage-return line-feed combinations. Your file would only contain new-line characters if you previously used it as a binary stream. To avoid this problem, either continue to process the file as a binary stream, or use unbuffered I/O operations. Return Value ftell returns the current file position. On error, ftell returns -1L and sets errno to a nonzero value. ═══ Example of ftell ═══ /************************************************************************ This example opens the file myfile.dat 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); printf("Current position of the file is stored.\n"); } 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.dat"); return 0; } ═══ Related Information ═══ Example of ftell  fseek - Reposition File Position  fgetpos - Get File Position  fopen - Open Files  fsetpos - Set File Position  ═══ 4.125. _ftime - Store Current Time ═══ ═══ Format ═══ #include #include void _ftime(struct timeb *timeptr); ═══ Description ═══ Language Level: Extension _ftime 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 The time in seconds since 00:00:00 Coordinated Universal Time, January 1, 1970. millitm The fraction of a second, in milliseconds. timezone The difference in minutes between Coordinated Universal Time and local time, going from east to west. _ftime sets the value of timezone from the value of the global variable _timezone. dstflag 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. Return Value There is no return value. ═══ 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 Thu May 16 16:08:17 1995 ****************************************************************************/ } ═══ Related Information ═══ Example of _ftime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  time - Determine Current Time  tzset - Assign Values to Locale Information   ═══ 4.126. _fullpath - Get Full Path Name of Partial Path ═══ ═══ Format ═══ #include char *_fullpath(char *pathbuf, char *partialpath, size_t n); ═══ Description ═══ Language Level: Extension _fullpath 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 pathbuf is NULL, _fullpath uses malloc to allocate a buffer of size _MAX_PATH bytes to store the path name. Return Value _fullpath 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 ═══ /************************************************************************ 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 (NULL == retBuffer) { 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; /**************************************************************************** The output should be similar to: Full path name of current directory is D:\BIN. ****************************************************************************/ } ═══ Related Information ═══ Example of _fullpath  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  _makepath - Create Path  malloc - Reserve Storage Block  _splitpath - Decompose Path Name  ═══ 4.127. fwrite - Write Items ═══ ═══ Format ═══ #include size_t fwrite(const void *buffer, size_t size, size_t count, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA SAA, POSIX, XPG4 fwrite writes up to count items, each of size bytes in length, from buffer to the output stream. Return Value fwrite returns the number of full items successfully written, which can be fewer than count if an error occurs. ═══ 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); printf("Number of items successfully written : %d\n", numwritten); return 0; /**************************************************************************** The output should be: Number of items successfully written : 100 ****************************************************************************/ } ═══ Related Information ═══ Example of fwrite  fopen - Open Files  fread - Read Items  read - Read Into Buffer  write - Writes from Buffer to File  ═══ 4.128. _fyl2x - Calculate y * log2(x) ═══ ═══ Format ═══ #include double _fyl2x(double x, double y); ═══ Description ═══ Language Level: Extension _fyl2x 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 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:  You cannot take the address of _fyl2x.  You cannot parenthesize a _fyl2x function call, because parentheses specify a call to the backing code for the function in the library. Return Value _fyl2x returns the result of the formula y * log2(x). ═══ Example of _fyl2x ═══ /************************************************************************ This example calculates (y * log2(x)), after prompting the user for values of x and y. ************************************************************************/ #include #include int main(void) { double x, y; printf("Enter a value for x:\n"); scanf("%lf", &x); printf("Enter a value for y:\n"); scanf("%lf", &y); printf("%lf * log2(%lf) is %lf.\n", y, x, _fyl2x(x, y)); return 0; /**************************************************************************** Assuming you enter 4.0 for x and 3.0 for y. The output should be : 3.000000 * log2(4.000000) is 6.000000. ****************************************************************************/ } ═══ Related Information ═══ Example of _fyl2x  _fyl2xp1 - Calculate y * log2(x + 1)  _f2xm1 - Calculate (2**x) - 1  ═══ 4.129. _fyl2xp1 - Calculate y * log2(x + 1) ═══ ═══ Format ═══ #include double _fyl2xp1(double x, double y); ═══ Description ═══ Language Level: Extension _fyl2xp1 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). _fyl2xp1 provides improved accuracy over _fyl2x when logarithms of numbers very close to 1 are computed. 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:  You cannot take the address of _fyl2xp1.  You cannot parenthesize a _fyl2xp1 function call, because parentheses specify a call to the backing code for the function in the library. Return Value _fyl2xp1 returns the result of the formula y * log2(x+1). ═══ Example of _fyl2xp1 ═══ /************************************************************************ This example calculates (y * log2(x + 1)), after prompting the user for values of x and y. ************************************************************************/ #include #include int main(void) { double x, y; printf("Enter a value for x:\n"); scanf("%lf", &x); printf("Enter a value for y:\n"); scanf("%lf", &y); printf("%lf * log2(%lf + 1) is %lf.\n", y, x, _fyl2xp1(x, y)); return 0; /**************************************************************************** Assuming you enter 0.001 for x and 2.0 for y. The output should be : 2.000000 * log2(0.001000 + 1) is 0.002884. ****************************************************************************/ } ═══ Related Information ═══ Example of _fyl2xp1  _fyl2x - Calculate y * log2(x)  _f2xm1 - Calculate (2**x) - 1  ═══ 4.130. _f2xm1 - Calculate (2**x) - 1 ═══ ═══ Format ═══ #include double _f2xm1(double x); ═══ Description ═══ Language Level: Extension _f2xm1 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:  You cannot take the address of _f2xm1.  You cannot parenthesize a _f2xm1 function call, because parentheses specify a call to the backing code for the function in the library. Return Value This function returns the value of the formula (2**x)-1. ═══ Example of _f2xm1 ═══ /************************************************************************ This example calculates (2**x)-1 after prompting the user for a value for x. ************************************************************************/ #include #include int main(void) { double x; printf("Enter a value for x:\n"); scanf("%lf", &x); printf("(2**(%lf)) - 1 is %lf.\n", x, _f2xm1(x)); return 0; /**************************************************************************** Assuming you enter : 0.001 The output should be : (2**(0.001000)) - 1 is 0.000693. ****************************************************************************/ } ═══ Related Information ═══ Example of _f2xm1  _fyl2x - Calculate y * log2(x)  _fyl2xp1 - Calculate y * log2(x + 1)  ═══ 4.131. gamma - Gamma Function ═══ ═══ Format ═══ #include /* SAA extension to ANSI */ double gamma(double x); ═══ Description ═══ Language Level: SAA gamma computes ln( |G(x)| ). Portability Note According to the SAA standard, x must be a positive real value. Under the VisualAge C++ compiler, x can also be a negative integer. Return Value gamma returns the value of ln(|G(x)|). If x is a negative value, errno is set to EDOM. If the result causes an overflow, gamma returns HUGE_VAL and sets errno to ERANGE. ═══ 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.2f) is %7.2e\n", x, g_at_x); return 0; /**************************************************************************** The output should be: The value of G(42.00) is 3.35e+49 ****************************************************************************/ } ═══ Related Information ═══ Example of gamma  Bessel Functions - Solve Differential Equations  erf - erfc - Calculate Error Functions  ═══ 4.132. _gcvt - Convert Floating-Point to String ═══ ═══ Format ═══ #include char *_gcvt(double value, int ndec, char *buffer); ═══ Description ═══ Language Level: Extension _gcvt 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. _gcvt 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: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ ┌───────┐ ┌───────────┐ │ │  │  │ │ │ >>──┬───┬──digit──.────digit─┴──E──┬───┬──digit────┬───────┬─┴──>< │ │ ├─+─┤ ├─+─┤ └─digit─┘ │ │ └─┴─┘ └─┴─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ _gcvt 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, _ecvt, _fcvt and _gcvt 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. Return Value _gcvt returns a pointer to the string of digits. If it cannot allocate memory to perform the conversion, _gcvt returns an empty string and sets errno to ENOMEM. ═══ 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 output should be: The first result is -3141.5 The second result is INFINITY ****************************************************************************/ } ═══ Related Information ═══ Example of _gcvt  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  Infinity and NaN Support  ═══ 4.133. getc - getchar - Read a Character ═══ ═══ Format ═══ #include int getc(FILE *stream); int getchar(void); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 getc reads a single character from the current stream position and advances the stream position to the next character. getchar is identical to getc(stdin). getc is equivalent to fgetc except that, if it is implemented as a macro, getc can evaluate stream more than once. Therfore, the stream argument to getc should not be an expression with side effects. Return Value getc and getchar 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 ═══ /************************************************************************ 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 newline 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); return 0; /**************************************************************************** The output should be similar to: Please enter string hello world The string is hello world ****************************************************************************/ } ═══ Related Information ═══ Example of getc - getchar  fgetc - Read a Character  _fgetchar - Read Single Character from stdin  _getch - _getche - Read Character from Keyboard  putc - putchar - Write a Character  ungetc - Push Character onto Input Stream  gets - Read a Line  ═══ 4.134. _getch - _getche - Read Character from Keyboard ═══ ═══ Format ═══ #include int _getch(void); int _getche(void); ═══ Description ═══ Language Level: Extension _getch reads a single character from the keyboard, without echoing. _getche reads a single character from the keyboard and displays the character read. Neither function can be used to read Ctrl-Break. You can use _kbhit to test if a keystroke is waiting in the buffer. If you call _getch or _getche without first calling _kbhit, the program waits for a key to be pressed. Return Value _getch and _getche return the character read. To read a function key or cursor-moving key, you must call _getch and _getche twice; the first call returns 0 or E0H, and the second call returns the particular extended key code. ═══ Example of _getch - _getche ═══ /************************************************************************ This example gets characters from the keyboard until it finds the character 'x'. ************************************************************************/ #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 (; ; ) { ch = _getch(); if ('x' == ch) { _ungetch(ch); break; } _putch(ch); } ch = _getch(); printf("\nThe last character was '%c'.", ch); return 0; /**************************************************************************** Here is the output from a sample run: 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 ═══ Example of _getch - _getche  _cgets - Read String of Characters from Keyboard  fgetc - Read a Character  getc - getchar - Read a Character  _kbhit - Test for Keystroke  _putch - Write Character to Screen  _ungetch - Push Character Back to Keyboard  ═══ 4.135. _getcwd - Get Path Name of Current Directory ═══ ═══ Format ═══ #include char *_getcwd(char *pathbuf, int n); ═══ Description ═══ Language Level: Extension _getcwd 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. Return Value _getcwd 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 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 ═══ /************************************************************************ 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 (NULL == getcwd(buffer, _MAX_PATH)) 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 ═══ Example of _getcwd  chdir - Change Current Working Directory  _fullpath - Get Full Path Name of Partial Path  _getdcwd - Get Full Path Name of Current Directory  _getdrive - Get Current Working Drive  malloc - Reserve Storage Block  ═══ 4.136. _getdcwd - Get Full Path Name of Current Directory ═══ ═══ Format ═══ #include char *_getdcwd(int drive, char *pathbuf, int n); ═══ Description ═══ Language Level: Extension _getdcwd 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. Alternatives to this function are the DosQueryCurrentDir and DosQueryCurrentDisk API calls. Return Value _getdcwd 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 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 _getdcwd ═══ /************************************************************************ 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 (NULL == retBuffer) printf("An error has occurred, errno is set to %d.\n", errno); else printf("%s is the current working directory in drive C.\n", retBuffer); return 0; /**************************************************************************** The output should be similar to: C:\ is the current working directory in drive C. ****************************************************************************/ } ═══ Related Information ═══ Example of _getdcwd  chdir - Change Current Working Directory  _chdrive - Change Current Working Drive  _fullpath - Get Full Path Name of Partial Path  _getcwd - Get Path Name of Current Directory  _getdrive - Get Current Working Drive  malloc - Reserve Storage Block  ═══ 4.137. _getdrive - Get Current Working Drive ═══ ═══ Format ═══ #include int _getdrive(void); ═══ Description ═══ Language Level: Extension _getdrive gets the drive number for the current working drive. An alternative to this function is the DosQueryCurrentDisk API call. Return Value _getdrive 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. ═══ 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; /**************************************************************************** The output should be similar to: Current working drive is 5. ****************************************************************************/ } ═══ Related Information ═══ Example of _getdrive  chdir - Change Current Working Directory  _chdrive - Change Current Working Drive  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  ═══ 4.138. getenv - Search for Environment Variables ═══ ═══ Format ═══ #include char *getenv(const char *varname); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 getenv searches the list of environment variables for an entry corresponding to varname. Return Value getenv 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 ═══ /************************************************************************ In this example, pathvar points to the value of the PATH environment variable. ************************************************************************/ #include int main(void) { char *pathvar; pathvar = getenv("PATH"); if (NULL == pathvar) printf("Environment variable PATH is not defined.\n"); else printf("Path set by environment variable PATH is successfully stored.\n"); return 0; /**************************************************************************** The output should be: Path set by environment variable PATH is successfully stored. ****************************************************************************/ } ═══ Related Information ═══ Example of getenv  putenv - Modify Environment Variables  ═══ 4.139. getmccoll - Get Next Collating Element from String ═══ ═══ Format ═══ #include collel_t getmccoll(char **src) ═══ Description ═══ Language Level: Extension getmccoll finds the first sequence of characters in the array pointed to by src that constitute a valid multicharacter collating element. It then produces the collel_t value that corresponds to that collating element. It also changes src to point to the next byte following that collating element. Return Value getmccoll returns the collel_t value that represents the collating element found. If the object pointed to by src is a null pointer or points to a null character, getmccoll returns 0. ═══ Example of getmccoll ═══ /************************************************************************ This example uses getmccoll to find the first collating element in the string "de xyz" in the France locale. ************************************************************************/ #include #include #include int main(void) { char s[] = "de xyz"; char *str = s; collel_t x; if (NULL == setlocale(LC_ALL, LC_C_FRANCE)) { printf("Setlocale(LC_ALL, LC_A_FRANCE) failed.\n"); exit(1); } x = getmccoll(&str); printf("getmccoll(\"%s\")\n", s); printf(" returns: \"%s\"\n", colltostr(x)); printf(" remainder of string: \"%s\"\n", str); return 0; /**************************************************************************** The output should be similar to : getmccoll("de xyz") returns: "de " remainder of string: "xyz" ****************************************************************************/ } ═══ Related Information ═══ Example of getmccoll  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.140. getpid - Get Process Identifier ═══ ═══ Format ═══ #include int getpid(void); ═══ Description ═══ Language Level: XPG4, Extension getpid gets the process identifier that uniquely identifies the calling process. Note: In earlier releases of C Set ++, getpid began with an underscore (_getpid). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _getpid to getpid for you. Return Value getpid function the process identifier as an integer value. There is no error return value. ═══ Example of getpid ═══ /************************************************************************ This example prints the process identifier: ************************************************************************/ #include #include #include #include int main(void) { printf("Process identifier is %05d\n", getpid()); return 0; /**************************************************************************** The output should be similar to: Process identifier is 00242 ****************************************************************************/ } ═══ Related Information ═══ Example of getpid  _cwait - Wait for Child Process  execl - _execvpe - Load and Run Child Process  _spawnl - _spawnvpe - Start and Run Child Processes  wait - Wait for Child Process  ═══ 4.141. gets - Read a Line ═══ ═══ Format ═══ #include char *gets(char *buffer); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 gets 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. gets then replaces the new-line character, if read, with a null character (\0) before returning the line. Return Value If successful, gets 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 ═══ /************************************************************************ 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"); printf("Input line : %s\n", result); } return 0; /**************************************************************************** For the following input: This is a test for function gets. The output should be: Input line : This a test for function gets. ****************************************************************************/ } ═══ Related Information ═══ Example of gets  _cgets - Read String of Characters from Keyboard  fgets - Read a String  feof - Test End-of-File Indicator  ferror - Test for Read/Write Errors  fputs - Write String  getc - getchar - Read a Character  puts - Write a String  ═══ 4.142. getsyntx - Return LC_SYNTAX Characters ═══ ═══ Format ═══ #include struct variant *getsyntx(void); ═══ Description ═══ Language Level: Extension getsyntx determines the encoding of the special characters defined in the LC_SYNTAX category of the current locale, and stores the encoding values in the structure of type struct variant. For details of the structure type, see . Your program cannot modify the returned structure. The structure can be overwritten by a call to setlocale with the argument LC_ALL or LC_SYNTAX. Return Value getsyntx returns the pointer to the structure containing the values of the special characters. If the information about the special characters is not available in the current locale, getsyntx returns a null pointer. ═══ Example of getsyntx ═══ /************************************************************************ This example uses getsyntx to show the value of various special characters. ************************************************************************/ #include #include #include int main(void) { struct variant *var; setlocale(LC_ALL, LC_C_USA); var = getsyntx(); printf("codeset : %s\n", var->codeset ); printf("backslash : %c\n", var->backslash ); printf("right_bracket : %c\n", var->right_bracket ); printf("left_bracket : %c\n", var->left_bracket ); printf("right_brace : %c\n", var->right_brace ); printf("left_brace : %c\n", var->left_brace ); printf("circumflex : %c\n", var->circumflex ); printf("tilde : %c\n", var->tilde ); printf("exclamation_mark: %c\n", var->exclamation_mark); printf("number_sign : %c\n", var->number_sign ); printf("vertical_line : %c\n", var->vertical_line ); printf("dollar_sign : %c\n", var->dollar_sign ); printf("commercial_at : %c\n", var->commercial_at ); printf("grave_accent : %c\n", var->grave_accent ); return 0; /**************************************************************************** The output should be similar to : codeset : IBM-850 backslash : \ right_bracket : ] left_bracket : [ right_brace : } left_brace : { circumflex : ^ tilde : ~ exclamation_mark: ! number_sign : # vertical_line : | dollar_sign : $ commercial_at : @ grave_accent : ` ****************************************************************************/ } ═══ Related Information ═══ Example of getsyntx  setlocale - Set Locale   ═══ 4.143. _getTIBvalue - Get Thread Information Block Value ═══ ═══ Format ═══ #include unsigned long _getTIBvalue(const unsigned int offset); ═══ Description ═══ Language Level: Extension _getTIBvalue 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. Note: _getTIBvalue is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _getTIBvalue.  You cannot parenthesize a call to _getTIBvalue. (Parentheses specify a call to the function's backing code, and _getTIBvalue has none.) Return Value _getTIBvalue returns an unsigned long value from the TIB. There is no error return value and _getTIBvalue does not set errno. If offset is too large, it will cause an access violation when running the program. ═══ Example of _getTIBvalue ═══ /************************************************************************ This example prints out all the values in the TIB structure. ************************************************************************/ #define INCL_DOS #include #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; /**************************************************************************** The output should be similar to : Values in Thread Information Block are: Exception chain pointer: 38844 Base stack address: 30000 End of stack address: 38860 System specific TIB pointer: 50048 Version number: 20 Ordinal number: 122 ****************************************************************************/ } ═══ Related Information ═══ Example of _getTIBvalue  _threadstore - Access Thread-Specific Storage  ═══ 4.144. getwc - Read Wide Character from Stream ═══ ═══ Format ═══ #include #include wint_t getwc(FILE *stream); ═══ Description ═══ Language Level: ANSI 93, XPG4 getwc reads the next multibyte character from stream, converts it to a wide character, and advances the associated file position indicator for stream. getwc is equivalent to fgetwc except that, if it is implemented as a macro, it can evaluate stream more than once. Therefore, the argument should never be an expression with side effects. The behavior of getwc is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent read operations on the same stream, undefined results can occur. Using non-wide-character functions with getwc on the same stream results in undefined behavior. After calling getwc, flush the buffer or reposition the stream pointer before calling a write function for the stream, unless EOF has been reached. After a write operation on the stream, flush the buffer or reposition the stream pointer before calling getwc. Return Value getwc returns the next wide character from the input stream, or WEOF. If an error occurs, getwc sets the error indicator. If getwc encounters the end-of-file, it sets the EOF indicator. If an encoding error occurs during conversion of the multibyte character, getwc sets errno to EILSEQ. Use ferror or feof to determine whether an error or an EOF condition occurred. EOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator. ═══ Example of getwc ═══ /************************************************************************ This example opens a file and uses getwc to read wide characters from the file. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wint_t wc; if (NULL == (stream = fopen("getwc.dat", "r"))) { printf("Unable to open: \"getwc.dat\".\n"); exit(1); } errno = 0; while (WEOF !=(wc = getwc(stream))) printf("wc = %lc\n", wc); if (EILSEQ == errno) { printf("An invalid wide character was encountered.\n"); exit(1); } fclose(stream); return 0; /**************************************************************************** Assuming the file getwc.dat contains: Hello world! The output should be: wc = H wc = e wc = l wc = l wc = o : ****************************************************************************/ } ═══ Related Information ═══ Example of getwc  fgetwc - Read Wide Character from Stream  getwchar - Get Wide Character from stdin  getc - getchar - Read a Character  _getch - _getche - Read Character from Keyboard  putwc - Write Wide Character   ═══ 4.145. getwchar - Get Wide Character from stdin ═══ ═══ Format ═══ #include wint_t getwchar(void); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 getwchar reads the next multibyte character from stdin, converts it to a wide character, and advances the associated file position indicator for stdin. A call to getwchar is equivalent to a call to getwc(stdin). The behavior of getwchar is affected by the LC_CTYPE category of the current locale. If you change the category between subsequent read operations on the same stream, undefined results can occur. Using non-wide-character functions with getwchar on the same stream results in undefined behavior. Return Value getwchar returns the next wide character from stdin or WEOF. If getwchar encounters EOF, it sets the EOF indicator for the stream and returns WEOF. If a read error occurs, the error indicator for the stream is set and getwchar returns WEOF. If an encoding error occurs during the conversion of the multibyte character to a wide character, getwchar sets errno to EILSEQ and returns WEOF. Use ferror or feof to determine whether an error or an EOF condition occurred. EOF is only reached when an attempt is made to read past the last byte of data. Reading up to and including the last byte of data does not turn on the EOF indicator. ═══ Example of getwchar ═══ /************************************************************************ This example uses getwchar to read wide characters from the keyboard, then prints the wide characters. ************************************************************************/ #include #include #include int main(void) { wint_t wc; errno = 0; while (WEOF != (wc = getwchar())) printf("wc = %lc\n", wc); if (EILSEQ == errno) { printf("An invalid wide character was encountered.\n"); exit(1); } return 0; /**************************************************************************** Assuming you enter: abcde^Z (note: ^Z is CNTRL-Z) The output should be: wc = a wc = b wc = c wc = d wc = e ****************************************************************************/ } ═══ Related Information ═══ Example of getwchar  fgetc - Read a Character  _fgetchar - Read Single Character from stdin  getc - getchar - Read a Character  _getch - _getche - Read Character from Keyboard  getwc - Read Wide Character from Stream  ═══ 4.146. getwmccoll - Get Next Collating Element from Wide String ═══ ═══ Format ═══ #include #include collel_t getwmccoll(wchar_t **src); ═══ Description ═══ Language Level: Extension getwmccoll finds the first sequence of wide characters in the array pointed to by src that constitute a valid multi-wide-character collating element. It then produces the collel_t value that corresponds to that collating element. It also changes src to point to the next byte following that collating element. Return Value getwmccoll returns the collel_t value that represents the collating element found. If the object pointed to by src is a null pointer or points to a null wide character, getwmccoll returns 0. If the object pointed to by src points to an invalid wide character, getwmccoll returns -1 and sets errno to EILSEQ. ═══ Example of getwmccoll ═══ /************************************************************************ This example uses getwmccoll to find the first collating element in the wide string s. ***********************************************************************/ #include #include #include #include int main(void) { wchar_t s[] = L"\x8141\x64"; wchar_t *str = s; collel_t x; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("Setlocale(LC_ALL, \"ja_jp.ibm-932\") failed.\n"); exit(1); } x = getwmccoll(&str); printf("getwmccoll(\"%s\")\n", s); printf(" returns: 0x%x\n", x); printf(" remainder of string: <%s>\n", str); return 0; /**************************************************************************** The output should be similar to : getwmccoll("A─d") returns: 0x8141 remainder of string: ****************************************************************************/ } ═══ Related Information ═══ Example of getwmccoll  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String   ═══ 4.147. gmtime - Convert Time ═══ ═══ Format ═══ #include struct tm *gmtime(const time_t *time); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 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 value time is usually obtained from a call to time. The fields of the tm structure include: 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. Return Value gmtime returns a pointer to the resulting tm structure. It 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 ═══ /************************************************************************ This example uses gmtime 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))); return 0; /**************************************************************************** The output should be similar to: Coordinated Universal Time is Mon Sep 16 21:44 1995 ****************************************************************************/ } ═══ Related Information ═══ Example of gmtime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  localtime - Convert Time  mktime - Convert Local Time  time - Determine Current Time  ═══ 4.148. _heap_check - Validate Default Memory Heap ═══ ═══ Format ═══ #include /* also in */ void _heap_check(void); ═══ Description ═══ Language Level: Extension _heap_check checks all memory blocks in the default heap that have been allocated or freed using the debug memory management functions (_debug_calloc, _debug_malloc, and so on). _heap_check checks that your program has not overwritten freed memory blocks or memory outside the bounds of allocated blocks. When you call a debug memory management function (such as _debug_malloc), it calls _heap_check automatically. You can also call _heap_check explicitly. Place calls to _heap_check throughout your code, especially in areas that you suspect have memory problems. Calling _heap_check frequently (explicitly or through the debug memory functions) can increase your program's memory requirements and decrease its execution speed. To reduce the overhead of heap-checking, you can use the DDE4_HEAP_SKIP environment variable to control how often the functions check the heap. For example: SET DDE4_HEAP_SKIP=10 specifies that every tenth call to any debug memory function (regardless of the type or heap) checks the heap. Explicit calls to _heap_check are always performed. For more details on DDE4_HEAP_SKIP, see "Skipping Heap Checks" in the Programming Guide. To use _heap_check and the debug memory management functions, you must compile with the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Heap-specific and tiled versions of this function (_uheap_check and _theap_check) are also available. _heap_check always checks the default heap. Return Value There is no return value. ═══ 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. ************************************************************************/ #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(5000))) { puts("Could not allocate memory block."); return EXIT_FAILURE; } *(ptr-1) = 'a'; /* overwrites storage that was not allocated */ _heap_check(); puts("_heap_check did not detect that a memory block was overwritten."); return 0; /**************************************************************************** The output should be similar to: Header information of object 0x00073890 was overwritten at 0x0007388c. The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA. This memory block was (re)allocated at line number 8 in _heap_check.c. Heap state was valid at line 8 of _heap_check.c. Memory error detected at line 14 of _heap_check.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _heap_check  Memory Management in the Programming Guide  Debugging Your Heaps in the Programming Guide  Differentiating between Memory Management Functions  _debug_calloc - Allocate and Initialize Memory  _debug_free - Release Memory  _debug_heapmin - Release Unused Memory in the Default Heap  _debug_malloc - Allocate Memory  _debug_realloc - Reallocate Memory Block  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _heapchk - Validate Default Memory Heap  _uheap_check - Validate User Memory Heap   ═══ 4.149. _heapchk - Validate Default Memory Heap ═══ ═══ Format ═══ #include int _heapchk(void); ═══ Description ═══ Language Level: Extension _heapchk checks the default storage heap for minimal consistency by checking all allocated and freed objects on the heap. A heap-specific version of this function, _uheapchk, is also available. Note: Using the _heapchk, _heapset, and _heap_walk functions (and their heap-specific equivalents) may add overhead to each object allocated from the heap. Return Value _heapchk returns one of the following values, defined in : _HEAPBADBEGIN The heap specified is not valid. (Only occurs if you changed the default heap and then later closed or destroyed it.) _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. ═══ Example of _heapchk ═══ /************************************************************************ This example performs some memory allocations, then calls _heapchk to check the heap. ***********************************************************************/ #include #include #include int main(void) { char *ptr; int rc; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } *(ptr - 1) = 'x'; /* overwrites storage that was not allocated */ if (_HEAPOK != (rc = _heapchk())) { switch(rc) { case _HEAPEMPTY: puts("The heap has not been initialized."); break; case _HEAPBADNODE: puts("A memory node is corrupted or the heap is damaged."); break; case _HEAPBADBEGIN: puts("The heap specified is not valid."); break; } exit(rc); } free(ptr); return 0; /**************************************************************************** The output should be similar to : A memory node is corrupted or the heap is damaged. ****************************************************************************/ } ═══ Related Information ═══ Example of _heapchk  "Managing Memory" in the Programming Guide  _uheapchk - Validate Memory Heap  _heapmin - Release Unused Memory from Default Heap  _heapset - Validate and Set Default Heap  _heap_walk - Return Information about Default Heap   ═══ 4.150. _heapmin - Release Unused Memory from Default Heap ═══ ═══ Format ═══ #include /* also in */ int _heapmin(void); ═══ Description ═══ Language Level: Extension _heapmin returns all unused memory from the default runtime heap to the operating system. Heap-specific, tiled, and debug versions of this function (_uheapmin, _theapmin, and _debug_heapmin) are also available. _heapmin always operates on the default heap. Note: If you create your own heap and make it the default heap, _heapmin calls the release function that you provide to return the memory. Return Value _heapmin returns 0 if successful; if not, it returns -1. ═══ 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 output should be: _heapmin was successful. ****************************************************************************/ } ═══ Related Information ═══ Example of _heapmin  Managing Memory in the Programming Guide  _debug_heapmin - Release Unused Memory in the Default Heap  _debug_theapmin - Release Unused Tiled Memory  _debug_uheapmin - Release Unused Memory in User Heap  _theapmin - Release Unused Tiled Memory  _uheapmin - Release Unused Memory in User Heap   ═══ 4.151. _heapset - Validate and Set Default Heap ═══ ═══ Format ═══ #include int _heapset(unsigned int fill); ═══ Description ═══ Language Level: Extension _heapset checks the default storage heap for minimal consistency by checking all allocated and freed objects on the heap (similar to _heapchk). It then sets each byte of the heap's free objects to the value of fill. Using _heapset can help you locate problems where your program continues to use a freed pointer to an object. After you set the free heap to a specific value, when your program tries to interpret the set values in the freed object as data, unexpected results occur, indicating a problem. A heap-specific version of this function, _uheapset, is also available. Note: Using the _heapchk, _heapset, and _heap_walk functions (and their heap-specific equivalents) may add overhead to each object allocated from the heap. Return Value _heapset returns one of the following values, defined in : _HEAPBADBEGIN The heap specified is not valid; it may have been closed or destroyed. _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. ═══ Example of _heapset ═══ /************************************************************************ This example allocates and frees memory, then uses _heapset to set the free heap to X. It checks the return code from _heapset to ensure the heap is still valid. *********************************************************************** / #include #include #include int main (void) { char *ptr; int rc; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr,'A',5); free(ptr); if (_HEAPOK != (rc = _heapset('X'))) { switch(rc) { case _HEAPEMPTY: puts("The heap has not been initialized."); break; case _HEAPBADNODE: puts("A memory node is corrupted or the heap is damaged."); break; case _HEAPBADBEGIN: puts("The heap specified is not valid."); break; } exit(rc); } return 0; } ═══ Related Information ═══ Example of _heapset  "Managing Memory" in the Programming Guide  _heapchk - Validate Default Memory Heap  _heapmin - Release Unused Memory from Default Heap  _heap_walk - Return Information about Default Heap  _uheapset - Validate and Set Memory Heap   ═══ 4.152. _heap_walk - Return Information about Default Heap ═══ ═══ Format ═══ #include int _heap_walk(int (*callback_fn)(const void *object, size_t size, int flag, int status, const char* file, int line) ); ═══ Description ═══ Language Level: Extension _heap_walk traverses the default heap, and for each allocated or freed object, it calls the callback_fn function that you provide. For each object, it passes your function: object A pointer to the object. size The size of the object. flag The value _USEDENTRY if the object is currently allocated, or _FREEENTRY if the object has been freed. (Both values are defined in .) status One of the following values, defined in , depending on the status of the object: _HEAPBADBEGIN The heap specified is not valid; it may have been closed or destroyed. _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. file The name of the file where the object was allocated. line The line where the object was allocated. _heap_walk provides information about all objects, regardless of which memory management functions were used to allocate them. However, the file and line information are only available if the object was allocated and freed using the debug versions of the memory management functions. Otherwise, file is NULL and line is 0. _heap_walk calls callback_fn for each object until one of the following occurs:  All objects have been traversed.  callback_fn returns a nonzero value to _heap_walk.  It cannot continue because of a problem with the heap. You may want to code your callback_fn to return a nonzero value if the status of the object is not _HEAPOK. Even if callback_fn returns 0 for an object that is corrupted, _heap_walk cannot continue because of the state of the heap and returns to its caller. You can use callback_fn to process the information from _heap_walk in various ways. For example, you may want to print the information to a file or use it to generate your own error messages. You can use the information to look for memory leaks and objects incorrectly allocated or freed from the heap. It can be especially useful to call _heap_walk when _heapchk returns an error. A heap-specific version of this function, _uheap_walk, is also available. Note: 1. Using the _heapchk, _heapset, and _heap_walk functions (and their heap-specific equivalents) may add overhead to each object allocated from the heap. 2. _heap_walk locks the heap while it traverses it, to ensure that no other operations use the heap until _heap_walk finishes. As a result, in your callback_fn, you cannot call any critical functions in the runtime library, either explicitly or by calling another function that calls a critical function. See the Programming Guide for a list of critical functions. Return Value _heap_walk returns the last value of status to the caller. ═══ Example of _heap_walk ═══ /************************************************************************ This example allocates some memory, then uses _heap_walk to walk the heap and pass information about allocated objects to the callback function callback_function. callback_function then checks the information and keeps track of the number of allocated objects. *********************************************************************** / #include #include #include int callback_function(const void *pentry, size_t sz, int useflag, int status, const char *filename, size_t line) { if (_HEAPOK != status) { puts("status is not _HEAPOK."); exit(status); } if (_USEDENTRY == useflag) printf("allocated %p %u\n", pentry, sz); else printf("freed %p %u\n", pentry, sz); return 0; } int main(void) { char *p1, *p2, *p3; if (NULL == (p1 = malloc(100)) || NULL == (p2 = malloc(200)) || NULL == (p3 = malloc(300))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } free(p2); puts("usage address size\n----- ------- ----"); _heap_walk(callback_function); free(p1); free(p3); return 0; /**************************************************************************** The output should be similar to : usage address size ----- ------- ---- allocated 73A10 300 allocated 738B0 100 : : freed 73920 224 ****************************************************************************/ } ═══ Related Information ═══ Example of _heap_walk  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  _heapchk - Validate Default Memory Heap  _heapmin - Release Unused Memory from Default Heap  _heapset - Validate and Set Default Heap  _uheap_walk - Return Information about Memory Heap  ═══ 4.153. hypot - Calculate Hypotenuse ═══ ═══ Format ═══ #include double hypot(double side1, double side2); ═══ Description ═══ Language Level: SAA, XPG4 hypot 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 equivalent to: sqrt(side1 * side1 + side2 * side2); Return Value hypot returns the length of the hypotenuse. If an overflow results, hypot sets errno to ERANGE and returns the value HUGE_VAL. If an underflow results, hypot sets errno to ERANGE and returns zero. ═══ 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); return 0; /**************************************************************************** The output should be: The hypotenuse of the triangle with sides 3.000000 and 4.000000 is 5.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of hypot  _fsqrt - Calculate Square Root  sqrt - Calculate Square Root  ═══ 4.154. iconv - Convert Characters to New Code Set ═══ ═══ Format ═══ #include size_t iconv(iconv_t cd, char **inbuf, size_t *insize, char **outbuf, size_t *outsize); ═══ Description ═══ Language Level: XPG4 iconv converts a sequence of characters in one encoded character set, in the array indirectly pointed to by inbuf and converts them to a sequence of corresponding characters in another encoded character set. It stores the corresponding sequence in the array indirectly pointed to by outbuf. cd is the conversion descriptor returned from iconv_open that describes which codesets are used in the conversion. inbuf points to a variable that points to the first character of input, and insize indicates the number of bytes of input. outbuf points to a variable that points to the first character of output, and outsize indicates the number of available bytes for output. As iconv converts the characters, it updates the variable pointed to by inbuf to point to the next byte in the input buffer, and updates the variable pointed to by outbut to the byte following the last successfully converted character. It also decrements insize and outsize to reflect the number of bytes of input remaining and the number of bytes still available for output, respectively. If the entire input string is converted, insize will be 0; if an error stops the conversion, insize will have a nonzero value. If it encounters a valid input character that does not have a defined conversion in cd, iconv translates the character to the ASCII value 0x1a. Sharing a conversion descriptor in iconv across multiple threads may result in undefined behavior. Return Value iconv returns the number of characters successfully converted. If an error occurs, conversion stops after the previous successfully converted character; iconv returns (size_t)-1, and sets errno to one of the following values: Value Meaning EILSEQ A sequence of input bytes does not form a valid character in the specified encoded character set. E2BIG outbuf is not large enough to hold the converted value. EINVAL The input ends with an incomplete character. EBADF cd is not a valid conversion descriptor. ═══ Example of iconv ═══ /************************************************************************ This example converts an array of characters coded in encoded character set IBM-850 (in in) to an array of characters coded in encoded character set IBM-037 (stored in out). ************************************************************************/ #include #include #include int main(void) { const char fromcode[] = "IBM-850"; const char tocode[] = "IBM-037"; iconv_t cd; char in[] = "ABCDEabcde"; size_t in_size; char *inptr = in; char out[100]; size_t out_size = sizeof(out); char *outptr = out; int i; if ((iconv_t)(-1) == (cd = iconv_open(tocode, fromcode))) { printf("Failed to iconv_open %s to %s.\n", fromcode, tocode); exit(EXIT_FAILURE); } /* Convert the first 3 characters in array "in". */ in_size = 3; if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) { printf("Fail to convert first 3 characters to new code set.\n"); exit(EXIT_FAILURE); } /* Convert the rest of the characters in array "in". */ in_size = sizeof(in) - 3; if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) { printf("Fail to convert the rest of the characters to new code set.\n"); exit(EXIT_FAILURE); } *outptr = '\0'; printf("The hex representation of string %s are:\n In codepage %s ==> ", in, fromcode); for (i = 0; in[i] != '\0'; i++) { printf("0x%02x ", in[i]); } printf("\n In codepage %s ==> ", tocode); for (i = 0; out[i] != '\0'; i++) { printf("0x%02x ", out[i]); } if (-1 == iconv_close(cd)) { printf("Fail to iconv_close.\n"); exit(EXIT_FAILURE); } return 0; /**************************************************************************** The output should be similar to : The hex representation of string ABCDEabcde are: In codepage IBM-850 ==> 0x41 0x42 0x43 0x44 0x45 0x61 0x62 0x63 0x64 0x65 In codepage IBM-037 ==> 0xc1 0xc2 0xc3 0xc4 0xc5 0x81 0x82 0x83 0x84 0x85 ****************************************************************************/ } ═══ Related Information ═══ Example of iconv  iconv_close - Remove Conversion Descriptor  iconv_open - Create Conversion Descriptor  setlocale - Set Locale  "Introduction to Locale" in the Programming Guide  ═══ 4.155. iconv_close - Remove Conversion Descriptor ═══ ═══ Format ═══ #include int iconv_close(iconv_t cd); ═══ Description ═══ Language Level: XPG4 iconv_close deallocates the conversion descriptor cd and all other associated resources allocated by the iconv_open function. Return Value If successful, iconv_close returns 0. Otherwise, iconv_close returns -1 is returned and sets errno to indicate the cause of the error. If cd is not a valid descriptor, an error occurs and iconv_close sets errno to EBADF. ═══ Example of iconv_close ═══ /************************************************************************ This example shows how you would use iconv_close to remove a conversion descriptor. ************************************************************************/ #include #include #include int main(void) { const char fromcode[] = "IBM-850"; const char tocode[] = "IBM-863"; iconv_t cd; if ((iconv_t)(-1) == (cd = iconv_open(tocode, fromcode))) { printf("Failed to iconv_open %s to %s.\n", fromcode, tocode); exit(EXIT_FAILURE); } if (-1 == iconv_close(cd)) { printf("Fail to iconv_close.\n"); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of iconv_close  iconv - Convert Characters to New Code Set  iconv_open - Create Conversion Descriptor  setlocale - Set Locale  "Introduction to Locale" in the Programming Guide  ═══ 4.156. iconv_open - Create Conversion Descriptor ═══ ═══ Format ═══ #include iconv_t iconv_open(const char *tocode, const char *fromcode); ═══ Description ═══ Language Level: XPG4 iconv_open performs all the initialization needed to convert characters from the encoded character set specified in the array pointed to by fromcode to the encoded character set specified in the array pointed to by tocode. It creates a conversion descriptor that relates the two encoded character sets. You can then use the conversion descriptor with the iconv function to convert characters between the codesets. The conversion descriptor remains valid until you close it with iconv_close. For information about the settings of fromcode, tocode, and their permitted combinations, see the section on internationalization in the Programming Guide. Return Value If successful, iconv_open returns a conversion descriptor of type iconv_t. Otherwise, it returns (iconv_t)-1, and sets errno to indicate the error. If you cannot convert between the encoded character sets specified, an error occurs and iconv_open sets errno to EINVAL. ═══ Example of iconv_open ═══ /************************************************************************ This example shows how to use iconv_open, iconv, and iconv_close to convert characters from one codeset to another. ************************************************************************/ #include #include #include int main(void) { const char fromcode[] = "IBM-932"; const char tocode[] = "IBM-930"; iconv_t cd; char in[] = "\x81\x40\x81\x80"; size_t in_size = sizeof(in); char *inptr = in; char out[100]; size_t out_size = sizeof(out); char *outptr = out; int i; if ((iconv_t)(-1) == (cd = iconv_open(tocode, fromcode))) { printf("Failed to iconv_open %s to %s.\n", fromcode, tocode); exit(EXIT_FAILURE); } if ((size_t)(-1) == iconv(cd, &inptr, &in_size, &outptr, &out_size)) { printf("Fail to convert characters to new code set.\n"); exit(EXIT_FAILURE); } *outptr = '\0'; printf("The hex representation of string %s are:\n In codepage %s ==> ", in, fromcode); for (i = 0; in[i] != '\0'; i++) { printf("0x%02x ", in[i]); } printf("\n In codepage %s ==> ", tocode); for (i = 0; out[i] != '\0'; i++) { printf("0x%02x ", out[i]); } if (-1 == iconv_close(cd)) { printf("Fail to iconv_close.\n"); exit(EXIT_FAILURE); } return 0; /**************************************************************************** The output should be similar to : The hex representation of string ─@─Д are: In codepage IBM-932 ==> 0x81 0x40 0x81 0x80 In codepage IBM-930 ==> 0x0e 0x40 0x40 0x44 0x7b 0x0f ****************************************************************************/ } ═══ Related Information ═══ Example of iconv_open  iconv - Convert Characters to New Code Set  iconv_close - Remove Conversion Descriptor  setlocale - Set Locale  "Introduction to Locale" in the Programming Guide  ═══ 4.157. _inp - Read Byte from Input Port ═══ ═══ Format ═══ #include /* also in */ int _inp(const unsigned int port); ═══ Description ═══ Language Level: Extension _inp 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. Note: _inp is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _inp.  You cannot parenthesize a call to _inp. (Parentheses specify a call to the function's backing code, and _inp has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _inp returns the byte value as an integer that was read from the specified port. There is no error return value, and _inp does not set errno. ═══ Example of _inp ═══ /************************************************************************ This example uses _inp 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, cantaloupes}; int arr[] = {cantaloupes, 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 ═══ Example of _inp  _inpw - Read Unsigned Short from Input Port  _inpd - Read Doubleword from Input Port  isatty - Test Handle for Character Device  _outp - Write Byte to Output Port  _outpw - Write Word to Output Port  _outpd - Write Double Word to Output Port   ═══ 4.158. _inpd - Read Doubleword from Input Port ═══ ═══ Format ═══ #include /* also in */ unsigned long _inpd(const unsigned int port); ═══ Description ═══ Language Level: Extension _inpd reads a 4-byte (doubleword) unsigned value from the specified input port. The port number must be an unsigned short value within the range 0 to 65 535 inclusive. Note: _inpd is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _inpd.  You cannot parenthesize a call to _inpd. (Parentheses specify a call to the function's backing code, and _inpd has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _inpd returns the value read from the specified port. There is no error return value, and _inpd does not set errno. ═══ Example of _inpd ═══ /************************************************************************ This example uses _inpd to read a doubleword 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, cantaloupes}; int arr[] = {cantaloupes, 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(cantaloupes)); /* - 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 ═══ Example of _inpd  _inp - Read Byte from Input Port  _inpw - Read Unsigned Short from Input Port  isatty - Test Handle for Character Device  _outp - Write Byte to Output Port  _outpw - Write Word to Output Port  _outpd - Write Double Word to Output Port   ═══ 4.159. _inpw - Read Unsigned Short from Input Port ═══ ═══ Format ═══ #include /* also in */ unsigned short _inpw(const unsigned int port); ═══ Description ═══ Language Level: Extension _inpw 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. Note: _inpw is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _inpw.  You cannot parenthesize a call to _inpw. (Parentheses specify a call to the function's backing code, and _inpw has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _inpw returns the value read from the specified port. There is no error return value, and _inpw does not set errno. ═══ Example of _inpw ═══ /************************************************************************ This example uses _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, cantaloupes}; int arr[] = {cantaloupes, 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,cantaloupes)); /* - return value from a */ /* builtin function call */ /* --------------------------- */ return 0; } int Add1(int j) { j += 1; return j; } ═══ Related Information ═══ Example of _inpw  _inp - Read Byte from Input Port  _inpd - Read Doubleword from Input Port  isatty - Test Handle for Character Device  _outp - Write Byte to Output Port  _outpw - Write Word to Output Port  _outpd - Write Double Word to Output Port   ═══ 4.160. _interrupt - Call Interrupt Procedure ═══ ═══ Format ═══ #include void _interrupt(const unsigned int intnum); ═══ Description ═══ Language Level: Extension _interrupt 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. Note: _interrupt is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _interrupt.  You cannot parenthesize a call to _interrupt. (Parentheses specify a call to the function's backing code, and _interrupt has none.) Return Value There is no return value, and _interrupt does not set errno. ═══ Example of _interrupt ═══ /************************************************************************ This example calls 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 ═══ Example of _interrupt  _disable - Disable Interrupts  _enable - Enable Interrupts  ═══ 4.161. isalnum to isxdigit - Test Integer Value ═══ ═══ Format ═══ #include /* test for: */ int isalnum(int c); /* alphanumeric character */ int isalpha(int c); /* alphabetic character */ int iscntrl(int c); /* control character */ int isdigit(int c); /* decimal digit */ int isgraph(int c); /* printable character, excluding space */ int islower(int c); /* lowercase character */ int isprint(int c); /* printable character, including space */ int ispunct(int c); /* nonalphanumeric printable character, excluding space */ int isspace(int c); /* whitespace character */ int isupper(int c); /* uppercase character */ int isxdigit(int c); /* hexadecimal digit */ ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 These functions test a given integer value c to determine if it has a certain property as defined by the LC_CTYPE category of your current locale. The value of c must be representable as an unsigned char, or EOF. The functions test for the following: isalnum Alphanumeric character (upper- or lowercase letter, or decimal digit), as defined in the locale source file in the alnum class of the LC_CTYPE category of the current locale. isalpha Alphabetic character, as defined in the locale source file in the alpha class of the LC_CTYPE category of the current locale. iscntrl Control character, as defined in the locale source file in the cntrl class of the LC_CTYPE category of the current locale. isdigit Decimal digit (0 through 9), as defined in the locale source file in the digit class of the LC_CTYPE category of the current locale. isgraph Printable character, excluding the space character, as defined in the locale source file in the graph class of the LC_CTYPE category of the current locale. islower Lowercase letter, as defined in the locale source file in the lower class of the LC_CTYPE category of the current locale. isprint Printable character, including the space character, as defined in the locale source file in the print class of the LC_CTYPE category of the current locale. ispunct Nonalphanumeric printable character, excluding the space character, as defined in the locale source file in the punct class of the LC_CTYPE category of the current locale. isspace White-space character, as defined in the locale source file in the space class of the LC_CTYPE category of the current locale. isupper Uppercase letter, as defined in the locale source file in the upper class of the LC_CTYPE category of the current locale. isxdigit Hexadecimal digit (0 through 9, a through f, or A through F), as defined in the locale source file in the xdigit class of the LC_CTYPE category of the current locale. You can redefine any character class in the LC_CTYPE category of the current locale, with some restrictions. See the section about the LC_CTYPE class in the Programming Guide for details about these restrictions. Return Value These functions return a nonzero value if the integer satisfies the test condition, or 0 if it does not. ═══ Example of isalnum to isxdigit ═══ /************************************************************************ This example analyzes all characters between 0x0 and 0xFF. The output of this example is a 256-line table showing the characters from 0 to 255, indicating whether they have the properties tested for. ************************************************************************/ #include #include #include #define UPPER_LIMIT 0xFF int main(void) { int ch; setlocale(LC_ALL, LC_C_USA); for (ch = 0; ch <= UPPER_LIMIT; ++ch) { printf("%#04x ", ch); printf("%c", isprint(ch) ? ch : ' '); printf("%s", isalnum(ch) ? " AN" : " "); printf("%s", isalpha(ch) ? " A " : " "); printf("%s", iscntrl(ch) ? " C " : " "); printf("%s", isdigit(ch) ? " D " : " "); printf("%s", isgraph(ch) ? " G " : " "); printf("%s", islower(ch) ? " L " : " "); printf("%s", ispunct(ch) ? " PU" : " "); printf("%s", isspace(ch) ? " S " : " "); printf("%s", isprint(ch) ? " PR" : " "); printf("%s", isupper(ch) ? " U " : " "); printf("%s", isxdigit(ch) ? " H " : " "); putchar('\n'); } return 0; /**************************************************************************** The output should be similar to : : 0x20 S PR 0x21 ! G PU PR 0x22 " G PU PR 0x23 # G PU PR 0x24 $ G PU PR 0x25 % G PU PR 0x26 & G PU PR 0x27 ' G PU PR 0x28 ( G PU PR 0x29 ) G PU PR 0x2a * G PU PR 0x2b + G PU PR 0x2c , G PU PR 0x2d - G PU PR 0x2e . G PU PR 0x2f / G PU PR 0x30 0 AN D G PR H 0x31 1 AN D G PR H 0x32 2 AN D G PR H 0x33 3 AN D G PR H 0x34 4 AN D G PR H 0x35 5 AN D G PR H 0x36 6 AN D G PR H 0x37 7 AN D G PR H 0x38 8 AN D G PR H 0x39 9 AN D G PR H : ****************************************************************************/ } ═══ Related Information ═══ Example of isalnum to isxdigit  isascii - Test Integer Values  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  setlocale - Set Locale  tolower() - toupper() - Convert Character Case  _toascii - _tolower - _toupper - Convert Character  ═══ 4.162. isascii - Test Integer Values ═══ ═══ Format ═══ #include int isascii(int c); ═══ Description ═══ Language Level: XPG4, Extension isascii tests if an integer is within the ASCII range. This macro assumes that the system uses the ASCII character set. Note: In earlier releases of C Set ++, isascii began with an underscore (_isascii). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _isascii to isascii for you. Return Value isascii returns a nonzero value if the integer is within the ASCII set, and 0 if it is not. ═══ 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: 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 ═══ Example of isascii  isalnum to isxdigit - Test Integer Value  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  _toascii - _tolower - _toupper - Convert Character  tolower() - toupper() - Convert Character Case  ═══ 4.163. isatty - Test Handle for Character Device ═══ ═══ Format ═══ #include int isatty(int handle); ═══ Description ═══ Language Level: XPG4, Extension isatty determines whether the given handle is associated with a character device (a keyboard, display, or printer or serial port). Note: In earlier releases of C Set ++, isatty began with an underscore (_isatty). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _isatty to isatty for you. Return Value isatty returns a nonzero value if the device is a character device. Otherwise, the return value is 0. ═══ Example of isatty ═══ /************************************************************************ This example opens the console and determines if it is a character device: ************************************************************************/ #include #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 EXIT_FAILURE; } 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 output should be: CON is a character device. ****************************************************************************/ } ═══ Related Information ═══ Example of isatty  _inp - Read Byte from Input Port  _inpd - Read Doubleword from Input Port  _inpw - Read Unsigned Short from Input Port  _outp - Write Byte to Output Port  _outpd - Write Double Word to Output Port  _outpw - Write Word to Output Port  ═══ 4.164. isblank - Test for Blank Character Classification ═══ ═══ Format ═══ #include int isblank(int c); ═══ Description ═══ Language Level: Extension isblank tests whether the current LC_CTYPE locale category assigns c the blank character attribute. The value for c must be representable as an unsigned character, or EOF. In the "POSIX" and "C" locales, the tab and space characters have the blank attribute. Return Value isblank returns a nonzero value if the integer c has the blank attribute; 0 if it does not. ═══ Example of isblank ═══ /************************************************************************ This example tests if c is a blank type. ************************************************************************/ #include #include #include void check(char c) { if ((' ' != c) && (isprint(c))) printf(" %c is ", c); else printf("x%02x is ", c); if (!isblank(c)) printf("not "); puts("a blank type character"); return; } int main(void) { printf("In LC_CTYPE category of locale name \"%s\":\n", setlocale(LC_CTYPE, NULL)); check('a'); check(' '); check(0x00); check('\n'); check('\t'); return 0; /**************************************************************************** The output should be similar to : In LC_CTYPE category of locale name "C": a is not a blank type character x20 is a blank type character x00 is not a blank type character x0a is not a blank type character x09 is a blank type character ****************************************************************************/ } ═══ Related Information ═══ Example of isblank  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  iswblank - Test for Wide Blank Character Classification  setlocale - Set Locale  ═══ 4.165. _iscsym - _iscsymf - Test Integer ═══ ═══ Format ═══ #include int _iscsym(int c); int _iscsymf(int c); ═══ Description ═══ _iscsymf macro tests if a character is alphabetic or an underscore (_). 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. _iscsym tests if a character is alphabetic, a digit, or an underscore (_). _iscsymf tests is a character is alphabetic or an underscore. Return Value _iscsym and _iscsymf return a nonzero value if the integer is within the ASCII set for which it tests, and 0 if it is not. ═══ 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: _iscsym('a') returns TRUE _iscsymf('a') returns TRUE _iscsym('_') returns TRUE _iscsymf('_') returns TRUE _iscsym('1') returns TRUE _iscsymf('1') returns FALSE ****************************************************************************/ } ═══ Related Information ═══ Example of _iscsym - _iscsymf  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  isblank - Test for Blank Character Classification  iswalnum to iswxdigit - Test Wide Integer Value  iswblank - Test for Wide Blank Character Classification  tolower() - toupper() - Convert Character Case  _toascii - _tolower - _toupper - Convert Character  ═══ 4.166. ismccollel - Identify Multi-Character Collating Element ═══ ═══ Format ═══ #include int ismccollel(collel_t c); ═══ Description ═══ Language Level: Extension ismccollel determines whether the collel_t value represents a multicharacter collating element. A collating element is a glyph, usually a character, that has a value that defines its order in a collating sequence. A multicharacter collating element is a sequence of two or more characters that are to be collated as one entity. Note: If c is greater than 255 and is not a multicharacter collating element, as determined by the LC_COLLATE category of the current locale, it is a multibyte character. c is the wide character representation for the multibyte character. Return Value ismccollel returns: 1 if c represents a multi-character collating element. 0 if c represents a single-character collating element. -1 if c is out of range or otherwise invalid. ═══ Example of ismccollel ═══ /************************************************************************ This example prints all the collating elements in the collating sequence by using the ismccollel function to determine if the collating element is a multicharacter collating element. ************************************************************************/ #include #include #include #include int main(void) { collel_t *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); i = collorder(&rp); for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** The output should be similar to : : : ' ' '!' '"' '#' '$' '%' '&' '(' ''' ')' '-' '*' 'Du ' 'Des ' 'De ' 'D'' 'Les ' 'Le ' 'La ' 'L'' 'du ' 'des ' 'de ' 'd'' 'les ' 'le ' 'la ' 'l'' '+' ',' '.' '/' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' ':' ';' '<' '=' '>' '?' '@' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '[' '\' ']' '^' '_' : ****************************************************************************/ } ═══ Related Information ═══ Example of ismccollel  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  maxcoll - Return Maximum Collating Element  strtocoll - Return Collating Element for String  ═══ 4.167. iswalnum to iswxdigit - Test Wide Integer Value ═══ ═══ Format ═══ #include /* test for: */ int iswalnum(wint_t wc); /* wide alphanumeric character */ int iswalpha(wint_t wc); /* wide alphabetic character */ int iswcntrl(wint_t wc); /* wide control character */ int iswdigit(wint_t wc); /* wide decimal digit */ int iswgraph(wint_t wc); /* wide printable character, excluding space */ int iswlower(wint_t wc); /* wide lowercase character */ int iswprint(wint_t wc); /* wide printable character, including space */ int iswpunct(wint_t wc); /* wide punctuation character, excluding space */ int iswspace(wint_t wc); /* wide whitespace character */ int iswupper(wint_t wc); /* wide uppercase character */ int iswxdigit(wint_t wc); /* wide hexadecimal digit */ ═══ Description ═══ Language Level: ANSI 93, POSIX, XPG4 These functions test a given wide integer value wc to determine whether it has a certain property as defined by the LC_CTYPE category of your current locale. The value of wc must be representable as a wchar_t, or WEOF. The functions test for the following: iswalnum Wide alphanumeric character (upper- or lowercase letter, or decimal digit), as defined in the locale source file in the alnum class of the LC_CTYPE category of the current locale. iswalpha Wide alphabetic character, as defined in the locale source file in the alpha class of the LC_CTYPE category of the current locale. iswcntrl Wide control character, as defined in the locale source file in the cntrl class of the LC_CTYPE category of the current locale. iswdigit Wide decimal digit (0 through 9), as defined in the locale source file in the digit class of the LC_CTYPE category of the current locale. iswgraph Wide printable character, excluding the space character, as defined in the locale source file in the graph class of the LC_CTYPE category of the current locale. iswlower Wide lowercase letter, as defined in the locale source file in the lower class of the LC_CTYPE category of the current locale. iswprint Wide printable character, including the space character, as defined in the locale source file in the print class of the LC_CTYPE category of the current locale. iswpunct Wide non-alphanumeric printable character, excluding the space character, as defined in the locale source file in the punct class of the LC_CTYPE category of the current locale. iswspace Wide white-space character, as defined in the locale source file in the space class of the LC_CTYPE category of the current locale. iswupper Wide uppercase letter, as defined in the locale source file in the upper class of the LC_CTYPE category of the current locale. iswxdigit Wide hexadecimal digit (0 through 9, a through f, or A through F), as defined in the locale source file in the xdigit class of the LC_CTYPE category of the current locale. You can redefine any character class in the LC_CTYPE category of the current locale. For more information, see "Introduction to Locales" in the Programming Guide. Return Value These functions return a nonzero value if the wide integer satisfies the test value; 0 if it does not. ═══ Example of iswalnum to iswxdigit ═══ /************************************************************************ This example analyzes all characters between 0x0 and 0xFF. The output of this example is a 256-line table showing the characters from 0 to 255, indicating whether they have the properties tested for. ************************************************************************/ #include #include #include #define UPPER_LIMIT 0xFF int main(void) { wint_t wc; setlocale(LC_ALL, LC_C_USA); for (wc = 0; wc <= UPPER_LIMIT; wc++) { printf("%#4x ", wc); printf("%c", iswprint(wc) ? wc : ' '); printf("%s", iswalnum(wc) ? " AN" : " "); printf("%s", iswalpha(wc) ? " A " : " "); printf("%s", iswcntrl(wc) ? " C " : " "); printf("%s", iswdigit(wc) ? " D " : " "); printf("%s", iswgraph(wc) ? " G " : " "); printf("%s", iswlower(wc) ? " L " : " "); printf("%s", iswpunct(wc) ? " PU" : " "); printf("%s", iswspace(wc) ? " S " : " "); printf("%s", iswprint(wc) ? " PR" : " "); printf("%s", iswupper(wc) ? " U " : " "); printf("%s", iswxdigit(wc) ? " H " : " "); putchar('\n'); } return 0; /**************************************************************************** The output should be similar to : : 0x20 S PR 0x21 ! G PU PR 0x22 " G PU PR 0x23 # G PU PR 0x24 $ G PU PR 0x25 % G PU PR 0x26 & G PU PR 0x27 ' G PU PR 0x28 ( G PU PR 0x29 ) G PU PR 0x2a * G PU PR 0x2b + G PU PR 0x2c , G PU PR 0x2d - G PU PR 0x2e . G PU PR 0x2f / G PU PR 0x30 0 AN D G PR H 0x31 1 AN D G PR H 0x32 2 AN D G PR H 0x33 3 AN D G PR H 0x34 4 AN D G PR H 0x35 5 AN D G PR H 0x36 6 AN D G PR H 0x37 7 AN D G PR H 0x38 8 AN D G PR H 0x39 9 AN D G PR H : ****************************************************************************/ } ═══ Related Information ═══ Example of iswalnum to iswxdigit  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  isblank - Test for Blank Character Classification  _iscsym - _iscsymf - Test Integer  iswblank - Test for Wide Blank Character Classification  iswctype - Test for Character Property  ═══ 4.168. iswblank - Test for Wide Blank Character Classification ═══ ═══ Format ═══ #include int iswblank(wint_t wc); ═══ Description ═══ Language Level: Extension iswblank tests whether the current LC_CTYPE locale category assigns the the blank character attribute to the wide character wc. The value for wc must be representable as a wchar_t, or WEOF. The behavior of iswblank is affected by the LC_CTYPE category of the current locale. In the "POSIX" and "C" locales, the tab and space characters have the blank attribute. Return Value iswblank returns a nonzero value if wc has the blank attribute; 0 if it does not. ═══ Example of iswblank ═══ /************************************************************************ This example tests whether wc is a blank type. ************************************************************************/ #include #include #include #include void check(wchar_t wc) { if ((' ' != wc) && (iswprint(wc))) printf(" %lc is ", wc); else printf("x%02x is ", wc); if (!iswblank(wc)) printf("not "); puts("a blank type character"); return; } int main(void) { printf("In LC_CTYPE category of locale name \"%s\":\n", setlocale(LC_CTYPE, NULL)); check(L'a'); check(L' '); check(0x00); check(L'\n'); check(L'\t'); return 0; /**************************************************************************** The output should be similar to : In LC_CTYPE category of locale name "C": a is not a blank type character x20 is a blank type character x00 is not a blank type character x0a is not a blank type character x09 is a blank type character ****************************************************************************/ } ═══ Related Information ═══ Example of iswblank  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  isblank - Test for Blank Character Classification  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  iswctype - Test for Character Property  ═══ 4.169. iswctype - Test for Character Property ═══ ═══ Format ═══ #include int iswctype(wint_t wc, wctype_t wc_prop); ═══ Description ═══ Language Level: ANSI 93, XPG4 iswctype determines whether the wide character wc has the property wc_prop. It is similar in function to the iswalnum through isxdigit functions, but with iswctype you can specify the property to check for, or check for a property other than the standard ones. You must obtain the wc_prop value from a call to wctype. If you do not, or if the LC_CTYPE category of the locale was modified after you called wctype, the behavior of iswctype is undefined. The value of wc must be representable as an unsigned wchar_t, or WEOF. The following strings correspond to the standard (basic) character classes or properties: ┌───────────────────┬───────────────────┬───────────────────┬──────────────────┐ │ " │ " │ " │ " │ │ "alnum" │ "cntrl" │ "lower" │ "space" │ │ "alpha" │ "digit" │ "print" │ "upper" │ │ "blank" " │ "graph" " │ "punct" " │ "xdigit" " │ └───────────────────┴───────────────────┴───────────────────┴──────────────────┘ The following shows calls to wctype and indicates the equivalent isw* function: iswctype(wc, wctype("alnum")); /* iswalnum(wc); */ iswctype(wc, wctype("alpha")); /* iswalpha(wc); */ iswctype(wc, wctype("blank")); /* iswblank(wc); */ iswctype(wc, wctype("cntrl")); /* iswcntrl(wc); */ iswctype(wc, wctype("digit")); /* iswdigit(wc); */ iswctype(wc, wctype("graph")); /* iswgraph(wc); */ iswctype(wc, wctype("lower")); /* iswlower(wc); */ iswctype(wc, wctype("print")); /* iswprint(wc); */ iswctype(wc, wctype("punct")); /* iswpunct(wc); */ iswctype(wc, wctype("space")); /* iswspace(wc); */ iswctype(wc, wctype("upper")); /* iswupper(wc); */ iswctype(wc, wctype("xdigit")); /* iswxdigit(wc); */ Return Value iswctype returns a nonzero value if the wide character has the property tested for. If the value for wc or wc_prop is not valid, the behavior is undefined. ═══ Example of iswctype ═══ /************************************************************************ This example analyzes all characters between 0x0 and 0xFF. The output of this example is a 256-line table showing the characters from 0 to 255, indicating whether they have the properties tested for. ************************************************************************/ #include #include #include #define UPPER_LIMIT 0xFF int main(void) { wint_t wc; setlocale(LC_ALL, LC_C_USA); for (wc = 0; wc <= UPPER_LIMIT; wc++) { printf("%#4x ", wc); printf("%c", iswctype(wc, wctype("print")) ? wc : ' '); printf("%s", iswctype(wc, wctype("alnum")) ? " AN" : " "); printf("%s", iswctype(wc, wctype("alpha")) ? " A " : " "); printf("%s", iswctype(wc, wctype("blank")) ? " B " : " "); printf("%s", iswctype(wc, wctype("cntrl")) ? " C " : " "); printf("%s", iswctype(wc, wctype("digit")) ? " D " : " "); printf("%s", iswctype(wc, wctype("graph")) ? " G " : " "); printf("%s", iswctype(wc, wctype("lower")) ? " L " : " "); printf("%s", iswctype(wc, wctype("punct")) ? " PU" : " "); printf("%s", iswctype(wc, wctype("space")) ? " S " : " "); printf("%s", iswctype(wc, wctype("print")) ? " PR" : " "); printf("%s", iswctype(wc, wctype("upper")) ? " U " : " "); printf("%s", iswctype(wc, wctype("xdigit")) ? " H " : " "); putchar('\n'); } return 0; /**************************************************************************** The output should be similar to : : 0x1e C 0x1f C 0x20 B S PR 0x21 ! G PU PR 0x22 " G PU PR 0x23 # G PU PR 0x24 $ G PU PR 0x25 % G PU PR : 0x30 0 AN D G PR H 0x31 1 AN D G PR H 0x32 2 AN D G PR H 0x33 3 AN D G PR H 0x34 4 AN D G PR H 0x35 5 AN D G PR H : 0x43 C AN A G PR U H 0x44 D AN A G PR U H 0x45 E AN A G PR U H 0x46 F AN A G PR U H 0x47 G AN A G PR U : ****************************************************************************/ } ═══ Related Information ═══ Example of iswctype  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  isblank - Test for Blank Character Classification  _iscsym - _iscsymf - Test Integer  iswalnum to iswxdigit - Test Wide Integer Value  iswblank - Test for Wide Blank Character Classification  iswalnum to iswxdigit - Test Wide Integer Value  wctype - Get Handle for Character Property Classification  ═══ 4.170. _itoa - Convert Integer to String ═══ ═══ Format ═══ #include char *_itoa(int value, char * string, int radix); ═══ Description ═══ Language Level: Extension _itoa 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). Return Value _itoa returns a pointer to string. There is no error return value. ═══ 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 output should be: 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 ═══ Example of _itoa  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  _ltoa - Convert Long Integer to String  _ultoa - Convert Unsigned Long Integer to String  ═══ 4.171. _kbhit - Test for Keystroke ═══ ═══ Format ═══ include int _kbhit(void); ═══ Description ═══ Language Level: Extension _kbhit tests if a key has been pressed on the keyboard. If the result is nonzero, a keystroke is waiting in the buffer. You can read in 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. Return Value _kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0. ═══ 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 test result. ************************************************************************/ #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 (0==_kbhit()){ /* Processing without waiting for a key to be pressed */ } ch = _getch(); printf("You have pressed the '%c' key.\n",ch); if ('x' == ch) break; } return 0; /**************************************************************************** The output should be similar to: 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. ****************************************************************************/ } ═══ Related Information ═══ Example of _kbhit  _getch - _getche - Read Character from Keyboard  ═══ 4.172. labs - Calculate Absolute Value of Long Integer ═══ ═══ Format ═══ #include long int labs(long int n); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 labs 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. Return Value labs returns the absolute value of n. There is no error return value. ═══ Example of labs ═══ /************************************************************************ This example computes y as the absolute value of the long integer -41567. ************************************************************************/ #include int main(void) { long x,y; x = -41567L; y = labs(x); printf("The absolute value of %ld is %ld\n", x, y); return 0; /**************************************************************************** The output should be: The absolute value of -41567 is 41567 ****************************************************************************/ } ═══ Related Information ═══ Example of labs  abs - Calculate Integer Absolute Value  _cabs - Calculate Absolute Value of Complex Number  fabs - Calculate Floating-Point Absolute Value  ═══ 4.173. ldexp - Multiply by a Power of Two ═══ ═══ Format ═══ #include double ldexp(double x, int exp); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ldexp calculates the value of x * (2**exp). Return Value ldexp returns the resulting value. 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be: 1.500000 times 2 to the power of 5 is 48.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of ldexp  exp - Calculate Exponential Function  frexp - Separate Floating-Point Value  modf - Separate Floating-Point Value  ═══ 4.174. ldiv - Perform Long Division ═══ ═══ Format ═══ #include ldiv_t ldiv(long int numerator, long int denominator); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 ldiv calculates the quotient and remainder of the division of numerator by denominator. Return Value ldiv 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 ═══ /************************************************************************ This example uses ldiv 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); } return 0; /**************************************************************************** The output should be: 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 ═══ Example of ldiv  div - Calculate Quotient and Remainder  ═══ 4.175. lfind - lsearch - Find Key in Array ═══ ═══ Format ═══ #include char *lfind(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*compare)(const void *key, const void *element)); char *lsearch(char *search_key, char *base, unsigned int *num, unsigned int *width, int (*compare)(const void *key, const void *element)); ═══ Description ═══ Language Level: XPG4, Extension lfind and lsearch 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 compare argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. Both lfind and lsearch call this function one or more times during the search. The function must compare the key and the element and return one of the following values: Value Meaning Nonzero key and element are different. 0 key and element are identical. Note: In earlier releases of C Set ++, lfind and lsearch began with an underscore (_lfind and _lsearch). Because they are defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _lfind and _lsearch to lfind and lsearch for you. Return Value If search_key is found, both lsearch and lfind return a pointer to that element of the array to which base points. If 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 ═══ /************************************************************************ This example uses lfind to search for the keyword PATH in the command-line arguments. ************************************************************************/ #include #include #include #define CNT 2 /* Note: Library always calls functions internally with _Optlink */ /* linkage convention. Ensure that compare() is always */ /* _Optlink. */ int _Optlink compare(const void *arg1,const void *arg2) { return (strncmp(*(char **)arg1, *(char **)arg2, strlen(*(char **)arg1))); } int main(void) { char **result; char *key = "PATH"; unsigned int num = CNT; char *string[CNT] = { "PATH = d:\\david\\matthew\\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 output should be: PATH = d:\david\matthew\heather\ed\simon found ****************************************************************************/ } ═══ Related Information ═══ Example of lfind  bsearch - Search Arrays  qsort - Sort Array  ═══ 4.176. _loadmod - Load DLL ═══ ═══ Format ═══ #include int _loadmod(char *module_name, unsigned long *module_handle); ═══ Description ═══ Language Level: Extension _loadmod loads a 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. Note: _loadmod and _freemod perform exactly the same function as the OS/2 APIs DosLoadModule and DosFreeModule. They are provided for compatibility with earlier VisualAge C++ releases only, and will not be supported in future versions. Use DosLoadModule and DosFreeModule instead. For more details on these APIs, see the Control Program Guide and Reference. 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. Return Value _loadmod returns 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 ═══ /************************************************************************ 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); return EXIT_FAILURE; } /* get function address from DLL */ rc = DosQueryProcAddr(handle, 0, fname, &faddr); if (0 == rc) { 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); return EXIT_FAILURE; } if (_freemod(handle)) { printf("Error in freeing the %s DLL module\n", modname); return EXIT_FAILURE; } printf("Reference to the %s DLL module has been freed\n", modname); return 0; /**************************************************************************** The output should be: Calling the function from the MARK 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 ═══ Example of _loadmod  _freemod - Free User DLL  ═══ 4.177. localdtconv - Return Date and Time Formatting Convention ═══ ═══ Format ═══ #include struct dtconv *localdtconv(void); ═══ Description ═══ Language Level: Extension localdtconv determines the date and time formatting conventions of the current locale and places the information in a structure of type struct dtconv. The dtconv structure is described in detail on page . Subsequent calls to localdtconv or to setlocale with LC_ALL or LC_TIME can overwrite the structure. Return Value localdtconv returns the address of the dtconv structure. ═══ Example of localdtconv ═══ /************************************************************************ This example sets the Spanish locale, calls localdtconv to determine how date and time are formatted, and prints the fields from the resulting structure. ************************************************************************/ #include #include #include int main(void) { struct dtconv *p; int i; if (NULL == setlocale(LC_ALL, LC_C_SPAIN)) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } else { p = localdtconv(); printf("SPAIN date/time convention.\n"); printf(" Abbreviated month names:"); for (i = 0; i < 12; ++i) printf(" %s", p->abbrev_month_names[i]); printf("\n Full month names:"); for (i = 0; i < 12; ++i) printf(" %s", p->month_names[i]); printf("\n Abbreviated day names:"); for (i = 0; i < 7; ++i) printf(" %s", p->abbrev_day_names[i]); printf("\n Full day names:"); for (i = 0; i < 7; ++i) printf(" %s", p->day_names[i]); printf("\n Date and time format: %s\n", p->date_time_format); printf(" Date format: %s\n", p->date_format); printf(" Time format: %s\n", p->time_format); printf(" AM string: %s\n", p->am_string); printf(" PM string: %s\n", p->pm_string); printf(" Long date format: %s\n", p->time_format_ampm); } return 0; /**************************************************************************** The output should be similar to : SPAIN date/time convention. Abbreviated month names: ENE FEB MAR ABR MAY JUN JUL AGO SEP OCT NOV DIC Full month names: Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre Abbreviated day names: DOM LUN MAR MIE JUE VIE SAB Full day names: Domingo Lunes Martes Miercoles Jueves Viernes Sabado Date and time format: %d %B %Y %H:%M:%S Date format: %d/%m/%y Time format: %H:%M:%S AM string: PM string: Long date format: %H:%M:%S %p ****************************************************************************/ } ═══ Related Information ═══ Example of localdtconv  localeconv - Retrieve Information from the Environment  localtime - Convert Time  setlocale - Set Locale  strftime - Convert to Formatted Time  strptime - Convert to Formatted Date and Time  wcsftime - Convert to Formatted Date and Time  ═══ 4.178. localeconv - Retrieve Information from the Environment ═══ ═══ Format ═══ #include struct lconv *localeconv(void); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 localeconv retrieves information about the environment for the current locale and places the information in a structure of type struct lconv. Subsequent calls to localeconv, or to setlocale with the argument LC_ALL, LC_MONETARY, or LC_NUMERIC, can overwrite the structure. The structure contains the members listed below. Defaults shown are for the "C" locale. Pointers to strings with a value of "" indicate that the value is not available in this locale or is of zero length. Character types with a value of UCHAR_MAX indicate that the value is not available in this locale. ELEMENT PURPOSE OF ELEMENT DEFAULT "char *decimal_point" Decimal-point character for formatting "." 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" Size of each group of digits in for- "" matted nonmonetary quantities. The value of each character in the string determines the number of digits in a group. "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. The "" *int_curr_symbol" first three characters contain the alphabetic international currency symbol. The fourth character (usually a space) separates the international cur- rency symbol from the monetary quantity. "char Local currency symbol. "" *currency_symbol" "char Decimal-point character for formatting "." *mon_decimal_point" monetary quantities. "char Separator for digits in formatted mone- "" *mon_thousands_sep" tary quantities. "char *mon_grouping" Size of each group of digits in for- "" matted monetary quantities. The value of each character in the string deter- mines the number of digits in a group. "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" Positive sign used in monetary quanti- "" ties. "char *negative_sign" Negative sign used in monetary quanti- "" ties. "char int_frac_digits" Mumber of displayed digits to the right UCHAR_MAX of the decimal place for internationally 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 is 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 is not. "char p_sign_posn" Position of the "positive_sign" for a UCHAR_MAX nonnegative formatted monetary quantity. "char n_sign_posn" Position of the "negative_sign" for a UCHAR_MAX negative formatted monetary quantity. "char Symbol to appear to the left of a ""("" *left_parenthesis" negative-valued monetary symbol (such as a loss or deficit). "char Symbol to appear to the right of a "")"" *right_parenthesis" negative-valued monetary symbol (such as a loss or deficit). "char *debit_sign" String to indicate a non-negative-valued ""DB"" formatted monetary quantity. "char *credit_sign" String to indicate a negative-valued ""CR"" formatted monetary quantity. The grouping and mon_grouping members can have the following values: Value Meaning CHAR_MAX No further grouping is to be performed. 0 The previous element is to be repeatedly used for the rest of the digits. other The number of digits that comprise the current group. The next element is examined to determine the size of the next group of digits before the current group. 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. 5 Use debit_sign for p_sign_posn or credit_sign for n_sign_posn. Return Value localeconv returns a pointer to the lconv structure. ═══ 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) { struct lconv *mylocale; mylocale = localeconv(); printf("Default decimal point is a %s\n", mylocale->decimal_point); if (NULL != setlocale(LC_ALL, LC_C_FRANCE)) { mylocale = localeconv(); printf("France's decimal point is a %s\n", mylocale->decimal_point); } else { printf("setlocale(LC_ALL, LC_C_FRANCE) returned \n"); } return 0; /**************************************************************************** The output should be similar to : Default decimal point is a . France's decimal point is a , ****************************************************************************/ } ═══ Related Information ═══ Example of localeconv  setlocale - Set Locale  ═══ 4.179. localtime - Convert Time ═══ ═══ Format ═══ #include struct tm *localtime(const time_t *timeval); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 localtime breaks down timeval, 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 time value is usually obtained by a call to the time function. Note: 1. gmtime and localtime 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. Return Value localtime returns a pointer to the structure result. If unsuccessful, it returns NULL. ═══ 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)); return 0; /**************************************************************************** The output should be similar to: The date and time is Wed Oct 31 15:00:00 1995 ****************************************************************************/ } ═══ Related Information ═══ Example of localtime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  mktime - Convert Local Time  time - Determine Current Time  ═══ 4.180. log - Calculate Natural Logarithm ═══ ═══ Format ═══ #include double log(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 log calculates the natural logarithm (base e) of x. Return Value log returns the computed value. If x is negative, log sets 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 ═══ /************************************************************************ This example calculates the natural logarithm of 1000.0. ************************************************************************/ #include int main(void) { double x = 1000.0,y; y = log(x); printf("The natural logarithm of %lf is %lf\n", x, y); return 0; /**************************************************************************** The output should be: The natural logarithm of 1000.000000 is 6.907755 ****************************************************************************/ } ═══ Related Information ═══ Example of log  exp - Calculate Exponential Function  log10 - Calculate Base 10 Logarithm  pow - Compute Power  ═══ 4.181. log10 - Calculate Base 10 Logarithm ═══ ═══ Format ═══ #include double log10(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 log10 calculates the base 10 logarithm of x. Return Value log10 returns the computed value. If x is negative, log10 sets 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 ═══ /************************************************************************ This example calculates the base 10 logarithm of 1000.0. ************************************************************************/ #include int main(void) { double x = 1000.0,y; y = log10(x); printf("The base 10 logarithm of %lf is %lf\n", x, y); return 0; /**************************************************************************** The output should be: The base 10 logarithm of 1000.000000 is 3.000000 ****************************************************************************/ } ═══ Relative Information ═══ Example of log10  exp - Calculate Exponential Function  log - Calculate Natural Logarithm  pow - Compute Power  ═══ 4.182. longjmp - Restore Stack Environment ═══ ═══ Format ═══ #include void longjmp(jmp_buf env, int value); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 longjmp restores a stack environment previously saved in env by setjmp. setjmp and longjmp 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 variables that are allocated to registers by the compiler are unpredictable. Because any auto variable could be allocated to a register in optimized code, you should consider the values of all auto variables to be unpredictable after a longjmp call. 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 must be nonzero. If you give a zero argument for value, longjmp substitutes 1 in its place. C++ Considerations When you call setjmp in a C++ program, ensure that that part of the program does not also create C++ objects that need to be destroyed. When you call longjmp, objects existing at the time of the setjmp call will still exist, but any destructors called after setjmp are not called. Click here for an example. Return Value longjmp does not use the normal function call and return mechanisms; it has no return value. ═══ Example of C++ setjmp/longjmp Restriction ═══ Given the following program: #include #include class A { int i; public: A(int I) {i = I; printf("Constructed at line %d\n", i);} ~A() {printf("Destroying object constructed at line %d\n",i);} }; jmp_buf jBuf; int main(void) { A a1(__LINE__); if (!setjmp(jBuf)) { A a2(__LINE__); printf("Press y (and Enter) to longjmp; anything else to return norm char c = getchar(); if (c == 'y') longjmp(jBuf, 1); } A a3(__LINE__); return 0; } If you return normally, the output would be: Constructed at line 13 Constructed at line 15 Press y (and Enter) to longjmp; anything else to return normally x Destroying object constructed at line 15 Constructed at line 21 Destroying object constructed at line 21 Destroying object constructed at line 13 If you called longjmp, the output would be: Constructed at line 13 Constructed at line 15 Press y (and Enter) to longjmp; anything else to return normally y Constructed at line 21 Destroying object constructed at line 21 Destroying object constructed at line 13 Notice that the object from line 15 is not destroyed. ═══ Example of longjmp ═══ /************************************************************************ This example saves 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 call longjmp. 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 longjmp. The example then performs the statements in the block, prints longjmp has been called, calls recover, and leaves the program. ************************************************************************/ #include #include jmp_buf mark; int main(void) { if (setjmp(mark) != 0) { printf("longjmp has been called\n"); recover(); exit(1); } printf("setjmp has been called\n"); p(); return 0; /**************************************************************************** The output should be: setjmp has been called longjmp has been called ****************************************************************************/ } int p(void) { int error = 0; error = 9; if (error != 0) longjmp(mark, -1); } int recover(void) { } ═══ Related Information ═══ Example of longjmp  setjmp - Preserve Environment  goto in the Language Reference  ═══ 4.183. _lrotl - _lrotr - Rotate Bits of Unsigned Long Value ═══ ═══ Format ═══ #include /* also in */ unsigned long _lrotl(unsigned long value, int shift); unsigned long _lrotr(unsigned long value, int shift); ═══ Description ═══ Language Level: Extension _lrotl and _lrotr rotate the unsigned long integer value by shift bits. _lrotl rotates to the left, and _lrotr to the right. Note: Both _lrotl and _lrotr are built-in functions, which means they are implemented as inline instructions and have no backing code in the library. For this reason:  You cannot take the address of these functions.  You cannot parenthesize a call to either function. (Parentheses specify a call to the function's backing code, and these functions have none.) Return Value Both functions return the rotated value. There is no error return value. ═══ 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: 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 ═══ Example of _lrotl - _lrotr  _crotl - _crotr - Rotate Bits of Character Value  _rotl - _rotr - Rotate Bits of Unsigned Integer  _srotl - _srotr - Rotate Bits of Unsigned Short Value   ═══ 4.184. lseek - Move File Pointer ═══ ═══ Format ═══ #include /* constants in */ long lseek(int handle, long offset, int origin); ═══ Description ═══ Language Level: XPG4, Extension lseek 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. 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. lseek 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.) An attempt to position the pointer before the beginning of the file causes an error. Note: In earlier releases of C Set ++, lseek began with an underscore (_lseek). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _lseek to lseek for you. Return Value lseek returns the offset, in bytes, of the new position from the beginning of the file. A return value of -1L indicates an error, and lseek sets errno 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), lseek returns -1 and sets errno to EOS2ERR. ═══ 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(EXIT_FAILURE); } if (-1 == lseek(fh, 7, SEEK_SET)) { /* place the file pointer at the */ perror("Unable to lseek"); /* eighth position in the file */ close(fh); return EXIT_FAILURE; } if (8 != read(fh, buffer, 8)) { perror("Unable to read from sample.dat."); close(fh); return EXIT_FAILURE; } printf("Successfully read in the following:\n%s.\n", buffer); close(fh); return 0; /**************************************************************************** The output should be: Creating sample.dat. Successfully read in the following: Program . ****************************************************************************/ } ═══ Related Information ═══ Example of lseek  _chsize - Alter Length of File  fseek - Reposition File Position  _tell - Get Pointer Position   ═══ 4.185. _ltoa - Convert Long Integer to String ═══ ═══ Format ═══ #include char *_ltoa(long value, char *string, int radix); ═══ Description ═══ Language Level: Extension _ltoa 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). Return Value _ltoa returns a pointer to string. There is no error return value. ═══ 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 output should be: 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 ═══ Example of _ltoa  atol - Convert Character String to Long Integer  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  _itoa - Convert Integer to String  strtol - Convert Character String to Long Integer  _ultoa - Convert Unsigned Long Integer to String  wcstol - Convert Wide-Character to Long Integer  ═══ 4.186. __lxchg - Exchange Integer Value with Memory ═══ ═══ Format ═══ #include int _Builtin __lxchg(volatile int*lockptr, int value); ═══ Description ═══ Language Level: Extension __lxchg puts the specified value in the memory location pointed to by lockptr, and returns the value that was previously in that location. Use this function to implement fast-RAM semaphores to serialize access to a critical resource (so that only one thread can use it at a time). You can also use OS/2 semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and an OS/2 semaphore for the resource. For more details about OS/2 semaphores and how to use them, see the Control Program Guide and Reference. To implement a fast-RAM semaphore, allocate a volatile memory location lockptr (for __lxchg, it must be of type int), and statically initialize it to 0 to indicate that the resource is free (not being used). To give a thread access to the resource, call __lxchg from the thread to exchange a non-zero value with that memory location. If __lxchg returns 0, the thread can access the resource; it has also set the memory location so that other threads can tell the resource is in use. When your thread no longer needs the resource, call __lxchg again to reset the memory location to 0. If __lxchg returns a non-zero value, another thread is already using the resource, and the calling thread must wait for access. You could then use the OS/2 semaphore to inform your waiting thread when the resource is unlocked by the thread currently using it. It is important that you set the memory to a nonzero value when you are using the resource. You can use the same nonzero value for all threads, or a unique value for each. Note: __lxchg is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of __lxchg.  You cannot parenthesize a call to __lxchg. (Parentheses specify a call to the function's backing code, and __lxchg has none.) Return Value __lxchg returns the previous value stored in the memory location pointed to by lockptr. ═══ Example of __lxchg ═══ /************************************************************************ This example creates five separate threads, each associated with a State. At most two threads can have a State of Eating at the same time. When a thread calls PickUpChopSticks, that function checks the states of the preceding threads to make sure they are not already Eating, If the call to __lxchg is successful, the thread has locked the Lock semaphore and can change its State to Eating. It then calls __lxchg a second time to unlock the semaphore, and returns. If __lxchg cannot lock the semaphore, another thread has it locked. The current thread then suspends itself briefly with DosSleep and tries again. The semaphore is used to ensure that two threads cannot simultaneously change their State to Eating, which would cause a deadlock. (Note that although the semaphore solves the problem of deadlock, it is not an optimal solution; some threads may never get the semaphore or the State of Eating.) Note: You must compile this example with the multithread (/Gm) option. The example runs in an infinite loop; press Ctrl-C to end it. ************************************************************************/ #pragma strings(readonly) #define INCL_DOS #include #include #include #include typedef enum { Thinking, Eating, Hungry } States; #define UNLOCKED 0 #define LOCKED 1 #define NUM_PHILOSOPHERS 5 static volatile int Lock; static States State[NUM_PHILOSOPHERS]; static const int NameMap[NUM_PHILOSOPHERS] = {0, 1, 2, 3, 4}; static const char * const Names[NUM_PHILOSOPHERS] = {"Plato", "Socrates", "Kant", "Hegel", "Nietsche"}; void PickUpChopSticks(int Ident); void PutDownChopSticks(int Ident); void Think(int Ident); void Eat(int Ident); void _Optlink StartPhilosopher(void *pIdent); void _Optlink StartPhilosopher(void *pIdent) { int Ident = *(int *)pIdent; while (1) { State[Ident] = Hungry; printf("%s hungry.\n", Names[Ident]); PickUpChopSticks(Ident); Eat(Ident); PutDownChopSticks(Ident); Think(Ident); } } int main(int argc, char *argv[], char *envp[]) { int i; unsigned long tid; for (i = 0; i < NUM_PHILOSOPHERS; i++) { tid = _beginthread(StartPhilosopher, NULL, 8192, (void *)&NameMap[i]); if (tid == -1) { printf("Unable to start %s.\n", Names[i]); } else { printf("%s started with Thread Id = %d.\n", Names[i], tid); } } DosWaitThread(&tid, DCWW_WAIT); return 0; } void PickUpChopSticks(int Ident) { while (1) { if (State[(Ident + NUM_PHILOSOPHERS - 1) % NUM_PHILOSOPHERS] != Eating && State[(Ident + 1) % NUM_PHILOSOPHERS] != Eating && !__lxchg(&Lock, LOCKED)) { State[Ident] = Eating; __lxchg(&Lock, UNLOCKED); return; } else { DosSleep(1); } } } void PutDownChopSticks(int Ident) { State[Ident] = Thinking; } void Eat(int Ident) { printf("%s eating.\n", Names[Ident]); DosSleep(1); } void Think(int Ident) { printf("%s thinking.\n", Names[Ident]); DosSleep(1); } /**************************************************************************** The output should be similar to : Plato started with Thread Id = 2. Socrates started with Thread Id = 3. Kant started with Thread Id = 4. Hegel started with Thread Id = 5. Nietsche started with Thread Id = 6. Plato hungry. Plato eating. Socrates hungry. Kant hungry. Kant eating. Hegel hungry. Nietsche hungry. Kant thinking. Plato thinking. Plato hungry. Plato eating. Kant hungry. Kant eating. : ****************************************************************************/ ═══ Related Information ═══ Example of __lxchg  __cxchg - Exchange Character Value with Memory  __sxchg - Exchange Integer Value with Memory  ═══ 4.187. _makepath - Create Path ═══ ═══ Format ═══ #include void _makepath(char *path, char *drive, char *dir, char *fname, char *ext); ═══ Description ═══ Language Level: Extension _makepath 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: drive A letter (A, B, ...) corresponding to the desired drive and an optional following colon. _makepath 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 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 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 The base file name without any extensions. ext The actual file name extension, with or without a leading period. _makepath 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. Return Value There is no return value. ═══ 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: 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 ═══ Example of _makepath  _fullpath - Get Full Path Name of Partial Path  _splitpath - Decompose Path Name  ═══ 4.188. malloc - Reserve Storage Block ═══ ═══ Format ═══ #include /* also in */ void *malloc(size_t size); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension malloc reserves a block of storage of size bytes. Unlike calloc, malloc does not initialize all elements to 0. Heap-specific, tiled, and debug versions of this function (_umalloc, _tmalloc, and _debug_malloc) are also available. malloc always operates on the default heap. For more information about memory management, see Managing Memory in the Programming Guide. Return Value malloc returns a pointer to the reserved space. The storage space to which the return value points is suitably aligned for storage of any type of object. The return value is NULL if not enough storage is available, or if size was specified as zero. ═══ 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(); } return 0; /**************************************************************************** The output should be similar to: Enter the size of the array 5 array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2 array[ 3 ] = 3 array[ 4 ] = 4 ****************************************************************************/ } ═══ Related Information ═══ Example of malloc  calloc - Reserve and Initialize Storage  _debug_malloc - Allocate Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_umalloc - Reserve Memory Blocks from User Heap  free - Release Storage Blocks  _mheap - Query Memory Heap for Allocated Object  _msize - Return Number of Bytes Allocated  realloc - Change Reserved Storage Block Size  _tmalloc - Reserve Tiled Storage Block  _umalloc - Reserve Memory Blocks from User Heap   ═══ 4.189. _matherr - Process Math Library Errors ═══ ═══ Format ═══ #include int _matherr(struct exception *x); ═══ Description ═══ Language Level: Extension _matherr processes 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 VisualAge C++ library performs no error handling and returns 0 to the calling function. You can provide a different definition of _matherr to carry out special error handling. Be sure to use the /NOE link option, if you are using your own _matherr function. For VisualAge C++ 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 field specifies the type of math error. It has 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. PLOSS is provided for compatibility with other compilers; VisualAge C++ does not 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 fields 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 it. 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 ═══ /************************************************************************ This example provides a _matherr function to handle errors from the log or log10 functions. The arguments to these logarithmic functions must be positive double values. _matherr 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: You must compile this example with the /B"/NOE" compiler option. ************************************************************************/ #include #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; /**************************************************************************** The output should be: 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 ****************************************************************************/ } int _matherr(struct exception *x) { printf("inside _matherr\n"); if (DOMAIN == x->type) { if (0 == strcmp(x->name, "log")) { x->retval = log(-(x->arg1)); return EXIT_FAILURE; } else if (0 == strcmp(x->name, "log10")) { x->retval = log10(-(x->arg1)); return EXIT_FAILURE; } } return 0; /* Use default actions */ } ═══ Related Information ═══ Example of _matherr  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  ═══ 4.190. max - Return Larger of Two Values ═══ ═══ Format ═══ #include type max(type a, type b); ═══ Description ═══ Language Level: Extension max 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. Return Value max returns the larger of the two values. ═══ 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 output should be: The larger of 10 and 21 is 21 ****************************************************************************/ } ═══ Related Information ═══ Example of max  min - Return Lesser of Two Values  ═══ 4.191. maxcoll - Return Maximum Collating Element ═══ ═══ Format ═══ #include collel_t maxcoll(void); ═══ Description ═══ Language Level: Extension maxcoll determines the largest possible value of a collating element in the current locale. Return Value maxcoll returns the largest collating element. ═══ Example of maxcoll ═══ /************************************************************************ This example sets the current locale to several different locales, and uses maxcoll to determine the largest collating element for each. ************************************************************************/ #include #include #include #define LOCALEMAX 4 static char *locales[LOCALEMAX] = {"ES_ES.IBM-850", "EN_US.IBM-850", "FR_FR.IBM-850", "JA_JP.IBM-932"}; int main(void) { int locnum; for (locnum = 0; locnum < LOCALEMAX; locnum++) { if (NULL == setlocale(LC_ALL, locales[locnum])) printf("setlocale(LC_ALL, \"%s\") failed.\n", locales[locnum]); else { printf("The current locale is %s.\n", locales[locnum]); printf(" maxcoll() returned %d\n", maxcoll()); } } return 0; /**************************************************************************** The output should be similar to : The current locale is ES_ES.IBM-850. maxcoll() returned 263 The current locale is EN_US.IBM-850. maxcoll() returned 255 The current locale is FR_FR.IBM-850. maxcoll() returned 255 The current locale is JA_JP.IBM-932. maxcoll() returned 64587 ****************************************************************************/ } ═══ Related Information ═══ Example of maxcoll  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  strtocoll - Return Collating Element for String  ═══ 4.192. mblen - Determine Length of Multibyte Character ═══ ═══ Format ═══ #include int mblen(const char *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 mblen determines the length in bytes of the multibyte character pointed to by string. A maximum of n bytes is examined. The behavior of mblen is affected by the LC_CTYPE category of the current locale. Return Value If string is NULL, mblen returns 0. Note: On platforms that support shift states, mblen can also return a nonzero value to indicate that the multibyte encoding is state-dependent. Because VisualAge C++ does not support state-dependent encoding, mblen always returns 0 when string is NULL. If string is not NULL, mblen returns:  0 if string points to the null character  The number of bytes comprising the multibyte character  The value -1 if string does not point to a valid multibyte character. ═══ Example of mblen ═══ /************************************************************************ This example uses mblen and mbtowc to convert a multibyte character into a single wide character. ************************************************************************/ #include #include #include #include int main(void) { char mb_string[] = "\x81\x41\x81\xc2" "b"; int length; wchar_t widechar; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length = mblen(mb_string, MB_CUR_MAX); mbtowc(&widechar, mb_string, length); printf("The wide character %lc has length of %d.\n", widechar, length); return 0; /**************************************************************************** The output should be similar to : The wide character ─A has length of 2. ****************************************************************************/ } ═══ Related Information ═══ Example of mblen  mbrlen - Calculate Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  mbstowcs - Convert Multibyte String to Wide-Character String  mbtowc - Convert Multibyte Character to Wide Character  setlocale - Set Locale  strlen - Determine String Length  wcrtomb - Convert Wide Character to Multibyte Character  wcslen - Calculate Length of Wide-Character String  wcsrtombs - Convert Wide-Character String to Multibyte String  wctomb - Convert Wide Character to Multibyte Character   ═══ 4.193. mbrlen - Calculate Length of Multibyte Character ═══ ═══ Format ═══ #include size_t mbrlen(const char *string, size_t n, mbstate_t *state); ═══ Description ═══ Language Level: ANSI 93 mbrlen is a restartable version of mblen and performs the same function. It determines the length in bytes of the multibyte character pointed to by string. A maximum of n bytes are examined. With mbrlen, you can switch from one multibyte string to another. On platforms that support shift states, state represents the initial shift state of the string (0). If you read in only part of the string, mbrlen sets state to the string's shift state at the point you stopped. You can then call mbrlen again for that string and pass in the updated state value to continue reading where you left off. Note: Because OS/2 does not have shift states, the state parameter is provided only for compatibility with other ANSI/ISO platforms. VisualAge C++ ignores the value passed for state. The behavior of mbrlen is affected by the LC_CTYPE category of the current locale. Return Value If string is a null pointer, mbrlen returns 0. If string is not a null pointer, mbrlen returns the first of the following that applies: 0 If the next n or fewer bytes complete the valid multibyte character that corresponds to the null wide character. positive If the next n or fewer bytes complete the valid multibyte character; the value returned is the number of bytes that complete the multibyte character. -2 If the next n bytes form an incomplete (but potentially valid) multibyte character, and all n bytes have been processed. -1 If an encoding error occurs (when the next n or fewer bytes do not form a complete and valid multibyte character). mbrlen sets errno to EILSEQ. ═══ Example of mbrlen ═══ /************************************************************************ This example uses mbrlen to determine the length of the strings mbs1 and mbs2. ************************************************************************/ #include #include #include #include int main(void) { char mbs1[] = "abc"; char mbs2[] = "\x81\x41" "a" "\x81\xc1"; mbstate_t ss1 = 0; mbstate_t ss2 = 0; size_t length1, length2; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length1 = mbrlen(mbs1, MB_CUR_MAX, &ss1); /* first char */ length2 = mbrlen(mbs2, MB_CUR_MAX, &ss2); /* first char */ length1 += mbrlen(mbs1 + length1, MB_CUR_MAX, &ss1); /* second char */ length2 += mbrlen(mbs2 + length2, MB_CUR_MAX, &ss2); /* second char */ length1 += mbrlen(mbs1 + length1, MB_CUR_MAX, &ss1); /* third char */ length2 += mbrlen(mbs2 + length2, MB_CUR_MAX, &ss2); /* third char */ printf("Length of the first multibyte string = %d\n", length1); printf("Length of the second multibyte string = %d\n", length2); return 0; /**************************************************************************** The output should be similiar to : Length of the first multibyte string = 3 Length of the second multibyte string = 5 ****************************************************************************/ } ═══ Related Information ═══ Example of mbrlen  mblen - Determine Length of Multibyte Character  mbtowc - Convert Multibyte Character to Wide Character  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  setlocale - Set Locale  wcrtomb - Convert Wide Character to Multibyte Character  wcsrtombs - Convert Wide-Character String to Multibyte String   ═══ 4.194. mbrtowc - Convert Multibyte Character to Wide Character ═══ ═══ Format ═══ #include size_t mbrtowc (wchar_t *pwc, const char *string, size_t n, mbstate_t *ps); ═══ Description ═══ Language Level: ANSI 93 mbrtowc is a restartable version of mbtowc, and performs the same function. It first determines the length of the multibyte character pointed to by string. It then converts the multibyte character to the corresponding wide character, and stores the converted character in the location pointed to by pwc, if pwc is not a null pointer. A maximum of n bytes are examined. With mbrtowc, you can switch from one multibyte string to another. On systems that support shift states, ps represents the initial shift state of the string (0). If you read in only part of the string, mbrtowc sets ps to the string's shift state at the point you stopped. You can then call mbrtowc again for that string and pass in the updated ps value to continue reading where you left off. Note: Because OS/2 does not have shift states, the ps parameter is provided only for compatibility with other ANSI/ISO platforms. VisualAge C++ ignores the value passed for ps. The behavior of mbrtowc is affected by the LC_CTYPE category of the current locale. Return Value If string is a null pointer, mbrtowc returns 0. If string is not a null pointer, mbrtowc returns the first of the following that applies: 0 If the next n or fewer bytes complete the valid multibyte character that corresponds to the null wide character. positive If the next n or fewer bytes complete the valid multibyte character; the value returned is the number of bytes that complete the multibyte character. -2 If the next n bytes form an incomplete (but potentially valid) multibyte character, and all n bytes have been processed. -1 If an encoding error occurs (when the next n or fewer bytes do not form a complete and valid multibyte character). mbrtowc sets errno to EILSEQ. ═══ Example of mbrtowc ═══ /************************************************************************ This example uses mbrlen to move to the second character in a string, then calls mbrtowc to convert the multibyte character to a wide character. ************************************************************************/ #include #include #include #include int main(void) { char mbs1[] = "abc"; char mbs2[] = "\x81\x41\x81\x42" "m"; mbstate_t ss1 = 0; mbstate_t ss2 = 0; size_t length1, length2; wchar_t wc1, wc2; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length1 = mbrlen(mbs1, MB_CUR_MAX, &ss1); length2 = mbrlen(mbs2, MB_CUR_MAX, &ss2); mbrtowc(&wc1, mbs1 + length1, MB_CUR_MAX, &ss1); mbrtowc(&wc2, mbs2 + length2, MB_CUR_MAX, &ss2); printf("The second wide character in mbs1 is: <%lc>\n", wc1); printf("The second wide character in mbs2 is: <%lc>\n", wc2); return 0; /**************************************************************************** The output should be similiar to : The second wide character in mbs1 is: The second wide character in mbs2 is: <─B> ****************************************************************************/ } ═══ Related Information ═══ Example of mbrtowc  mblen - Determine Length of Multibyte Character  mbrlen - Calculate Length of Multibyte Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  setlocale - Set Locale  wcrtomb - Convert Wide Character to Multibyte Character  wcsrtombs - Convert Wide-Character String to Multibyte String   ═══ 4.195. mbsinit - Test Object for Initial State ═══ ═══ Format ═══ #include int mbsinit(mbstate_t *state); ═══ Description ═══ Language Level: Extension mbsinit determines whether the state describes an initial conversion state. Note: mbsinit is provided only for compatibility with EBCDIC systems that support conversion or shift states. OS/2 does not use shift states for multibyte character encoding. Return Value If state is a null pointer or points to 0, mbsinit returns a nonzero value. If state points to any other value, mbsinit returns 0. On systems that support shift states, mbsinit returns nonzero if state describes an initial conversion state, or 0 otherwise. ═══ Example of mbsinit ═══ /************************************************************************ This example checks the conversion state to see if it is in the initial state. ************************************************************************/ #include #include #include int main(void) { char *string = "ABC"; mbstate_t state = 0; wchar_t wc; mbrtowc(&wc, string, MB_CUR_MAX, &state); if (0 != mbsinit(&state)) printf("In initial conversion state.\n"); return 0; /**************************************************************************** The output should be similar to : In initial conversion state. ****************************************************************************/ } ═══ Related Information ═══ Example of mbsinit  mbrlen - Calculate Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  setlocale - Set Locale  wcrtomb - Convert Wide Character to Multibyte Character  wcsrtombs - Convert Wide-Character String to Multibyte String   ═══ 4.196. mbsrtowcs - Convert Multibyte String to Wide-Character String ═══ ═══ Format ═══ #include size_t mbsrtowcs (wchar_t *dest, const char **src, size_t len, mbstate_t *ps); ═══ Description ═══ Language Level: ANSI 93 mbsrtowcs is a restartable version of mbstowcs, and performs the same function. It converts the sequence of multibyte characters from the array indirectly pointed to by src into a sequence of corresponding wide characters, and then stores the converted characters in the array pointed to by dest. Conversion continues up to and including the terminating wchar_t null character. The terminating null wide character is also stored. Conversion stops earlier if a sequence of bytes does not form a valid multibyte character, or when len codes have been stored into the array pointed to by dest. Each conversion takes place as if by a call to the mbrtowc function. mbsrtowcs assigns the object pointed to by src either a null pointer (if conversion stopped because a terminating null character was reached) or the address just past the last multibyte character converted. With mbsrtowcs, you can switch from one multibyte string to another. On platforms that support shift states, ps represents the initial shift state of the string (0). If you read in only part of the string, mbsrtowcs sets ps to the string's shift state at the point you stopped. You can then call mbsrtowcs again for that string and pass in the updated ps value to continue reading where you left off. Note: Because OS/2 does not have shift states, the ps parameter is provided only for compatibility with other ANSI/ISO platforms. VisualAge C++ ignores the value passed for ps. The behavior of mbsrtowcs is affected by the LC_CTYPE category of the current locale. Return Value mbsrtowcs returns the number of multibyte characters successfully converted, not including the terminating null character. If dest is a null pointer, the value of len is ignored and mbsrtowcs returns the number of elements required for the converted wide characters. If the input string contains an invalid multibyte character, mbsrtowcs sets errno to EILSEQ and returns (size_t)-1. ═══ Example of mbsrtowcs ═══ /************************************************************************ This example uses mbsrtowcs to convert the multibyte characters in the arrays mbs1 and mbs2, and store them in the arrays wcs1 and wcs2. ************************************************************************/ #include #include #include #include #define SIZE 10 int main(void) { char mbs1[] = "abc"; char mbs2[] = "\x81\x41" "m" "\x81\x42"; const char *pmbs1 = mbs1; const char *pmbs2 = mbs2; mbstate_t ss1 = 0; mbstate_t ss2 = 0; wchar_t wcs1[SIZE], wcs2[SIZE]; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } mbsrtowcs(wcs1, &pmbs1, SIZE, &ss1); mbsrtowcs(wcs2, &pmbs2, SIZE, &ss2); printf("The first wide character string is %ls.\n", wcs1); printf("The second wide character string is %ls.\n", wcs2); return 0; /**************************************************************************** The output should be similiar to : The first wide character string is abc. The second wide character string is ─Am─B. ****************************************************************************/ } ═══ Related Information ═══ Example of mbsrtowcs  mblen - Determine Length of Multibyte Character  mbrlen - Calculate Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbstowcs - Convert Multibyte String to Wide-Character String  setlocale - Set Locale  wcrtomb - Convert Wide Character to Multibyte Character  wcsrtombs - Convert Wide-Character String to Multibyte String   ═══ 4.197. mbstowcs - Convert Multibyte String to Wide-Character String ═══ ═══ Format ═══ #include size_t mbstowcs(wchar_t *dest, const char *string, size_t len); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 mbstowcs converts the multibyte character string pointed to by string into the wide-character array pointed to by dest. Depending on the encoding scheme used by the code set, the multibyte character string can contain any combination of single-byte or double-byte characters. The conversion stops after len bytes in dest are filled or after a wchar_t null character is encountered. The terminating null character is converted to a wide character with the value 0; characters that follow it are not processed. The behavior of mbstowcs is affected by the LC_CTYPE category of the current locale. Return Value If successful, mbstowcs returns the number of characters converted and stored in dest, not counting the terminating null character. The string pointed to by dest ends with a null character unless mbstowcs returns the value len. If it encounters an invalid multibyte character, mbstowcs returns (size_t)-1. If dest is a null pointer, the value of len is ignored and mbstowcs returns the number of elements required for the converted wide characters. ═══ Example of mbstowcs ═══ /************************************************************************ This example uses mbstowcs to convert the multibyte character mbs to a a wide character string and store it in wcs. ************************************************************************/ #include #include #include #include #define SIZE 10 int main(void) { char mbs[] = "\x81\x41" "m" "\x81\x42"; wchar_t wcs[SIZE]; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } mbstowcs(wcs, mbs, SIZE); printf("The wide character string is %ls.\n", wcs); return 0; /**************************************************************************** The output should be similiar to : The wide character string is ─Am─B. ****************************************************************************/ } ═══ Related Information ═══ Example of mbstowcs  mblen - Determine Length of Multibyte Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  mbtowc - Convert Multibyte Character to Wide Character  setlocale - Set Locale  wcslen - Calculate Length of Wide-Character String  wcstombs - Convert Wide-Character String to Multibyte String   ═══ 4.198. mbtowc - Convert Multibyte Character to Wide Character ═══ ═══ Format ═══ #include int mbtowc(wchar_t *pwc, const char *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 mbtowc first determines the length of the multibyte character pointed to by string. It then converts the multibyte character to the corresponding wide character, and stores it in the location pointed to by pwc, if pwc is not a null pointer. mbtowc examines a maximum of n bytes from string. If pwc is a null pointer, the multibyte character is not converted. The behavior of mbtowc is affected by the LC_CTYPE category of the current locale. Return Value If string is NULL, mbtowc returns 0. Note: On platforms that support shift states, mbtowc can also return a nonzero value to indicate that the multibyte encoding is state dependent. Because VisualAge C++ does not support state-dependent encoding, mbtowc always returns 0 when string is NULL. If string is not NULL, mbtowc returns:  The number of bytes comprising the converted multibyte character, if n or fewer bytes form a valid multibyte character.  0 if string points to the null character.  -1 if string does not point to a valid multibyte character, and the next n bytes do not form a valid multibyte character. ═══ Example of mbtowc ═══ /************************************************************************ This example uses mbtowc to convert the second multibyte character in mbs to a wide character. ************************************************************************/ #include #include #include #include int main(void) { char mb_string[] = "\x81\x41\x81\x42" "c" "\x00"; int length; wchar_t widechar; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length = mblen(mb_string, MB_CUR_MAX); length = mbtowc(&widechar, mb_string + length, MB_CUR_MAX); printf("The wide character %lc has length of %d.\n", widechar, length); return 0; /**************************************************************************** The output should be similar to : The wide character ─B has length of 2. ****************************************************************************/ } ═══ Related Information ═══ Example of mbtowc  mblen - Determine Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbstowcs - Convert Multibyte String to Wide-Character String  setlocale - Set Locale  wcslen - Calculate Length of Wide-Character String  wctomb - Convert Wide Character to Multibyte Character   ═══ 4.199. memccpy - Copy Bytes ═══ ═══ Format ═══ #include /* also in */ void *memccpy(void *dest, void *src, int c, unsigned cnt); ═══ Description ═══ Language Level: Extension memccpy 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. Return Value 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 ═══ /************************************************************************ 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 (NULL == memccpy(result, source, '.', 55)) { printf("Error in copying source.\n"); exit(EXIT_FAILURE); } else printf("%s\n", result); return 0; /**************************************************************************** The output should be: This is the string. ****************************************************************************/ } ═══ Related Information ═══ Example of memccpy  memchr - Search Buffer  memcmp - Compare Buffers  memcpy - Copy Bytes  memmove - Copy Bytes  memset - Set Bytes to Value   ═══ 4.200. memchr - Search Buffer ═══ ═══ Format ═══ #include /* also in */ void *memchr(const void *buf, int c, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension memchr 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. Return Value memchr 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 ═══ /************************************************************************ 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"); } return 0; /**************************************************************************** If the program is passed the argumrnt boxing, the output should be: The string starting with x is xing ****************************************************************************/ } ═══ Related Information ═══ Example of memchr  memccpy - Copy Bytes  memcmp - Compare Buffers  memcpy - Copy Bytes  memicmp - Compare Bytes  memmove - Copy Bytes  memset - Set Bytes to Value  strchr - Search for Character   ═══ 4.201. memcmp - Compare Buffers ═══ ═══ Format ═══ #include /* also in */ int memcmp(const void *buf1, const void *buf2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension memcmp compares the first count bytes of buf1 and buf2. Return Value memcmp returns a value indicating the relationship between the two buffers 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 ═══ /************************************************************************ 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 (0 == result) 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]); } return 0; /**************************************************************************** If the program is passed the arguments "firststring secondstring", the output should be: When the first 11 characters are compared, "firststring" is less than "secondstring" ****************************************************************************/ } ═══ Related Information ═══ Example of memcmp  memccpy - Copy Bytes  memchr - Search Buffer  memcpy - Copy Bytes  memicmp - Compare Bytes  memmove - Copy Bytes  memset - Set Bytes to Value  strcmp - Compare Strings   ═══ 4.202. memcpy - Copy Bytes ═══ ═══ Format ═══ #include /* also */ void *memcpy(void *dest, const void *src, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension memcpy copies count bytes of src to dest. The behavior is undefined if copying takes place between objects that overlap. (The memmove function allows copying between objects that may overlap.) Return Value memcpy returns a pointer to dest. ═══ 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); return 0; /**************************************************************************** The output should be: Before memcpy, target is "This is the target string" After memcpy, target becomes "This is the source string" ****************************************************************************/ } ═══ Related Information ═══ Example of memcpy  memccpy - Copy Bytes  memchr - Search Buffer  memcmp - Compare Buffers  memicmp - Compare Bytes  memmove - Copy Bytes  memset - Set Bytes to Value  strcpy - Copy Strings   ═══ 4.203. memicmp - Compare Bytes ═══ ═══ Format ═══ #include /* also in */ int memicmp(void *buf1, void *buf2, unsigned int cnt); ═══ Description ═══ Language Level: Extension memicmp 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. Return Value 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 ═══ /************************************************************************ 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 (0 == result) printf("equal to String 2.\n"); else printf("greater than String 2.\n"); return 0; /**************************************************************************** The output should be: Comparing the first 29 characters of two strings. The first 29 characters of String 1 are equal to String 2 ****************************************************************************/ } ═══ Related Information ═══ Example of memicmp  memchr - Search Buffer  memcmp - Compare Buffers  memcpy - Copy Bytes  memmove - Copy Bytes  memset - Set Bytes to Value  strcmp - Compare Strings   ═══ 4.204. memmove - Copy Bytes ═══ ═══ Format ═══ #include /* also in */ void *memmove(void *dest, const void *src, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension memmove copies count bytes of src to dest. memmove allows copying between objects that may overlap as if src is first copied into a temporary array. Return Value memmove returns a pointer to dest. ═══ 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); return 0; /**************************************************************************** The output should be: Before memmove, target is "a shiny white sphere" After memmove, target becomes "a shiny shiny sphere" ****************************************************************************/ } ═══ Related Information ═══ Example of memmove  memccpy - Copy Bytes  memchr - Search Buffer  memcmp - Compare Buffers  memcpy - Copy Bytes  memicmp - Compare Bytes  memset - Set Bytes to Value  strcpy - Copy Strings   ═══ 4.205. memset - Set Bytes to Value ═══ ═══ Format ═══ #include /* also in */ void *memset(void *dest, int c, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension memset sets the first count bytes of dest to the value c. The value of c is converted to an unsigned character. Return Value memset returns a pointer to dest. ═══ 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); return 0; /**************************************************************************** The output should be: Buffer contents: AAAAAAAAAA Buffer contents: AAAAAAAAAABBBBBBBBBB ****************************************************************************/ } ═══ Related Information ═══ Example of memset  memccpy - Copy Bytes  memchr - Search Buffer  memcmp - Compare Buffers  memcpy - Copy Bytes  memicmp - Compare Bytes  memmove - Copy Bytes  strnset - strset - Set Characters in String   ═══ 4.206. _mheap - Query Memory Heap for Allocated Object ═══ ═══ Format ═══ #include Heap_t _mheap(void *ptr); ═══ Description ═══ Language Level: Extension _mheap determines from which heap the object specified by ptr was allocated. The ptr must be a valid pointer that was returned from a runtime allocation function (_ucalloc, malloc, realloc, and so on). If the pointer is not valid, the results of _mheap are undefined. For more information about creating and using heaps, see the chapter on Managing Memory in the Programming Guide. Return Value: _mheap returns the handle of the heap from which the object was allocated. If the object was allocated from the runtime heap, _mheap returns _RUNTIME_HEAP. If the object passed to _mheap is NULL, _mheap returns NULL. If the object is not valid, _mheap either returns NULL (depending on how closely the storage pointed to resembles a valid object), or an exception occurs. ═══ Example of _mheap ═══ /************************************************************************ This example allocates a block of memory from the heap, then uses _mheap to determine which heap the block came from. *********************************************************************** / #include #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } printf("Handle of heap used is 0x%x\n", _mheap(ptr)); return 0; /**************************************************************************** The output should be similar to : Handle of heap used is 0x70000 ****************************************************************************/ } ═══ Related Information ═══ Example of _mheap  "Managing Memory" in the Programming Guide  _msize - Return Number of Bytes Allocated  _ucreate - Create a Memory Heap  _ustats - Get Information about Heap  ═══ 4.207. min - Return Lesser of Two Values ═══ ═══ Format ═══ #include type min(type a, type b); ═══ Description ═══ Language Level: Extension min 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. Return Value min returns the smaller of the two values. ═══ 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 output should be: The smaller of 10 and 21 is 10 ****************************************************************************/ } ═══ Related Information ═══ Example of min  max - Return Larger of Two Values  ═══ 4.208. mkdir - Create New Directory ═══ ═══ Format ═══ #include int mkdir(char *pathname); ═══ Description ═══ Language Level: XPG4, Extension mkdir 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. Note: In earlier releases of C Set ++, mkdir began with an underscore (_mkdir). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _mkdir to mkdir for you. Return Value mkdir 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 ═══ /************************************************************************ This example creates two new directories: one at the root on drive C:, 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 (0 == (mkdir(dir1))) 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 (0 == (mkdir(dir2))) 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: 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 ═══ Example of mkdir  chdir - Change Current Working Directory  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  rmdir - Remove Directory  ═══ 4.209. mktime - Convert Local Time ═══ ═══ Format ═══ #include time_t mktime(struct tm *time); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 mktime converts local time, stored as a tm 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 for gmtime. The values of tm_wday and tm_yday passed to mktime are ignored and are assigned their correct values on return. Note: The time and date functions begin at 00:00:00 Coordinated Universal Time, January 1, 1970. Return Value mktime returns the calendar time having type time_t. The value (time_t)(-1) is returned if the calendar time cannot be represented. ═══ 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 %9s \n", wday[t2->tm_wday ]); return 0; /**************************************************************************** The output should be similar to: 40 days and 16 hours from now, it will be a Sunday ****************************************************************************/ } ═══ Related Information ═══ Example of mktime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  time - Determine Current Time  ═══ 4.210. modf - Separate Floating-Point Value ═══ ═══ Format ═══ #include double modf(double x, double *intptr); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 modf 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. Return Value modf returns the signed fractional portion of x. ═══ Example of modf ═══ /************************************************************************ This example breaks the floating-point number -14.876 into its fractional and integral components. ************************************************************************/ #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); return 0; /**************************************************************************** The output should be: x = -14.876000 Integral part = -14.000000 Fractional part = -0.876000 ****************************************************************************/ } ═══ Related Information ═══ Example of modf  fmod - Calculate Floating-Point Remainder  frexp - Separate Floating-Point Value  ldexp - Multiply by a Power of Two  ═══ 4.211. _msize - Return Number of Bytes Allocated ═══ ═══ Format ═══ #include /* also in */ size_t _msize(void *ptr) ═══ Description ═══ Language Level: Extension _msize determines the number of bytes that were allocated to the pointer argument ptr. The ptr must have been returned from one of the runtime memory allocation functions (_ucalloc, malloc, _trealloc, and so on). You cannot pass the argument of an object that has been freed. Return Value _msize returns the number of bytes allocated. If the argument is not a valid pointer returned from a memory allocation function, the return value is undefined. If NULL is passed, _msize returns 0. ═══ Example of _msize ═══ /************************************************************************ This example displays the size of an allocated object from malloc. ************************************************************************/ #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr, 'x', 5); printf("The size of the allocated object is %u.\n",_msize(ptr)); return 0; /**************************************************************************** The output should be similar to : The size of the allocated object is 10. ****************************************************************************/ } ═══ Related Information ═══ Example of _msize  calloc - Reserve and Initialize Storage  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  _tcalloc - Reserve Tiled Storage Block  _tmalloc - Reserve Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block   ═══ 4.212. nl_langinfo - Retrieve Locale Information ═══ ═══ Format ═══ #include #include char *nl_langinfo(nl_item item); ═══ Description ═══ Language Level: XPG4 nl_langinfo retrieves from the current locale the string that describes the requested information specified by item. The constant names and values for item are defined in . For a list of macros that define the constants used to identify the information queried in the current locale, see the table of defined macros under langinfo.h. You cannot retrieve the following information for the current locale: t_fmt_ampm era era_year era_d_fmt alt_digits t_fmt_ampm alt_digits Return Value nl_langinfo returns a pointer to a null-terminated string containing information about the active language or cultural area. The active language or cultural area is determined by the most recent setlocale call. Subsequent calls to the function may modify the array that the return value points to. Your own code cannot modify the array. If item is not valid, nl_langinfo returns a pointer to an empty string. ═══ Example of nl_langinfo ═══ /************************************************************************ This example uses nl_langinfo to retrieve the current codeset name. ************************************************************************/ #include #include #include int main(void) { printf("Current codeset is %s\n", nl_langinfo(CODESET)); return 0; /**************************************************************************** The output should be similar to : Current codeset is IBM-850 ****************************************************************************/ } ═══ Related Information ═══ Example of nl_langinfo  localdtconv - Return Date and Time Formatting Convention  localeconv - Retrieve Information from the Environment  setlocale - Set Locale   ═══ 4.213. _onexit - Record Termination Function ═══ ═══ Format ═══ #include onexit_t _onexit(onexit_t func); ═══ Description ═══ Language Level: Extension _onexit 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/ISO standard atexit function, which is equivalent to _onexit. Return Value If successful, _onexit returns a pointer to the function; otherwise, it returns a NULL value. ═══ 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: This is run first. This is run next. ****************************************************************************/ } ═══ Related Information ═══ Example of _onexit  abort - Stop a Program  atexit - Record Program Termination Function  exit - End Program  _exit - End Process  ═══ 4.214. open - Open File ═══ ═══ Format ═══ #include #include #include int open(char *pathname, int oflag, int pmode); ═══ Description ═══ Language Level: XPG4, Extension open opens the file specified by pathname and prepares the file for subsequent reading or writing as defined by oflag. open 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 . To specify more than one constant, join the constants with the bitwise OR operator (|); for example, O_CREAT | O_TEXT. 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. O_TEXT Open the file in text (translated) mode. 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. For more details on text and binary modes and their differences, see "Stream Processing" in the Programming Guide. 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. open applies the current file permission mask to pmode before setting the permissions. (See umask - Sets File Mask of Current Process.) Note: In earlier releases of C Set ++, open began with an underscore (_open). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _open to open for you. Return Value open 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 ═══ /************************************************************************ This example opens 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 #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 EXIT_FAILURE; } printf("File was successfully opened.\n"); if (-1 == close(fh)) { perror("close error"); return EXIT_FAILURE; } return 0; /**************************************************************************** The output should be: File was successfully opened. ****************************************************************************/ } ═══ Related Information ═══ Example of open  close - Close File Associated with Handle  creat - Create New File  fdopen - Associates Input Or Output With File  fopen - Open Files  _sopen - Open Shared File  umask - Sets File Mask of Current Process    ═══ 4.215. _outp - Write Byte to Output Port ═══ ═══ Format ═══ #include /* also in */ int _outp( const unsigned int port, const int value ); ═══ Description ═══ Language Level: Extension _outp writes a byte value to the specified port. The port number must be an unsigned integer value within the range 0 to 65 535 inclusive. The byte value must be within the range 0 to 255 inclusive. Note: _outp is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _outp.  You cannot parenthesize a call to _outp. (Parentheses specify a call to the function's backing code, and _outp has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _outp returns the integer value that was output to the specified port. There is no error return value, and _outp does not set errno. ═══ Example of _outp ═══ /************************************************************************ This example uses _outp 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, cantaloupes}; enum fruit f = cantaloupes; int arr[] = {cantaloupes, 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 ═══ Example of _outp  _inp - Read Byte from Input Port  _inpw - Read Unsigned Short from Input Port  _inpd - Read Doubleword from Input Port  _outpw - Write Word to Output Port  _outpd - Write Double Word to Output Port   ═══ 4.216. _outpd - Write Double Word to Output Port ═══ ═══ Format ═══ #include /* also in Description ═══ Language Level: Extension _outpd 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. Note: _outpd is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _outpd.  You cannot parenthesize a call to _outpd. (Parentheses specify a call to the function's backing code, and _outpd has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _outpd returns the unsigned long value that was output to the specified port. There is no error return value, and _outpd does not set errno. ═══ Example of _outpd ═══ /************************************************************************ This example uses _outpd 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 long g; enum fruit {apples=10, bananas, cantaloupes}; enum fruit f = cantaloupes; int arr[] = {cantaloupes, 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 ═══ Example of _outpd  _inp - Read Byte from Input Port  _inpw - Read Unsigned Short from Input Port  _inpd - Read Doubleword from Input Port  _outp - Write Byte to Output Port  _outpw - Write Word to Output Port   ═══ 4.217. _outpw - Write Word to Output Port ═══ ═══ Format ═══ #include /* also in Description ═══ Language Level: Extension _outpw writes an unsigned short word to the specified port. The port number must be an unsigned integer value within the range 0 to 65 535 inclusive. The unsigned short word must be in the range 0 to 65 535. Note: _outpw is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of _outpw.  You cannot parenthesize a call to _outpw. (Parentheses specify a call to the function's backing code, and _outpw has none.) You can run code containing this function only at ring zero. Otherwise, an invalid instruction exception is generated. Return Value _outpw returns the value that was output to the specified port. There is no error return value, and _outpw does not set errno. ═══ Example of _outpw ═══ /************************************************************************ This example uses _outpw 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, cantaloupes}; enum fruit f = cantaloupes; int arr[] = {cantaloupes, bananas, apples}; unsigned short s; static int i = 0; volatile const int c = 255; g = _outpw(cantaloupes, 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 ═══ Example of _outpw  _inp - Read Byte from Input Port  _inpw - Read Unsigned Short from Input Port  _inpd - Read Doubleword from Input Port  _outp - Write Byte to Output Port  _outpd - Write Double Word to Output Port   ═══ 4.218. __parmdwords - Get Number of dwords in Parameter List ═══ ═══ Format ═══ #include /* also 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. Note: To use __parmdwords, you must compile with the /Gp+ option to include the support for it. 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:  You cannot take the address of __parmdwords.  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. 3. Not all vendors implement the hidden parameter in the AL register, so __parmdwords may have incorrect results when you use it in a function that is called from code compiled by other compilers. The __parmdwords function returns the size of the parameter list passed to the function in units of dwords. 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 MessgageNum,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 = EXIT_FAILURE; 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 = EXIT_FAILURE; } } return rc; } int main(void) { return ErrorHandler(MESSAGE1, FATAL); /**************************************************************************** The output should be: Fatal Error:Some immensely profound message ****************************************************************************/ } ═══ Related Information ═══  Calling Conventions in the Programming Guide  /Gp option in the User's Guide  ═══ 4.219. perror - Print Error Message ═══ ═══ Format ═══ #include void perror(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 perror prints an error message to stderr. If string is not NULL and 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. Return Value There is no return value. ═══ Example of perror ═══ /************************************************************************ This example tries to open a stream. If fopen fails, the example prints a message and ends the program. ************************************************************************/ #include #include int main(void) { FILE *fh; if (NULL == (fh = fopen("myfile.mjq", "r"))) { perror("Could not open data file"); abort(); } return 0; /**************************************************************************** The output should be: Could not open data file: The file cannot be found. ****************************************************************************/ } ═══ Related Information ═══ Example of perror  clearerr - Reset Error Indicators.  ferror - Test for Read/Write Errors  strerror - Set Pointer to Runtime Error Message  _strerror - Set Pointer to System Error String  Runtime Return Codes and Messages in the User's Guide  ═══ 4.220. pow - Compute Power ═══ ═══ Format ═══ #include double pow(double x, double y); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 pow calculates the value of x to the power of y. Return Value 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 returns +HUGE_VAL for a large result or -HUGE_VAL for a small result. ═══ 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); return 0; /**************************************************************************** The output should be: 2.000000 to the power of 3.000000 is 8.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of pow  exp - Calculate Exponential Function  _fsqrt - Calculate Square Root  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  sqrt - Calculate Square Root  ═══ 4.221. printf - Print Formatted Characters ═══ ═══ Format ═══ #include int printf(const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension printf 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 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. If you specify a null string for the %s or %ls format specifier, printf prints (null). (In previous releases of C Set ++, printf produced no output for a null string.) Return Value printf returns the number of bytes printed. ═══ Related Information ═══ Example of printf  Format Specification - Types  Format Specification - Flags  Format Specification - Width  Format Specification - Precision  Format Specification - h,l,L  fprintf - Write Formatted Data to a Stream  fscanf - Read Formatted Data  scanf - Read Data  sprintf - Print Formatted Data to Buffer  sscanf - Read Data  Infinity and NaN Support  ═══ 4.221.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 mag- │ │ │ │ nitude of the number. The number of digits after │ │ │ │ the decimal point is equal to the requested preci- │ │ │ │ sion. NaN and infinity values are printed in lower- │ │ │ │ case ("nan" and "infinity"). │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ F │ Double │ In extended mode ("/Se" option), identical to the │ │ │ │ "f" format except that NaN and infinity values are │ │ │ │ printed in uppercase ("NAN" and "INFINITY"). In │ │ │ │ modes other than extended, "F" is treated like any │ │ │ │ other character not included in this table. │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ 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" intro- │ │ │ │ duces 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" intro- │ │ │ │ duces the exponent (where appropriate) instead of │ │ │ │ "e". │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ c │ Character │ Single character. │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ lc │ Wide char- │ Multibyte character (converted as if by a call to │ │ │ acter │ wcrtomb). │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ s │ String │ Characters printed up to the first null character │ │ │ │ (\"0") or until precision is reached. If you │ │ │ │ specify a null string, "(null)" is printed. │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ ls │ Wide- │ Multibyte characters, printed up to the first │ │ │ character │ "wchar_t" null character ("L\0") is encountered in │ │ │ string. │ the wide-character string, or until the specified │ │ │ │ precision is reached. Conversion takes place as if │ │ │ │ by a call to wcrtomb. The displayed result does not │ │ │ │ include the terminating null character. If you do │ │ │ │ not specify the precision, you must end the wide- │ │ │ │ character string with a null character. A partial │ │ │ │ multibyte character cannot be written. If you │ │ │ │ specify a null string, "(null)" is printed. │ ├──────────┼────────────┼──────────────────────────────────────────────────────┤ │ n │ Pointer to │ Number of characters successfully written so far to │ │ │ integer │ the 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. │ └──────────┴────────────┴──────────────────────────────────────────────────────┘ ═══ 4.221.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): ┌──────────────────────────────────────────────────────────────────────────────┐ │ Table 3. Flag Characters │ ├───────────┬───────────────────────────────────────────┬──────────────────────┤ │ 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", "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", "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. ═══ 4.221.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. ═══ 4.221.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" or │ │ d │ digits to be printed. If the number of │ omitted entirely, or │ │ u │ digits in the argument is less than preci- │ if the period (.) │ │ o │ sion, the output value is padded on the │ appears without a │ │ x │ left with zeros. The value is not trun- │ number following it, │ │ X │ cated when the number of digits exceeds │ the precision is set │ │ │ precision. │ to 1. │ ├────────┼────────────────────────────────────────────┼────────────────────────┤ │ f │ Precision specifies the number of digits │ Default precision is │ │ F │ to be printed after the decimal point. │ six. If precision is │ │ e │ The last digit printed is rounded. │ "0" or the period │ │ E │ │ appears without a │ │ │ │ number following it, │ │ │ │ no decimal point is │ │ │ │ printed. │ ├────────┼────────────────────────────────────────────┼────────────────────────┤ │ g │ Precision specifies the maximum number of │ All significant digits │ │ G │ significant digits printed. │ 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 printed │ │ │ characters to be printed. Characters in │ until a null character │ │ │ excess of precision are not printed. │ is encountered. │ ├────────┼────────────────────────────────────────────┼────────────────────────┤ │ ls │ Precision specifies the maximum number of │ "wchar_t" characters │ │ │ bytes to be printed. Bytes in excess of │ are printed until a │ │ │ precision are not printed; however, multi- │ null character is │ │ │ byte integrity is always preserved. │ encountered. │ └────────┴────────────────────────────────────────────┴────────────────────────┘ ═══ 4.221.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); return 0; /**************************************************************************** The output should be: 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 ****************************************************************************/ } ═══ 4.222. putc - putchar - Write a Character ═══ ═══ Format ═══ #include int putc(int c, FILE *stream); int putchar(int c); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 putc converts c to unsigned char and then writes c to the output stream at the current position. putchar is equivalent to putc(c, stdout). putc is equivalent to fputc except that, if it is implemented as a macro, putc can evaluate stream more than once. Therefore, the stream argument to putc should not be an expression with side effects. Return Value putc and putchar return the character written. A return value of EOF indicates an error. ═══ 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 #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 < sizeof(buffer)) && ((ch = putc(buffer[i], stream)) != EOF); ++i) ; return 0; /**************************************************************************** The output should be: Hello world ****************************************************************************/ } ═══ Related Information ═══ Example of putc - putchar  fputc - Write Character  _fputchar - Write Character  fwrite - Write Items  getc - getchar - Read a Character  _putch - Write Character to Screen  puts - Write a String  write - Writes from Buffer to File  ═══ 4.223. _putch - Write Character to Screen ═══ ═══ Format ═══ #include int _putch(int c); ═══ Description ═══ Language Level: Extension _putch writes the character c directly to the screen. Return Value If successful, _putch returns c. If an error occurs, _putch returns EOF. ═══ 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 ═══ Example of _putch  _cputs - Write String to Screen  _cprintf - Print Characters to Screen  fputc - Write Character  _getch - _getche - Read Character from Keyboard  putc - putchar - Write a Character  puts - Write a String  write - Writes from Buffer to File  ═══ 4.224. putenv - Modify Environment Variables ═══ ═══ Format ═══ #include int putenv(char *envstring); ═══ Description ═══ Language Level: XPG4, Extension putenv 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 the envstring pointer while the entry it points to is 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. Once you have added the envstring with putenv, any change to the entry it points to changes the environment used by your program. 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 putenv, but getenv will reflect the changes. Notes 1. putenv can change the value of _environ, thus invalidating the envp argument to the main function. 2. You cannot use %envvar%, where envvar is any OS/2 environment variable, with putenv to concatenate new envstring and old envstring. 3. In earlier releases of C Set ++, putenv began with an underscore (_putenv). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _putenv to putenv for you. Return Value putenv returns 0 if it is successful. A return value of -1 indicates an error. ═══ 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 (-1 == putenv("PATH=a:\\bin;b:\\andy")) { printf("putenv failed - out of memory\n"); return EXIT_FAILURE; } /* getting and printing the current environment path */ pathvar = getenv("PATH"); printf("The current path is: %s\n", pathvar); return 0; /**************************************************************************** The output should be: The current path is: a:\bin;b:\andy ****************************************************************************/ } ═══ Related Information ═══ Example of putenv  execl - _execvpe - Load and Run Child Process  getenv - Search for Environment Variables  _spawnl - _spawnvpe - Start and Run Child Processes  system - Invoke the Command Processor  "envp Parameter to main" in the Programming Guide  ═══ 4.225. puts - Write a String ═══ ═══ Format ═══ #include int puts(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 puts 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. Return Value puts returns EOF if an error occurs. A nonnegative return value indicates that no error has occurred. ═══ Example of puts ═══ /************************************************************************ This example writes Hello World to stdout. ************************************************************************/ #include int main(void) { if (EOF == puts("Hello World")) printf("Error in puts\n"); return 0; /**************************************************************************** The output should be: Hello World ****************************************************************************/ } ═══ Related Information ═══ Example of puts  _cputs - Write String to Screen  fputs - Write String  gets - Read a Line  putc - putchar - Write a Character  ═══ 4.226. putwc - Write Wide Character ═══ ═══ Format ═══ #include #include wint_t putwc(wint_t wc, FILE *stream); ═══ Description ═══ Language Level: ANSI 93, XPG4 putwc converts the wide character wc to a multibyte character, and writes it to the stream at the current position. It also advances the file position indicator for the stream appropriately. putwc function is equivalent to fputwc except that, if it is implemented as a macro, putwc can evaluate stream more than once. Therefore, the stream argument to putwc should not be an expression with side effects. The behavior of putwc is affected by the LC_CTYPE category of the current locale. Using a non-wide-character function with putwc on the same stream results in undefined behavior. After calling putwc, flush the buffer or reposition the stream pointer before calling a write function for the stream, unless EOF has been reached. After a write operation on the stream, flush the buffer or reposition the stream pointer before calling putwc. Return Value putwc returns the wide character written. If a write error occurs, putwc sets the error indicator for the stream and returns WEOF. If an encoding error occurs when a wide character is converted to a multibyte character, putwc sets errno to EILSEQ and returns WEOF. ═══ Example of putwc ═══ /************************************************************************ The following example uses putwc to convert the wide characters in wcs to multibyte characters and write them to the file putwc.out. ************************************************************************/ #include #include #include #include int main(void) { FILE *stream; wchar_t *wcs = L"A character string."; int i; if (NULL == (stream = fopen("putwc.out", "w"))) { printf("Unable to open: \"putwc.out\".\n"); exit(EXIT_FAILURE); } for (i = 0; wcs[i] != L'\0'; i++) { errno = 0; if (WEOF == putwc(wcs[i], stream)) { printf("Unable to putwc() the wide character.\n" "wcs[%d] = 0x%lx\n", i, wcs[i]); if (EILSEQ == errno) printf("An invalid wide character was encountered.\n"); exit(EXIT_FAILURE); } } fclose(stream); return 0; /**************************************************************************** The output file putwc.out should contain : A character string. ****************************************************************************/ } ═══ Related Information ═══ Example of putwc  fputc - Write Character  _fputchar - Write Character  fputwc - Write Wide Character  getwc - Read Wide Character from Stream  putc - putchar - Write a Character  _putch - Write Character to Screen  putwchar - Write Wide Character to stdout   ═══ 4.227. putwchar - Write Wide Character to stdout ═══ ═══ Format ═══ #include wint_t putwchar(wint_t wc); ═══ Description ═══ Language Level: ANSI 93, XPG4 putwchar converts the wide character wc to a multibyte character and writes it to stdout. A call to putwchar is equivalent to putwc(wc, stdout). The behavior of putwchar is affected by the LC_CTYPE category of the current locale. Using a non-wide-character function with putwchar on the same stream results in undefined behavior. After calling putwchar, flush the buffer or reposition the stream pointer before calling a write function for the stream, unless EOF has been reached. After a write operation on the stream, flush the buffer or reposition the stream pointer before calling putwchar. Return Value putwchar returns the wide character written. If a write error occurs, putwchar sets the error indicator for the stream and returns WEOF. If an encoding error occurs when a wide character is converted to a multibyte character, putwchar sets errno to EILSEQ and returns WEOF. ═══ Example of putwchar ═══ /************************************************************************ This example uses putwchar to write the string in wcs. ************************************************************************/ #include #include #include #include int main(void) { wchar_t *wcs = L"A character string."; int i; for (i = 0; wcs[i] != L'\0'; i++) { errno = 0; if (WEOF == putwchar(wcs[i])) { printf("Unable to putwchar() the wide character.\n"); printf("wcs[%d] = 0x%lx\n", i, wcs[i]); if (EILSEQ == errno) printf("An invalid wide character was encountered.\n"); exit(EXIT_FAILURE); } } return 0; /**************************************************************************** The output should be similar to : A character string. ****************************************************************************/ } ═══ Related Information ═══ Example of putwchar  fputc - Write Character  _fputchar - Write Character  fputwc - Write Wide Character  getwchar - Get Wide Character from stdin  putc - putchar - Write a Character  _putch - Write Character to Screen  ═══ 4.228. qsort - Sort Array ═══ ═══ Format ═══ #include void qsort(void *base, size_t num, size_t width, int(*compare)(const void *key, const void *element)); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 qsort sorts an array of num elements, each of width bytes in size. The base pointer is a pointer to the array to be sorted. qsort overwrites this array with the sorted elements. The compare argument is a pointer to a function you must supply that takes a pointer to the key argument and to an array element, in that order. qsort calls this function one or more times during the search. The function must compare the key and the element and return one of the following values: Value Meaning Less than 0 key less than element 0 key equal to element Greater than 0 key greater than element The sorted array elements are stored in ascending order, as defined by your compare function. You can sort in reverse order by reversing the sense of "greater than" and "less than" in compare. The order of the elements is unspecified when two elements compare equally. Return Value There is no return value. ═══ 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 /* -------------------------------------------------------------- */ /* compare() routine called internally by qsort() */ /* */ /* Assert: Library always calls functions internally with */ /* _Optlink linkage convention. Ensure that compare() is */ /* always _Optlink. */ /* -------------------------------------------------------------- */ int _Optlink compare(const void *arg1,const void *arg2) { return (strcmp(*(char **)arg1, *(char **)arg2)); } 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; /**************************************************************************** Assuming command line of: qsort kent theresa andrea laura brenden Output should be: andrea brenden kent laura theresa ****************************************************************************/ } ═══ Related Information ═══ Example of qsort  bsearch - Search Arrays  lfind - lsearch - Find Key in Array   ═══ 4.229. raise - Send Signal ═══ ═══ Format ═══ #include int raise(int sig); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 raise sends the signal sig to the running program. You can then use signal to handle sig. Signals and signal handling are described in signal - Handle Interrupt Signals, and in the Programming Guide under Signal and Exception Handling. Return Value raise returns 0 if successful, nonzero if unsuccessful. ═══ 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 */ return 0; } void sig_hand(int sig) { static int count = 0; /* initialized only once */ count++; if (10 == count) /* ignore the first 9 occurrences of this signal */ exit(10); else signal(SIGUSR1, sig_hand); /* set up the handler again */ raise(SIGUSR1); } ═══ Related Information ═══ Example of raise  signal - Handle Interrupt Signals  Signal and Exception Handling in the Programming Guide  ═══ 4.230. rand - Generate Random Number ═══ ═══ Format ═══ #include int rand(void); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 rand generates a pseudo-random integer in the range 0 to RAND_MAX (macro defined in ). Use srand before calling rand to set a starting point for the random number generator. If you do not call srand first, the default seed is 1. Return Value rand returns a pseudo-random number. ═══ 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()); return 0; /**************************************************************************** The output should be: 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 ═══ Example of rand  srand - Set Seed for rand Function  ═══ 4.231. read - Read Into Buffer ═══ ═══ Format ═══ #include int read(int handle, char *buffer, unsigned int count); ═══ Description ═══ Language Level: XPG4, Extension read 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. Note: In earlier releases of C Set ++, read began with an underscore (_read). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _read to read for you. Return Value read 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 ═══ /************************************************************************ 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 EXIT_FAILURE; } if (7 != read(fh, buffer, 7)) { perror("Unable to read from sample.dat."); close(fh); return EXIT_FAILURE; } printf("Successfully read in the following:\n%s\n ", buffer); close(fh); return 0; /**************************************************************************** The output should be: Creating sample.dat. Successfully read in the following: Sample ****************************************************************************/ } ═══ Related Information ═══ Example of read  creat - Create New File  fread - Read Items  open - Open File  _sopen - Open Shared File  write - Writes from Buffer to File  ═══ 4.232. realloc - Change Reserved Storage Block Size ═══ ═══ Format ═══ #include /* also in */ void *realloc(void *ptr, size_t size); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension realloc 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. realloc allocates the new block from the same heap the original block was in. If ptr is NULL, realloc reserves a block of storage of size bytes from the current thread's default heap (equivalent to calling malloc(size)). If size is 0 and the ptr is not NULL, realloc frees the storage allocated to ptr and returns NULL Return Value realloc returns a pointer to the reallocated storage block. The storage location of the block may be moved by the realloc function. Thus, the ptr argument to realloc is not necessarily the same as the return value. If size is 0, realloc returns NULL. If there is not enough storage to expand the block to the given size, the original block is unchanged and realloc returns NULL. The storage to which the return value points is aligned for storage of any type of object. ═══ 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(); } return 0; /**************************************************************************** The output should be similar to: Enter the size of the array 2 The array of size 2 is: array[ 0 ] = 0 array[ 1 ] = 1 Enter the size of the new array 4 The array of size 4 is: array[ 0 ] = 0 array[ 1 ] = 1 array[ 2 ] = 2002 array[ 3 ] = 2003 ****************************************************************************/ } 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]); } ═══ Related Information ═══ Example of realloc  calloc - Reserve and Initialize Storage  _debug_realloc - Reallocate Memory Block  _debug_trealloc - Reallocate Tiled Memory Block  free - Release Storage Blocks  malloc - Reserve Storage Block  _msize - Return Number of Bytes Allocated  _trealloc - Reallocate Tiled Storage Block   ═══ 4.233. regcomp - Compile Regular Expression ═══ ═══ Format ═══ #include int regcomp(regex_t *preg, const char *pattern, int cflags); ═══ Description ═══ Language Level: POSIX, XPG4 regcomp compiles the source regular expression pointed to by pattern into an executable version and stores it in the location pointed to by preg. You can then use regexec to compare the regular expression to other strings. The cflags flag defines the attributes of the compilation process: REG_EXTENDED Support extended regular expressions. REG_NEWLINE Treat new-line character as a special end-of-line character; it then establishes the line boundaries matched by the ^ and $ patterns, and can only be matched within a string explicitly using \n. (If you omit this flag, the new-line character is treated like any other character.) REG_ICASE Ignore case in match. REG_NOSUB Ignore the number of subexpressions specified in pattern. When you compare a string to the compiled pattern (using regexec), the string must match the entire pattern. regexec then returns a value that indicates only if a match was found; it does not indicate at what point in the string the match begins, or what the matching string is. Regular expressions are a context-independent syntax that can represent a wide variety of character sets and character set orderings, which can be interpreted differently depending on the current locale. The functions regcomp, regerror, regexec, and regfree use regular expressions in a similar way to the UNIX awk, ed, grep, and egrep commands. Regular expressions are described in more detail under "Regular Expressions" in the Programming Guide. Return Value If regcomp is successful, it returns 0. Otherwise, it returns an error code that you can use in a call to regerror, and the content of preg is undefined. ═══ Example of regcomp ═══ /************************************************************************ This example compiles an extended regular expression. ************************************************************************/ #include #include #include int main(void) { regex_t preg; char *pattern = ".*(simple).*"; int rc; if (0 != (rc = regcomp(&preg, pattern, REG_EXTENDED))) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(EXIT_FAILURE); } printf("regcomp() is sucessful.\n"); return 0; /**************************************************************************** The output should be similar to : regcomp() is sucessful. ****************************************************************************/ } ═══ Related Information ═══ Example of regcomp  regerror - Return Error Message for Regular Expression  regexec - Execute Compiled Regular Expression  regfree - Free Memory for Regular Expression  "Regular Expressions" in the Programming Guide  ═══ 4.234. regerror - Return Error Message for Regular Expression ═══ ═══ Format ═══ #include size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size); ═══ Description ═══ Language Level: POSIX, XPG4 regerror finds the description for the error code errcode for the regular expression preg. The description for errcode is assigned to errbuf. errbuf_size is a value that you provide that specifies the maximum message size that can be stored (the size of errbuf). Regular expressions are described in detail under "Regular Expressions" in the Programming Guide. The description strings for errcode are: errcode Description String REG_NOMATCH RE pattern not found REG_BADPAT Invalid regular expression REG_ECOLLATE Invalid collating element REG_ECTYPE Invalid character class REG_EESCAPE Last character is \ REG_ESUBREG Invalid number in \digit REG_EBRACK [] imbalance REG_EPAREN \( \) or () imbalance REG_EBRACE \{ \} or { } imbalance REG_BADBR Invalid \{ \} range exp REG_ERANGE Invalid range exp endpoint REG_ESPACE Out of memory REG_BADRPT ?*+ not preceded by valid RE REG_ECHAR Invalid multibyte character REG_EBOL ^ anchor and not BOL REG_EEOL $ anchor and not EOL The error descriptions are in the IBMCRERR.MSG message file. The directory for this file must be in your DPATH environment variable for the messages to be found. Return Value regerror returns the size of the buffer needed to hold the string that describes the error condition. ═══ Example of regerror ═══ /************************************************************************ This example compiles an invalid regular expression, and prints an error message using regerror. ************************************************************************/ #include #include #include int main(void) { regex_t preg; char *pattern = "a[missing.bracket"; int rc; char buffer[100]; if (0 != (rc = regcomp(&preg, pattern, REG_EXTENDED))) { regerror(rc, &preg, buffer, 100); printf("regcomp() failed with '%s'\n", buffer); exit(EXIT_FAILURE); } return 0; /**************************************************************************** The output should be similar to : regcomp() failed with '[] imbalance' ****************************************************************************/ } ═══ Related Information ═══ Example of regerror  regcomp - Compile Regular Expression  regexec - Execute Compiled Regular Expression  regfree - Free Memory for Regular Expression  "Regular Expressions" in the Programming Guide  ═══ 4.235. regexec - Execute Compiled Regular Expression ═══ ═══ Format ═══ #include int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t *pmatch, int eflags); ═══ Description ═══ Language Level: POSIX, XPG4 regexec compares the null-terminated string against the compiled regular expression preg to find a match between the two. (Regular expressions are described in "Regular Expressions" in the Programming Guide.) nmatch is the number of substrings in string that regexec should try to match with subexpressions in preg. The array you supply for pmatch must have at least nmatch elements. regexec fills in the elements of the array pmatch with offsets of the substrings in string that correspond to the parenthesized subexpressions of the original pattern given to regcomp to create preg. The zeroth element of the array corresponds to the entire pattern. If there are more than nmatch subexpressions, only the first nmatch - 1 are stored. If nmatch is 0, or if the REG_NOSUB flag was set when preg was created with regcomp, regexec ignores the pmatch argument. The eflags flag defines customizable behavior of regexec: REG_NOTBOL Indicates that the first character of string is not the beginning of line. REG_NOTEOL Indicates that the first character of string is not the end of line. When a basic or extended regular expression is matched, any given parenthesized subexpression of the original pattern could participate in the match of several different substrings of string. The following rules determine which substrings are reported in pmatch.: 1. If a subexpression participated in a match several times, regexec stores the offset of the last matching substring in pmatch. 2. If a subexpression did not match in the source string, regexec sets the offset shown in pmatch to -1. 3. If a subexpression contains subexpressions, the data in pmatch refers to the last such subexpression. 4. If a subexpression matches a zero-length string, the offsets in pmatch refer to the byte immediately following the matching string. If the REG_NOSUB flag was set when preg was created by regcomp, the contents of pmatch are unspecified. If the REG_NEWLINE flag was not set when preg was created, new-line characters are allowed in string. Note: If MB_CUR_MAX is specified as 2, the charmap file does not specify the DBCS characters, and a collating element (for example, [:a:]) is specified in the pattern, the DBCS characters will not match against the collating-element even if they have an equivalent weight to the collating-element. Return Value If a match is found, regexec returns 0. Otherwise, it returns a nonzero value indicating either no match or an error. ═══ Example of regexec ═══ /************************************************************************ This example compiles an expression and matches a string against it. The first substring uses the full pattern. The second substring uses the sub-expression inside the full pattern. ************************************************************************/ #include #include #include int main(void) { regex_t preg; char *string = "a very simple simple simple string"; char *pattern = "\\(sim[a-z]le\\) \\1"; int rc; size_t nmatch = 2; regmatch_t pmatch[2]; if (0 != (rc = regcomp(&preg, pattern, 0))) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(EXIT_FAILURE); } if (0 != (rc = regexec(&preg, string, nmatch, pmatch, 0))) { printf("Failed to match '%s' with '%s',returning %d.\n", string, pattern, rc); } else { printf("With the whole expression, " "a matched substring \"%.*s\" is found at position %d to %d.\n", pmatch[0].rm_eo - pmatch[0].rm_so, &string[pmatch[0].rm_so], pmatch[0].rm_so, pmatch[0].rm_eo - 1); printf("With the sub-expression, " "a matched substring \"%.*s\" is found at position %d to %d.\n", pmatch[1].rm_eo - pmatch[1].rm_so, &string[pmatch[1].rm_so], pmatch[1].rm_so, pmatch[1].rm_eo - 1); } regfree(&preg); return 0; /**************************************************************************** The output should be similar to : With the whole expression, a matched substring "simple simple" is found at position 7 to 19. With the sub-expression, a matched substring "simple" is found at position 7 to 12. ****************************************************************************/ } ═══ Related Information ═══ Example of regexec  regcomp - Compile Regular Expression  regerror - Return Error Message for Regular Expression  regfree - Free Memory for Regular Expression  "Regular Expressions" in the Programming Guide  ═══ 4.236. regfree - Free Memory for Regular Expression ═══ ═══ Format ═══ #include void regfree(regex_t *preg); ═══ Description ═══ Language Level: POSIX, XPG4 regfree frees any memory that was allocated by regcomp to implement the regular expression preg. After the call to regfree, the expression defined by preg is no longer a compiled regular or extended expression. Regular expressions are described in "Regular Expressions" in the Programming Guide. Return Value There is no return value. ═══ Example of regfree ═══ /************************************************************************ This example compiles an extended regular expression and frees it. ************************************************************************/ #include #include #include int main(void) { regex_t preg; char *pattern = ".*(simple).*"; int rc; if (0 != (rc = regcomp(&preg, pattern, REG_EXTENDED))) { printf("regcomp() failed, returning nonzero (%d)\n", rc); exit(EXIT_FAILURE); } regfree(&preg); printf("Memory allocated for reg is freed.\n"); return 0; /**************************************************************************** The output should be similar to : Memory allocated for reg is freed. ****************************************************************************/ } ═══ Related Information ═══ Example of regfree  regcomp - Compile Regular Expression  regerror - Return Error Message for Regular Expression  regexec - Execute Compiled Regular Expression  "Regular Expressions" in the Programming Guide  ═══ 4.237. remove - Delete File ═══ ═══ Format ═══ #include int remove(const char *filename); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 remove deletes the file specified by filename. Note: You cannot remove a nonexistent file or a file that is open. Return Value remove returns 0 if it successfully deletes the file. A nonzero return value idicates an error. ═══ Example of remove ═══ /************************************************************************ This example uses remove to remove a file. It issues a message if an error occurs. ************************************************************************/ #include int main(void) { char *FileName = "file2rm.mjq"; FILE *fp; fp = fopen(FileName, "w"); fprintf(fp, "Hello world\n"); fclose(fp); if (remove(FileName) != 0) perror("Could not remove file"); else printf("File \"%s\" removed successfully.\n", FileName); return 0; /**************************************************************************** The output should be: File "file2rm.mjq" removed successfully. ****************************************************************************/ } ═══ Related Information ═══ Example of remove  fopen - Open Files  rename - Rename File  _rmtmp - Remove Temporary Files  unlink - Delete File  ═══ 4.238. rename - Rename File ═══ ═══ Format ═══ #include /* also in */ int rename(const char *oldname, const char *newname); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 rename 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. Both oldname and newname must be on the same drive; you cannot rename files across drives. You cannot rename a file with the name of an existing file. You also cannot rename an open file. Return Value rename returns 0 if successful. On an error, it returns a nonzero value. ═══ Example of rename ═══ /************************************************************************ This example uses rename to rename a file. It issues a message if errors occur. ************************************************************************/ #include int main(void) { char *OldName = "oldfile.mjq"; char *NewName = "newfile.mjq"; FILE *fp; fp = fopen(OldName, "w"); fprintf(fp, "Hello world\n"); fclose(fp); if (rename(OldName, NewName) != 0) perror("Could not rename file"); else printf("File \"%s\" is renamed to \"%s\".\n", OldName, NewName); return 0; /**************************************************************************** The output should be: File "oldfile.mjq" is renamed to "newfile.mjq". ****************************************************************************/ } ═══ Related Information ═══ Example of rename  fopen - Open Files  remove - Delete File  ═══ 4.239. rewind - Adjust Current File Position ═══ ═══ Format ═══ #include void rewind(FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 rewind 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. Return Value There is no return value. ═══ Example of rewind ═══ /************************************************************************ This example first opens a file myfile.dat 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); return 0; /**************************************************************************** The output should be: The values read back in are: 1 and -37 ****************************************************************************/ } ═══ Related Information ═══ Example of rewind  fgetpos - Get File Position  fseek - Reposition File Position  fsetpos - Set File Position  ftell - Get Current Position  lseek - Move File Pointer  _tell - Get Pointer Position  ═══ 4.240. rmdir - Remove Directory ═══ ═══ Format ═══ #include int rmdir(char *pathname); ═══ Description ═══ Language Level: XPG4, Extension rmdir deletes the directory specified by pathname. The directory must be empty, and it must not be the current working directory or the root directory. Note: In earlier releases of C Set ++, rmdir began with an underscore (_rmdir). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _rmdir to rmdir for you. Return Value rmdir 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:  The given path name is not a directory.  The directory is not empty.  The directory is read only.  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 ═══ /************************************************************************ This example deletes two directories: one in the root directory, and the other 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 (0 == (mkdir(dir1))) 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 (0 == (mkdir(dir2))) 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: 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 ═══ Example of rmdir  chdir - Change Current Working Directory  _getdcwd - Get Full Path Name of Current Directory  _getcwd - Get Path Name of Current Directory  mkdir - Create New Directory  ═══ 4.241. _rmem_init - Initialize Memory Functions for Subsystem DLL ═══ ═══ Format ═══ int _rmem_init(void); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _rmem_init initializes the memory functions for subsystem DLLs. Although subsystems do not require a runtime environment (and therefore do not call _CRT_init), they do require the library memory functions. For DLLs that do use a runtime environment, the memory functions are initialized with the environment by _CRT_init. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn calls _rmem_init for you. However, if you are writing your own subsystem _DLL_InitTerm function (for example, to perform actions other than memory initialization and termination), you must call _rmem_init from your version of _DLL_InitTerm before you can call any other library functions. If your DLL contains C++ code, you must also call __ctordtorInit after _rmem_init to ensure that static constructors and destructors are initialized properly. __ctordtorInit is defined in the runtime startup code as: void __ctordtorInit(void); Return Value If the memory functions were successfully initialized, _rmem_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. ═══ Example of _rmem_init ═══ /************************************************************************ This example shows the _DLL_InitTerm function from the VisualAge C++ sample program for building subsystem DLLs, which calls _rmem_init to initialize the memory functions. ************************************************************************/ #pragma strings( readonly ) /******************************************************************************/ /* */ /* _DLL_InitTerm - Initialization/Termination function for the DLL that is */ /* invoked by the loader. When the /Ge- compile option is */ /* used the linker is told that this is the function to */ /* execute when the DLL is first loaded and last freed for */ /* each process. */ /* */ /* DLLREGISTER - Called by _DLL_InitTerm for each process that loads the */ /* DLL. */ /* */ /* DLLDEREGISTER- Called by _DLL_InitTerm for each process that frees the */ /* DLL. */ /* */ /******************************************************************************/ #define INCL_DOS #define INCL_DOSERRORS #define INCL_NOPMAPI #include #include unsigned long _System _DLL_InitTerm( unsigned long hModule, unsigned long ulFlag ); static unsigned long DLLREGISTER( void ); static unsigned long DLLDEREGISTER( void ); #define SHARED_SEMAPHORE_NAME "\\SEM32\\SAMPLE05\\DLL.LCK" /* The following data will be per-process data. It will not be shared among */ /* different processes. */ static HMTX hmtxSharedSem; /* Shared semaphore */ static ULONG ulProcessTotal; /* Total of increments for a process */ static PID pidProcess; /* Process identifier */ /* This is the global data segment that is shared by every process. */ #pragma data_seg( GLOBAL_SEG ) static ULONG ulProcessCount; /* total number of processes */ /* _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 ) { _rmem_init(); /* 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; _rmem_term(); break; default: return 0; } /* Indicate success. Non-zero means success!!! */ return 1; } /* DLLREGISTER - Registers the current process so that it can use this */ /* subsystem. Called by _DLL_InitTerm when the DLL is first */ /* loaded for the current process. */ static unsigned long DLLREGISTER( void ) { APIRET rc; PTIB ptib; PPIB ppib; /* Get the address of the process and thread information blocks. */ if ( ( rc = DosGetInfoBlocks( &ptib, &ppib ) ) != NO_ERROR ) { printf( "DosGetInfoBlocks rc = %lu\n", rc ); return rc; } /* Open the shared mutex semaphore for this process. */ if ( ( rc = DosOpenMutexSem( SHARED_SEMAPHORE_NAME, &hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosOpenMutexSem rc = %lu\n", rc ); return rc; } /* Acquire the shared mutex semaphore. */ if ( ( rc = DosRequestMutexSem( hmtxSharedSem, SEM_INDEFINITE_WAIT ) ) != NO_ERROR ) { printf( "DosRequestMutexSem rc = %lu\n", rc ); DosCloseMutexSem( hmtxSharedSem ); return rc; } /* Increment the count of processes registered. */ ++ulProcessCount; /* Initialize the per-process data. */ ulProcessTotal = 0; pidProcess = ppib->pib_ulpid; /* Tell the user that the current process has been registered. */ printf( "\nProcess %lu has been registered.\n\n", pidProcess ); /* Release the shared mutex semaphore. */ if ( ( rc = DosReleaseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosReleaseMutexSem rc = %lu\n", rc ); return rc; } return 0; } /* DLLDEREGISTER - Deregisters the current process from this subsystem. */ /* Called by _DLL_InitTerm when the DLL is freed for the */ /* last time by the current process. */ static unsigned long DLLDEREGISTER( void ) { APIRET rc; /* Acquire the shared mutex semaphore. */ if ( ( rc = DosRequestMutexSem( hmtxSharedSem, SEM_INDEFINITE_WAIT ) ) != NO_ERROR ) { printf( "DosRequestMutexSem rc = %lu\n", rc ); return rc; } /* Decrement the count of processes registered. */ --ulProcessCount; /* Tell the user that the current process has been deregistered. */ printf( "\nProcess %lu has been deregistered.\n\n", pidProcess ); /* Release the shared mutex semaphore. */ if ( ( rc = DosReleaseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosReleaseMutexSem rc = %lu\n", rc ); return rc; } /* Close the shared mutex semaphore for this process. */ if ( ( rc = DosCloseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosCloseMutexSem rc = %lu\n", rc ); return rc; } return 0; } ═══ Related Information ═══ Example of _rmem_init  Building Subsystem DLLs in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _CRT_term - Terminate DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.242. _rmem_term - Terminate Memory Functions for Subsystem DLL ═══ ═══ Format ═══ int _rmem_term(void); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _rmem_term terminates the memory functions for subsystem DLLs. It is only needed for DLLs where the runtime library is statically linked. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn calls _rmem_term for you. However, if you are writing your own _DLL_InitTerm function (for example, to perform actions other than memory initialization and termination), and your DLL statically links to the C runtime libraries, you need to call _rmem_term from your subsystem _DLL_InitTerm function. (For DLLs with a runtime environment, this termination is done by _CRT_term.) If your DLL contains C++ code, you must also call __ctordtorTerm before you call _rmem_term to ensure that static constructors and destructors are terminated correctly. __ctordtorTerm is defined in the runtime startup code as: void __ctordtorTerm(void); Once you have called _rmem_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. Return Value _rmem_term returns 0 if the memory functions were successfully terminated. A return value of -1 indicates an error. ═══ Example of _rmem_term ═══ /************************************************************************ This example shows the _DLL_InitTerm function from the VisualAge C++ sample program for building subsystem DLLs, which calls _rmem_term to terminate the library memory functions. ************************************************************************/ #pragma strings( readonly ) /******************************************************************************/ /* */ /* _DLL_InitTerm - Initialization/Termination function for the DLL that is */ /* invoked by the loader. When the /Ge- compile option is */ /* used the linker is told that this is the function to */ /* execute when the DLL is first loaded and last freed for */ /* each process. */ /* */ /* DLLREGISTER - Called by _DLL_InitTerm for each process that loads the */ /* DLL. */ /* */ /* DLLDEREGISTER- Called by _DLL_InitTerm for each process that frees the */ /* DLL. */ /* */ /******************************************************************************/ #define INCL_DOS #define INCL_DOSERRORS #define INCL_NOPMAPI #include #include unsigned long _System _DLL_InitTerm( unsigned long hModule, unsigned long ulFlag ); static unsigned long DLLREGISTER( void ); static unsigned long DLLDEREGISTER( void ); #define SHARED_SEMAPHORE_NAME "\\SEM32\\SAMPLE05\\DLL.LCK" /* The following data will be per-process data. It will not be shared among */ /* different processes. */ static HMTX hmtxSharedSem; /* Shared semaphore */ static ULONG ulProcessTotal; /* Total of increments for a process */ static PID pidProcess; /* Process identifier */ /* This is the global data segment that is shared by every process. */ #pragma data_seg( GLOBAL_SEG ) static ULONG ulProcessCount; /* total number of processes */ /* _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 ) { _rmem_init(); /* 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; _rmem_term(); break; default: return 0; } /* Indicate success. Non-zero means success!!! */ return 1; } /* DLLREGISTER - Registers the current process so that it can use this */ /* subsystem. Called by _DLL_InitTerm when the DLL is first */ /* loaded for the current process. */ static unsigned long DLLREGISTER( void ) { APIRET rc; PTIB ptib; PPIB ppib; /* Get the address of the process and thread information blocks. */ if ( ( rc = DosGetInfoBlocks( &ptib, &ppib ) ) != NO_ERROR ) { printf( "DosGetInfoBlocks rc = %lu\n", rc ); return rc; } /* Open the shared mutex semaphore for this process. */ if ( ( rc = DosOpenMutexSem( SHARED_SEMAPHORE_NAME, &hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosOpenMutexSem rc = %lu\n", rc ); return rc; } /* Acquire the shared mutex semaphore. */ if ( ( rc = DosRequestMutexSem( hmtxSharedSem, SEM_INDEFINITE_WAIT ) ) != NO_ERROR ) { printf( "DosRequestMutexSem rc = %lu\n", rc ); DosCloseMutexSem( hmtxSharedSem ); return rc; } /* Increment the count of processes registered. */ ++ulProcessCount; /* Initialize the per-process data. */ ulProcessTotal = 0; pidProcess = ppib->pib_ulpid; /* Tell the user that the current process has been registered. */ printf( "\nProcess %lu has been registered.\n\n", pidProcess ); /* Release the shared mutex semaphore. */ if ( ( rc = DosReleaseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosReleaseMutexSem rc = %lu\n", rc ); return rc; } return 0; } /* DLLDEREGISTER - Deregisters the current process from this subsystem. */ /* Called by _DLL_InitTerm when the DLL is freed for the */ /* last time by the current process. */ static unsigned long DLLDEREGISTER( void ) { APIRET rc; /* Acquire the shared mutex semaphore. */ if ( ( rc = DosRequestMutexSem( hmtxSharedSem, SEM_INDEFINITE_WAIT ) ) != NO_ERROR ) { printf( "DosRequestMutexSem rc = %lu\n", rc ); return rc; } /* Decrement the count of processes registered. */ --ulProcessCount; /* Tell the user that the current process has been deregistered. */ printf( "\nProcess %lu has been deregistered.\n\n", pidProcess ); /* Release the shared mutex semaphore. */ if ( ( rc = DosReleaseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosReleaseMutexSem rc = %lu\n", rc ); return rc; } /* Close the shared mutex semaphore for this process. */ if ( ( rc = DosCloseMutexSem( hmtxSharedSem ) ) != NO_ERROR ) { printf( "DosCloseMutexSem rc = %lu\n", rc ); return rc; } return 0; } ═══ Related Information ═══ Example of _rmem_term  Building Subsystem DLLs in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _CRT_term - Terminate DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.243. _rmtmp - Remove Temporary Files ═══ ═══ Format ═══ #include int _rmtmp(void); ═══ Description ═══ Language Level: Extension _rmtmp closes and deletes all temporary files in all directories that are held open by the calling process. Return Value _rmtmp returns the number of temporary files deleted. ═══ Example of _rmtmp ═══ /************************************************************************ This example uses _rmtmp to remove a number of temporary files. ************************************************************************/ #include int main(void) { int num; FILE *stream; if (NULL == (stream = tmpfile())) printf("Could not open new temporary file\n"); else { num = _rmtmp(); printf("Number of temporary files removed = %d\n", num); } return 0; /**************************************************************************** The output should be: Number of temporary files removed = 1 ****************************************************************************/ } ═══ Related Information ═══ Example of _rmtmp  _flushall - Write Buffers to Files  remove - Delete File  tmpfile - Create Temporary File  tmpnam - Produce Temporary File Name  unlink - Delete File  ═══ 4.244. _rotl - _rotr - Rotate Bits of Unsigned Integer ═══ ═══ Format ═══ #include /* also in */ 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. _rotl rotates to the left, and _rotr to the right. Note: Both _rotl and _rotr are built-in functions, which means they are implemented as inline instructions and have no backing code in the library. For this reason:  You cannot take the address of these functions.  You cannot parenthesize a call to either function. (Parentheses specify a call to the backing code for the function in the runtime library.) Portability Consideration 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. Return Value Both functions return the rotated value. There is no error return. ═══ 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: 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 ═══ Example of _rotl - _rotr  _crotl - _crotr - Rotate Bits of Character Value  _lrotl - _lrotr - Rotate Bits of Unsigned Long Value  _srotl - _srotr - Rotate Bits of Unsigned Short Value  swab - Swap Adjacent Bytes   ═══ 4.245. rpmatch - Test for Yes/No Response Match ═══ ═══ Format ═══ #include int rpmatch(const char *response); ═══ Description ═══ Language Level: POSIX, Extension rpmatch tests whether the string pointed to by response matches either the affirmative or the negative response set by LC_MESSAGES category in the current locale. Return Value rpmatch returns: 1 If the response string matches the affirmative expression. 0 If the response string matches the negative expression. -1 If the response string does not match either the affirmative or the negative expression. ═══ Example of rpmatch ═══ /************************************************************************ This example asks for a reply, and checks the response. ************************************************************************/ #include #include int main(void) { char *response; char buffer[100]; int rc; printf("Enter reply:\n"); response = fgets(buffer, 100, stdin); rc = rpmatch(response); if (rc > 0) printf("Response was affirmative\n"); else if (rc == 0) printf("Response was negative\n"); else printf("Response was neither negative or affirmative\n"); return 0; /**************************************************************************** Assuming you enter : No The output should be : Response was negative ****************************************************************************/ } ═══ Related Information ═══ Example of rpmatch  setlocale - Set Locale  ═══ 4.246. scanf - Read Data ═══ ═══ Format ═══ #include int scanf(const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, ANSI 93, SAA, POSIX, XPG4, Extension scanf 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. The format-string can contain one or more of the following:  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.  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.  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. scanf 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). The fields of the format specification are discussed in scanf Format Specification Fields and scanf Format Specification - Types. 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 %%. scanf 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. Return Value scanf 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. ═══ Related Information ═══ scanf Example 1 scanf Example 2  scanf Format Specification Fields  scanf Format Specification - Types  fscanf - Read Formatted Data  printf - Print Formatted Characters  sscanf - Read Data  Infinity and NaN Support  ═══ 4.246.1. scanf Format Specification Fields ═══ The scanf format specification fields are described below. The type field is described in scan Format Specification - Types. * 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. ═══ 4.246.2. scan Format Specification - Types ═══ 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, │ Floating-point value consisting │ Pointer to FLOAT │ │ f, g" │ of an optional sign (+ or -); a │ │ │ │ series of one or more decimal │ │ │ "E, │ digits possibly containing a │ │ │ G" │ decimal point; and an optional │ │ │ │ exponent (e or E) followed by a │ │ │ │ possibly signed integer value. │ │ ├───────┼───────────────────────────────────┼──────────────────────────────────┤ │ "c" │ Character; white-space charac- │ Pointer to CHAR large enough for │ │ │ ters that are ordinarily skipped │ input field │ │ │ are read when "c" is specified │ │ ├───────┼───────────────────────────────────┼──────────────────────────────────┤ │ "lc" │ Multibyte characters. The multi- │ Pointer to WCHAR_T large enough │ │ │ byte characters are converted to │ for input field │ │ │ wide characters as if by a call │ │ │ │ to mbrtowc. The field width │ │ │ │ specifies the number of wide │ │ │ │ characters matched; if no width │ │ │ │ is specified, one character is │ │ │ │ matched. │ │ ├───────┼───────────────────────────────────┼──────────────────────────────────┤ │ "s" │ String │ Pointer to character array large │ │ │ │ enough for input field plus a │ │ │ │ terminating null character │ │ │ │ ("\0"), which is automatically │ │ │ │ appended │ ├───────┼───────────────────────────────────┼──────────────────────────────────┤ │ "ls" │ Multibyte string. None of the │ Pointer to WCHAR_T array large │ │ │ characters can be single-byte │ enough for the input field and │ │ │ white-space characters (as speci- │ the terminating null wide char- │ │ │ fied by the isspace function). │ acter ("L\0"), which is added │ │ │ Each multibyte character in the │ automatically. │ │ │ sequence is converted to a wide │ │ │ │ character as if by a call to │ │ │ │ mbrtowc. │ │ ├───────┼───────────────────────────────────┼──────────────────────────────────┤ │ "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 │ │ └───────┴───────────────────────────────────┴──────────────────────────────────┘ 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. ═══ scanf Example 1 ═══ /************************************************************************ 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 assigned\n"); else { printf("integer = %d\n", i); printf("real number = %f\n", fp); printf("character = %c\n", c); printf("string = %s\n", s); } return 0; /**************************************************************************** The output should be similar to: Enter an integer, a real number, a character and a string : 12 2.5 a yes integer = 12 real number = 2.500000 character = a string = yes ****************************************************************************/ } ═══ scanf Example 2 ═══ /************************************************************************ 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); } return 0; /**************************************************************************** The output should be similar to: Enter a hexadecimal number or anything else to quit: 0x231 Hexadecimal Number = 231 Decimal Number = 561 0xf5e Hexadecimal Number = f5e Decimal Number = 3934 0x1 Hexadecimal Number = 1 Decimal Number = 1 q ****************************************************************************/ } ═══ 4.247. _searchenv - Search for File ═══ ═══ Format ═══ #include void _searchenv(char *name, char *env_var, char *path); ═══ Description ═══ Language Level: Extension _searchenv 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 fully-qualified file name is copied into the buffer that path points to. You must ensure sufficient space for the constructed file name. If the target file is not found, path contains an empty null-terminated string. Return Value There is no return value. ═══ 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("_searche.c", "DPATH", path_buffer); printf("path: %s\n", path_buffer); return 0; /**************************************************************************** The output should be similar to: path: C:\OS2\cmd.exe path: C:\src\_searche.c ****************************************************************************/ } ═══ Related Information ═══ Example of _searchenv  getenv - Search for Environment Variables  putenv - Modify Environment Variables  ═══ 4.248. setbuf - Control Buffering ═══ ═══ Format ═══ #include void setbuf(FILE *stream, char *buffer); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 setbuf controls 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 include file. The system uses the buffer, which you specify, for input/output buffering instead of the default system-allocated buffer for the given stream. setvbuf is more flexible than setbuf. Note: Under VisualAge C++, streams are fully buffered by default, with the exceptions of stderr, which is line-buffered, and memory files, which are unbuffered. Return Value There is no return value. ═══ Example of setbuf ═══ /************************************************************************ This example opens the file setbuf.dat for writing. It then calls setbuf 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 #define FILENAME "setbuf.dat" int main(void) { char buf[BUFSIZ]; char string[] = "hello world"; FILE *stream; memset(buf, '\0', BUFSIZ); /* initialize buf to null characters */ stream = fopen(FILENAME, "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 output stream */ return 0; /**************************************************************************** The output file should contain: hello world The output should be: hello world ****************************************************************************/ } ═══ Related Information ═══ Example of setbuf  fclose - Close Stream  fflush - Write Buffer to File  _flushall - Write Buffers to Files  fopen - Open Files  setvbuf - Control Buffering  ═══ 4.249. _set_crt_msg_handle - Change Runtime Message Output Destination ═══ ═══ Format ═══ #include int _set_crt_msg_handle(int fh); ═══ Description ═══ Language Level: Extension _set_crt_msg_handle 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. Return Value _set_crt_msg_handle 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 ═══ /************************************************************************ This example causes an exception by dereferencing a null pointer and uses _set_crt_msg_handle to send the exception messages to the file _scmhdl.out. ************************************************************************/ #include #include #include #include #include int main(void) { int fh; char *p = NULL; if (-1 == (fh = open("_scmhdl.out", O_CREAT|O_TRUNC|O_RDWR, S_IREAD|S_IWRITE))) { perror("Unable to open the file _scmhdl.out."); exit(EXIT_FAILURE); } /* change file handle where messages are sent */ if (fh != _set_crt_msg_handle(fh)) { perror("Could not change massage output handle."); exit(EXIT_FAILURE); } *p = 'x'; /* cause an exception, output should be in _scmhdl.out */ if (-1 == close(fh)) { perror("Unable to close _scmhdl.out."); exit(EXIT_FAILURE); } return 0; /**************************************************************************** Running this program would cause an exception to occur, the file _scmhdl.out should contain the exception messages similar to : Exception = c0000005 occurred at EIP = 10068. ****************************************************************************/ } ═══ Related Information ═══ Example of _set_crt_msg_handle  open - Open File  fileno - Determine File Handle  _sopen - Open Shared File  ═══ 4.250. setjmp - Preserve Environment ═══ ═══ Format ═══ #include int setjmp(jmp_buf env); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 setjmp saves a stack environment that can subsequently be restored by longjmp. setjmp and longjmp 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 variables that are allocated to registers by the compiler are unpredictable. Because any auto variable could be allocated to a register in optimized code, you should consider the values of all auto variables to be unpredictable after a longjmp call. C++ Considerations When you call setjmp in a C++ program, ensure that that part of the program does not also create C++ objects that need to be destroyed. When you call longjmp, objects existing at the time of the setjmp call will still exist, but any destructors called after setjmp are not called. Click here for an example. Return Value setjmp 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 error return value. ═══ 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 #include jmp_buf mark; void p(void) { int error = 0; error = 9; if (error != 0) longjmp(mark, -1); } void recover(void) { } int main(void) { if (setjmp(mark) != 0) { printf("longjmp has been called\n"); recover(); return 0; } printf("setjmp has been called\n"); p(); return 0; /**************************************************************************** The output should be: setjmp has been called longjmp has been called ****************************************************************************/ } ═══ Related Information ═══ Example of setjmp  longjmp - Restore Stack Environment  goto in the Language Reference  ═══ 4.251. setlocale - Set Locale ═══ ═══ Format ═══ #include char *setlocale(int category, const char *locale); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 setlocale sets or queries the specified category of the program's locale. A locale is the complete definition of that part of a program that depends on language and cultural conventions. The default VisualAge C++ locale is the POSIX C locale definition, represented as "C" or "POSIX". This locale is standard for all ANSI-conforming and POSIX-conforming compilers. You can accept the default, or you can use setlocale to set the locale to one of the supplied locales listed in "Introduction to Locale" in the Programming Guide. Some examples of the supplied locales as you would specify them for setlocale are: "En_GB.IBM-850" (English, Great Britain, code page 850) "Fr_CA.IBM-863" (French, Canada, code page 863) "Ja_JP.IBM-932" (Japanese, Japan, code page 932) Note: 1. If you are already using the code page for one of these locales, you can specify the locale name without the code page. For example, if you are using code page 850, you can specify "En_GB" for the English Great Britain locale. 2. In earlier versions of C Set ++, you could also specify locales using the macros LC_C, LC_C_GERMANY, LC_C_FRANCE, LC_C_SPAIN, LC_C_ITALY, LC_C_JAPAN, LC_C_USA, or LC_C_UK. These macros are provided only for compatibility with earlier releases; you can still use these macros, but the locales they specify are not POSIX locales. The result of setlocale depends on the arguments you specify:  To set a category to a specific locale, specify both the category and locale names. For example: setlocale(LC_CTYPE, "POSIX"); sets the LC_CTYPE category according to the "POSIX" locale. The category names and their purpose are described in Locale Categories for setlocale If you specify a null string ("") for locale, setlocale checks locale-related environment variables in the program's environment to find a locale name or names to use for category. If category is not LC_ALL, setlocale gets the locale name from: 1. LC_ALL, if it is defined and not null 2. The environment variable with the same name as category, if it is defined and not null 3. LANG, if it is defined and not null 4. If none of these variables is defined to a valid locale name, setlocale uses the "C" locale. For example, if the LC_ALL environment variable is set to "GERM" (Germany locale): setlocale(LC_TIME, ""); sets the LC_TIME category to the "GERM" locale. If category is LC_ALL and locale is a null string, setlocale checks the environment variables in the same order listed above. However, it checks the variable for each category and sets the category to the locale specified, which could be different for each category. (By contrast, if you specified LC_ALL and a specific locale name, all categories would be set to the same locale that you specify.) The string returned lists all the locales for all the categories.  To query the locale for a category, specify a null pointer for locale. setlocale then returns a string indicating the locale setting for that category, without changing it. For example: char *s = setlocale(LC_CTYPE, NULL); returns the current locale for the LC_CTYPE category. Return Value: setlocale returns a string that specifies the locale for the category. If you specified "" for locale, the string names the current locale; otherwise, it indicates the new locale that the category was set to. If you specified LC_ALL for category, the returned string can be either a single locale name or, if the individual categories have different locales, a list of the locale names for each category in the following order: 1. LC_COLLATE 2. LC_CTYPE 3. LC_MONETARY 4. LC_NUMERIC 5. LC_TIME 6. LC_TOD 7. LC_MESSAGES 8. LC_SYNTAX The string can be used on a subsequent call to restore that part of the program's locale. Because the returned string can be overwritten by subsequent calls to setlocale, you should copy the string if you plan to use it later. If an error occurs, setlocale returns NULL and does not alter the program's locale. Errors can occur if the category or locale is not valid, or if the value of the environment variable for a category does not contain a valid locale. ═══ Example 1 of setlocale ═══ /************************************************************************ This example sets the locale of the program to be "fr_fr.ibm-850" and prints the string that is associated with the locale. ************************************************************************/ #include #include int main(void) { char *string; if (NULL == (string = setlocale(LC_ALL, "fr_fr.ibm-850"))) printf("setlocale failed.\n"); else printf("The current locale is set to %s.\n", string); return 0; /**************************************************************************** The output should be similar to : The current locale is set to fr_fr.ibm-850. ****************************************************************************/ } ═══ Example 2 of setlocale ═══ /************************************************************************ This example uses setenv to set the value of the environment variable LC_TIME to FRAN, calls setlocale to set all categories to default values, then query all categories, and uses printf to print results. ************************************************************************/ #include #include int main(void) { char *string; _putenv("LC_TIME=FRAN"); if (NULL == (string = setlocale(LC_ALL, ""))) printf("setlocale failed.\n"); else printf("The current locale categories are: \"%s\"\n", string); return 0; /**************************************************************************** The output should be similar to : The current locale categories are: "C,C,C,C,FRAN,C,C,C" ****************************************************************************/ } ═══ Related Information ═══ setlocale Example 1 setlocale Example 2  Locale Categories for setlocale  "Introduction to Locale" in the Programming Guide  getenv - Search for Environment Variables  localeconv - Retrieve Information from the Environment  ═══ 4.251.1. Locale Categories for setlocale ═══ You can set the category argument of setlocale to one of these values: Category Purpose LC_ALL Specifies all categories associated with the program's locale. LC_COLLATE Defines the collation sequence, that is, the relative order of collation elements (characters and multicharacter collation elements) in the program's locale. The collation sequence definition is used by regular expression, pattern matching, and sorting functions. Affects the regular expression functions regcomp and regexec; the string functions strcoll, strxfrm, wcscoll, and wcsxfrm; and the collating functions collequiv, collorder, collrange, colltostr, ismccollel, maxcoll, and strtocoll. Note: Because both LC_CTYPE and LC_COLLATE modify the same storage area, setting LC_CTYPE and LC_COLLATE to different categories causes unpredictable results. LC_CTYPE Defines character classification and case conversion for characters in the program's locale. Affects the behavior of character-handling functions defined in the header file: csid, isalnum, isalpha, isblank, iswblank iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, iswalnum, iswalpha, iswcntrl, iswctype, iswdigit, iswgraph, iswlower, iswprint, iswpunct, iswspace, iswupper, iswxdigit, isxdigit, tolower, toupper, towlower, towupper, wcsid, and wctype. Affects behavior of the printf and scanf families of functions: fprintf, printf, sprintf, swprintf, vfprintf, vprintf, vsprintf, vswprintf; fscanf, scanf, sscanf, and swscanf. Affects the behavior of wide character input/output functions: fgetwc, fgetws, getwc, getwchar, fputwc, fputws, putwc, putwchar, and ungetwc. Affects the behavior of multibyte and wide character conversion functions: mblen, mbrlen, mbrtowc, mbsrtowcs, mbstowcs, mbtowc, wcrtomb, wcsrtombs, wcstod, wcstol, wcstombs, wcstoul, wcswidth, wctomb, and wcwidth. Note: Because both LC_CTYPE and LC_COLLATE modify the same storage area, setting LC_CTYPE and LC_COLLATE to different categories causes unpredictable results. LC_MESSAGES Under VisualAge C++, affects the values returned by nl_langinfo and also defines affirmative and negative response patterns, which affect rpmatch. LC_MESSAGES does not affect the messages for the following functions: perror, strerror, _strerror, and regerror. LC_MONETARY Affects monetary information returned by localeconv and strfmon. It defines the rules and symbols used to format monetary numeric information in the program's locale. The formatting rules and symbols are strings. localeconv returns pointers to these strings with names found in the header file. 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, specifically:  printf family of functions  scanf family of functions  strtod  atof. LC_TIME Defines time and date format information in the program's locale, affecting the strftime strptime, and wcsftime functions. LC_SYNTAX Affects the values that can be retrieved by the getsyntx function. It does not affect the behavior of functions that are dependent on the encoded values for formatting characters, as it may do on other platforms. LC_TOD Affects the behavior of the functions related to time zone and Daylight Savings Time information in the program's locale. ctime, localtime, mktime, setlocale, and strftime call the tzset function to override the LC_TOD category information when TZ is defined and valid. ═══ 4.252. _setmode - Set File Translation Mode ═══ ═══ Format ═══ #include #include int _setmode(int handle, int mode); ═══ Description ═══ Language Level: Extension _setmode 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 _setmode to change the translation mode of a file handle. The translation mode only affects the read and write functions. _setmode 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, you should call _setmode for that file handle before using it within the read or write functions. Return Value _setmode 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 ═══ /************************************************************************ 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(int rc) { if (-1 == rc) { printf("Unexpected return code = -1\n"); remove(FILENAME); exit(EXIT_FAILURE); } } 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 (O_TEXT == mode) 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 output should be: Read in 4 characters (4 expected) Mode changed from binary to text Read in 5 characters (5 expected) ****************************************************************************/ } ═══ Related Information ═══ Example of _setmode  creat - Create New File  open - Open File  _sopen - Open Shared File  read - Read Into Buffer  write - Writes from Buffer to File     ═══ 4.253. setvbuf - Control Buffering ═══ ═══ Format ═══ #include int setvbuf(FILE *stream, char *buf, int type, size_t size); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 setvbuf 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. The type must be one of the following: 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. If type is _IOFBF or _IOLBF, size is the size of the supplied buffer. If buf is NULL, the C library takes size as the suggested size for its own buffer. If type is _IONBF, both buf and size are ignored. The value for size must be greater than 0. Return Value setvbuf returns 0 if successful. It returns 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 ═══ /************************************************************************ This example sets up a buffer of buf for stream1 and specifies that input to stream2 is to be unbuffered. ************************************************************************/ #include #include #define BUF_SIZE 1024 #define FILE1 "setvbuf1.dat" #define FILE2 "setvbuf2.dat" char buf[BUF_SIZE]; FILE *stream1,*stream2; int main(void) { int flag = EXIT_SUCCESS; stream1 = fopen(FILE1, "r"); stream2 = fopen(FILE2, "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"); flag = EXIT_FAILURE; } /* stream2 is unbuffered */ if (setvbuf(stream2, NULL, _IONBF, 0) != 0) { printf("Incorrect type or size of buffer\n"); flag = EXIT_FAILURE; } fclose(stream1); fclose(stream2); return flag; } ═══ Related Information ═══ Example of setvbuf  fclose - Close Stream  fflush - Write Buffer to File  _flushall - Write Buffers to Files  fopen - Open Files  setbuf - Control Buffering  ═══ 4.254. signal - Handle Interrupt Signals ═══ ═══ Format ═══ #include void ( *signal(int sig, void (*sig_handler)(int)) )(int); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension signal function assigns the signal handler sig_handler to handle the interrupt signal sig. 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 argument must be one of the signal constants defined in : Value Meaning SIGABRT Abnormal termination signal sent by abort. Default action: end the program. SIGBREAK Ctrl-Break signal. Default action: end the program. SIGFPE Floating-point exceptions that are not masked, such as overflow, division by zero, and invalid operation. Default action: end the program and provide an error message. If machine-state dumps are enabled (with the /Tx compiler option), a dump is also provided. SIGILL Instruction not allowed. Default action: end the program and provide an error message. If machine-state dumps are enabled (with the /Tx compiler option), a dump is also provided. SIGINT Ctrl-C signal. Default action: end the program. SIGSEGV Access to memory not valid. Default action: end the program and provide an error message. If machine-state dumps are enabled (with the /Tx compiler option), a dump is also provided. SIGTERM Program termination signal sent by the user. Default action: end the program. SIGUSR1 Defined by the user. Default action: ignore the signal. SIGUSR2 Defined by the user. Default action: ignore the signal. SIGUSR3 Defined by the user. Default action: ignore the signal. For sig_handler, you must specify 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 Perform the default action. This is the initial setting for all signals. The default actions are described in the list of signals above. All files controlled by the process are closed, but buffers are not flushed. SIG_IGN Ignore the interrupt signal. sig_handler Call the function sig_handler, which you provide, to handle the signal specified. Your signal handler function (sig_handler) must take two integer arguments. The first argument is always the signal identifier. The second argument 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 your sig_handler returns, the calling process resumes running immediately following the point at which it received the interrupt signal. After a signal is reported and the sig_handler is called, signal handling for that signal is reset to the default. Depending on the purpose of the signal handler, you may want to call signal inside sig_handler to reestablish sig_handler as the signal handler. You can also reset the default handling at any time by calling signal and specifying SIG_DFL. Signals and signal handlers are not shared between threads. If you do not establish a handler for a specific signal within a thread, the default signal handling is 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 VisualAge C++ exception handler. Your sig_handler will not be called. For more information about signals and exceptions, refer to Signal and OS/2 Exception Handling in the Programming Guide. Return Value All calls to signal 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 sig_handler. ═══ 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. The handler prints a message and returns to the system. ************************************************************************/ #define INCL_DOSFILEMGR #include #include #include #include #include void handler(int sig) { UCHAR FileData[100]; ULONG Wrote; strcpy(FileData, "Signal occurred.\n\r"); DosWrite(2, (PVOID)FileData, strlen(FileData), &Wrote); } int main(void) { if (SIG_ERR == signal(SIGABRT, handler)) { perror("Could not set SIGABRT"); return EXIT_FAILURE; } abort(); /* signal raised by abort */ return 0; /* code should not reach here */ /**************************************************************************** The output should be: Signal occurred. ****************************************************************************/ } ═══ Related Information ═══ Example of signal  abort - Stop a Program  atexit - Record Program Termination Function  exit - End Program  _exit - End Process  _fpreset - Reset Floating-Point Unit  raise - Send Signal  _spawnl - _spawnvpe - Start and Run Child Processes  Signal and OS/2 Exception Handling in the Programming Guide  ═══ 4.255. sin - Calculate Sine ═══ ═══ Format ═══ #include double sin(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 sin calculates the sine of x, with x expressed in radians. If x is too large, a partial loss of significance in the result may occur. Return Value sin returns the value of the sine of x. ═══ Example of sin ═══ /************************************************************************ This example computes y as the sine of pi/2. ************************************************************************/ #include int main(void) { double pi,x,y; pi = 3.1415926535; x = pi/2; y = sin(x); printf("sin( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be: sin( 1.570796 ) = 1.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of sin  asin - Calculate Arcsine  cos - Calculate Cosine  _fasin - Calculate Arcsine  _fcossin - Calculate Cosine and Sine  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  ═══ 4.256. sinh - Calculate Hyperbolic Sine ═══ ═══ Format ═══ #include double sinh(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 sinh calculates the hyperbolic sine of x, with x expressed in radians. Return Value sinh returns the value of the hyperbolic sine of x. 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 ═══ /************************************************************************ This example computes y as the hyperbolic sine of pi/2. ************************************************************************/ #include int main(void) { double pi,x,y; pi = 3.1415926535; x = pi/2; y = sinh(x); printf("sinh( %lf ) = %lf\n", x, y); return 0; /**************************************************************************** The output should be: sinh( 1.570796 ) = 2.301299 ****************************************************************************/ } ═══ Related Information ═══ Example of sinh  asin - Calculate Arcsine  cosh - Calculate Hyperbolic Cosine  _fasin - Calculate Arcsine  _fcossin - Calculate Cosine and Sine  _fsin - Calculate Sine  _fsincos - Calculate Sine and Cosine  sin - Calculate Sine  tanh - Calculate Hyperbolic Tangent  ═══ 4.257. _sopen - Open Shared File ═══ ═══ Format ═══ #include #include #include #include int _sopen(char *pathname, int oflag, int shflag , int pmode); ═══ Description ═══ Language Level: Extension _sopen 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. O_TEXT Open the file in text (translated) mode. (See "Stream Processing" in the Programming Guide for a description of text and binary 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 required only when you specify O_CREAT. 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 value of pmode is ignored. The pmode must be one of the following values, defined in : 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. _sopen 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.) _sopen 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 at attempt was made to open if for writing, 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 ═══ /************************************************************************ This example opens the file sopen.dat for shared reading and writing using _sopen. It then opens the file for shared reading. ************************************************************************/ #include #include #include #include #include #define FILENAME "sopen.dat" int main(void) { int fh1,fh2; printf("Creating file.\n"); system("echo Sample Program > " FILENAME); /* share open the file for reading and writing */ if (-1 == (fh1 = _sopen(FILENAME, O_RDWR, SH_DENYNO))) { perror("sopen failed"); remove(FILENAME); return EXIT_FAILURE; } /* share open the file for reading only */ if (-1 == (fh2 = _sopen(FILENAME, O_RDONLY, SH_DENYNO))) { perror("sopen failed"); close(fh1); remove(FILENAME); return EXIT_FAILURE; } printf("File successfully opened for sharing.\n"); close(fh1); close(fh2); remove(FILENAME); return 0; /**************************************************************************** The output should be: Creating file. File successfully opened for sharing. ****************************************************************************/ } ═══ Related Information ═══ Example of _sopen  close - Close File Associated with Handle  creat - Create New File  open - Open File  fdopen - Associates Input Or Output With File  fopen - Open Files  _sopen - Open Shared File  umask - Sets File Mask of Current Process     ═══ 4.258. _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 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 functions 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, a NULL pointer must 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. Return Value The return from a spawn function 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 wait or _cwait 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 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 ═══ /************************************************************************ This example calls 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 process to run, and then spawns a second child process. The instructions for the child process are blocked to run only if argv[0] and one parameter were passed (case CHILD). In its turn, each child process spawns a grandchild as a copy of the same program. The grandchild instructions are blocked by the existence of two passed parameters. The grandchild process can overlay the child process. 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 ('o' == *argv[1]) /* child one? */ { _spawnl(P_OVERLAY, argv[0], argv[0], "one", "two", NULL); abort(); /* not executed because child was overlaid */ } if ('t' == *argv[1]) /* 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: child process one began grandchild one ran child process two began grandchild two ran Parent process ended ****************************************************************************/ } ═══ Related Information ═══ Example of _spawnl - _spawnvpe  abort - Stop a Program  _cwait - Wait for Child Process  execl - _execvpe - Load and Run Child Process  exit - End Program  _exit - End Process  wait - Wait for Child Process  ═══ 4.259. _splitpath - Decompose Path Name ═══ ═══ Format ═══ #include void _splitpath(char *path, char *drive, char *dir, char *fname, char *ext); ═══ Description ═══ Language Level: Extension _splitpath 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 (.). You can specify NULL for any of the buffer pointers to indicate that you do not want the string for that component returned. The return parameters contain empty strings for any path name components not found in path. Return Value There is no return value. ═══ 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: 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 ═══ Example of _splitpath  _fullpath - Get Full Path Name of Partial Path  _getcwd - Get Path Name of Current Directory  _getdcwd - Get Full Path Name of Current Directory  _makepath - Create Path  ═══ 4.260. sprintf - Print Formatted Data to Buffer ═══ ═══ Format ═══ #include int sprintf(char *buffer, const char *format-string, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension sprintf 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. If you specify a null string for the %s or %ls format specifier, sprintf prints (null). (In previous releases of C Set ++, sprintf produced no output for a null string.) Return Value sprintf returns the number of bytes written in the array, not counting the ending null character. ═══ Example of sprintf ═══ /************************************************************************ This 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); return 0; /**************************************************************************** The output should be: string: baltimore l 35 1.732051 character count = 24 ****************************************************************************/ } ═══ Related Information ═══ Example of sprintf  Infinity and NaN Support  _cprintf - Print Characters to Screen  fprintf - Write Formatted Data to a Stream  printf - Print Formatted Characters  sscanf - Read Data  swprintf - Format and Write Wide Characters to Buffer  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer  ═══ 4.261. sqrt - Calculate Square Root ═══ ═══ Format ═══ #include double sqrt(double x); ═══ Description ═══ Language Level: ANSI, SAA SAA, POSIX, XPG4 sqrt calculates the nonnegative value of the square root of x. Return Value sqrt returns the square root result. If x is negative, the function sets errno to EDOM, and returns 0. ═══ 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) { double value = 45.0; printf("sqrt( %f ) = %f\n", value, sqrt(value)); return 0; /**************************************************************************** The output should be: sqrt( 45.000000 ) = 6.708204 ****************************************************************************/ } ═══ Related Information ═══ Example of sqrt  exp - Calculate Exponential Function  _fsqrt - Calculate Square Root  hypot - Calculate Hypotenuse  log - Calculate Natural Logarithm  log10 - Calculate Base 10 Logarithm  pow - Compute Power  ═══ 4.262. srand - Set Seed for rand Function ═══ ═══ Format ═══ #include void srand(unsigned int seed); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 srand 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) were 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. Return Value There is no return value. ═══ Example of srand ═══ /************************************************************************ This example first calls srand with a value other than 1 to initiate the random value sequence. Then the program computes five 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]); } return 0; /**************************************************************************** The 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 ═══ Example of srand  rand - Generate Random Number  ═══ 4.263. _srotl - _srotr - Rotate Bits of Unsigned Short Value ═══ ═══ Format ═══ #include /* also in */ unsigned short _srotl(unsigned short value, int shift); unsigned short _srotr(unsigned short value, int shift); ═══ Description ═══ Language Level: Extension The _srotl and _srotr functions rotate the unsigned short integer value by shift bits. The _srotl function rotates to the left, and _srotr to the right. Note: Both _srotl and _srotr are built-in functions, which means they are implemented as inline instructions and have no backing code in the library. For this reason:  You cannot take the address of these functions.  You cannot parenthesize a call to either function. (Parentheses specify a call to the function's backing code, and these functions have none.) Return Value Both functions return the rotated value. There is no error return value. ═══ Example of _srotl - _srotr ═══ /************************************************************************ * This example uses _srotl and _srotr with different shift values to rotate the character value: * ************************************************************************/ #include #include int main(void) { unsigned short val = 0X0123; printf("The value of 0x%4.4x rotated 4 bits to the left is 0x%4.4x\n", val, _srotl(val, 4)); printf("The value of 0x%4.4x rotated 8 bits to the right is 0x%4.4x\n", val, _srotr(val, 8)); return 0; /**************************************************************************** The output should be: The value of 0x0123 rotated 4 bits to the left is 0x1230 The value of 0x0123 rotated 8 bits to the right is 0x2301 ****************************************************************************/ } ═══ Related Information ═══ Example  _crotl - _crotr - Rotate Bits of Character Value  _lrotl - _lrotr - Rotate Bits of Unsigned Long Value  _rotl - _rotr - Rotate Bits of Unsigned Integer   ═══ 4.264. sscanf - Read Data ═══ ═══ Format ═══ #include int sscanf(const char *buffer, const char *format, argument-list); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4, Extension sscanf 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. In extended mode, sscanf 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. Return Value sscanf 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 when the end of the string is encountered before anything is converted. ═══ Example of sscanf ═══ /************************************************************************ This example uses sscanf to read various data from the string tokenstring, and then displays that 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); return 0; /**************************************************************************** The output should be: string = 15 character = 1 integer = 2 floating-point number = 14.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of sscanf  Infinity and NaN Support  _cscanf - Read Data from Keyboard  fscanf - Read Formatted Data  scanf - Read Data  sprintf - Print Formatted Data to Buffer  swscanf - Read Wide Characters from Buffer  ═══ 4.265. stat - Get Information about File or Directory ═══ ═══ Format ═══ #include #include int stat(const char *pathname, struct stat *buffer) ; ═══ Description ═══ Language Level: XPG4, Extension stat 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. stat 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. 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 access of file. st_mtime Time of last modification of file. st_ctime Time of file creation. 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. Note: In earlier releases of C Set ++, stat began with an underscore (_stat). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _stat to stat for you. Return Value stat 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 ═══ /************************************************************************ 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 (0 == stat("test.exe", &buf)) { 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 is: #include int main(void) { puts("test.exe is an executable file"); } The output should be: test.exe is an executable file ****************************************************************************/ } ═══ Related Information ═══ Example of stat  fstat - Information about Open File   ═══ 4.266. _status87 - Get Floating-Point Status Word ═══ ═══ Format ═══ #include /* also in */ unsigned int _status87(void); ═══ Description ═══ Language Level: Extension _status87 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. Return Value The bits in the value returned reflect the floating-point status for the current thread only before the call was made. _status87 does not affect any other threads that may be processing. ═══ 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 output should be: status = 0x0000 - clear status = 0x0030 - inexact, underflow status = 0x0002 - denormal ****************************************************************************/ } ═══ Related Information ═══ Example of _status87  _clear87 - Clear Floating-Point Status Word  _control87 - Set Floating-Point Control Word  _fpreset - Reset Floating-Point Unit  ═══ 4.267. strcat - Concatenate Strings ═══ ═══ Format ═══ #include char *strcat(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strcat concatenates string2 to string1 and ends the resulting string with the null character. strcat 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. If the storage of string1 overlaps the storage of string2, the behavior is undefined. Return Value strcat returns a pointer to the concatenated string (string1). ═══ 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); return 0; /**************************************************************************** The output should be: buffer1 = computer program ****************************************************************************/ } ═══ Related Information ═══ Example of strcat  strchr - Search for Character  strcmp - Compare Strings  strcpy - Copy Strings  strcspn - Compare Strings for Substrings  strncat - Concatenate Strings  wcscat - Concatenate Wide-Character Strings  wcsncat - Concatenate Wide-Character Strings  ═══ 4.268. strchr - Search for Character ═══ ═══ Format ═══ #include char *strchr(const char *string, int c); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strchr 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. Return Value strchr returns a pointer to the first occurrence of c converted to a character in string. The function returns NULL if the specified character is not found. ═══ 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); return 0; /**************************************************************************** The output should be: The first occurrence of p in 'computer program' is 'puter program' ****************************************************************************/ } ═══ Related Information ═══ Example of strchr  strcmp - Compare Strings  strcspn - Compare Strings for Substrings  strncmp - Compare Strings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcsspn - Search Wide-Character Strings  ═══ 4.269. strcmp - Compare Strings ═══ ═══ Format ═══ #include int strcmp(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strcmp 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. Return Value strcmp 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 ═══ /************************************************************************ 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 (0 == result) 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]); } return 0; /**************************************************************************** If the following arguments are passed to this program: "is this first?" "is this before that one?" The output should be: "is this first?" is greater than "is this before that one?" ****************************************************************************/ } ═══ Related Information ═══ Example of strcmp  strcmpi - Compare Strings Without Case Sensitivity  strcoll - Compare Strings Using Collation Rules  strcspn - Compare Strings for Substrings  stricmp - Compare Strings as Lowercase  strncmp - Compare Strings  strnicmp - Compare Strings Without Case Sensitivity  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.270. strcmpi - Compare Strings Without Case Sensitivity ═══ ═══ Format ═══ #include int strcmpi(const char *string1, const char *string2); ═══ Description ═══ Language Level: Extension strcmpi 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. Return Value strcmpi 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 ═══ /************************************************************************ 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: The strings are equivalent. ****************************************************************************/ } ═══ Related Information ═══ Example of strcmpi  strcoll - Compare Strings Using Collation Rules  strcspn - Compare Strings for Substrings  strdup - Duplicate String  stricmp - Compare Strings as Lowercase  strncmp - Compare Strings  strnicmp - Compare Strings Without Case Sensitivity  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.271. strcoll - Compare Strings Using Collation Rules ═══ ═══ Format ═══ #include int strcoll(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 strcoll compares the string pointed to by string1 against the string pointed to by string2, both interpreted according to the information in the LC_COLLATE category of the current locale. strcoll differs from the strcmp function. strcoll performs a comparison between two character strings based on language collation rules as controlled by the LC_COLLATE category. In contrast, strcmp performs a character to character comparison. Return Value strcoll returns an integer value indicating the relationship between the strings, as listed below: Value Meaning Less than 0 string1 is less than string2 0 string1 is equivalent to string2 Greater than 0 string1 is greater than string2 Note: 1. strcoll might need to allocate additional memory to perform the comparison algorithm specified in the LC_COLLATE. If the memory request cannot be satisfied (by malloc), then strcoll fails. 2. If the locale supports double-byte characters (MB_CUR_MAX specified as 2), strcoll validates the multibyte characters. (Previously, strcoll did not validate the string.) strcoll will fail if the string contains invalid multibyte characters. 3. If MB_CUR_MAX is specified as 2, but the charmap file does not specify the DBCS characters, the DBCS characters will collate after the single-byte characters. ═══ 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 (0 == result) 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]); } return 0; /**************************************************************************** If the program is passed the following arguments: "firststring" "secondstring" The output should be: "firststring" is less than "secondstring" ****************************************************************************/ } ═══ Related Information ═══ Example of strcoll  setlocale - Set Locale  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  strncmp - Compare Strings  wcscoll - Compare Wide-Character Strings  ═══ 4.272. strcpy - Copy Strings ═══ ═══ Format ═══ #include char *strcpy(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strcpy copies string2, including the ending null character, to the location specified by string1. strcpy 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. Return Value strcpy returns a pointer to the copied string (string1.). ═══ Example of strcpy ═══ /************************************************************************ This example copies the contents of source to destination. ************************************************************************/ #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); return 0; /**************************************************************************** The output should be: destination is originally = 'abcdefg' After strcpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After strncpy, destination1 becomes '12345fg' ****************************************************************************/ } ═══ Related Information ═══ Example of strcpy  strcat - Concatenate Strings  strdup - Duplicate String  strncpy - Copy Strings  wcscpy - Copy Wide-Character Strings  wcsncpy - Copy Wide-Character Strings  ═══ 4.273. strcspn - Compare Strings for Substrings ═══ ═══ Format ═══ #include size_t strcspn(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strcspn 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. Return Value strcspn 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be: The first 10 characters in the string "This is the source string" are not in the string "axle" ****************************************************************************/ } ═══ Related Information ═══ Example of strcspn  strchr - Search for Character  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  stricmp - Compare Strings as Lowercase  strncmp - Compare Strings  strnicmp - Compare Strings Without Case Sensitivity  strpbrk - Find Characters in String  strspn - Search Strings  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.274. _strdate - Copy Current Date ═══ ═══ Format ═══ #include char *_strdate(char *date); ═══ Description ═══ Language Level: Extension _strdate 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. Return Value _strdate returns a pointer to the buffer containing the date string. There is no error return. ═══ 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 01/02/95 ****************************************************************************/ } ═══ Related Information ═══ Example of _strdate  asctime - Convert Time to Character String  ctime - Convert Time to Character String  _ftime - Store Current Time  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  time - Determine Current Time  tzset - Assign Values to Locale Information  ═══ 4.275. strdup - Duplicate String ═══ ═══ Format ═══ #include char *strdup(const char *string); ═══ Description ═══ Language Level: XPG2, Extension strdup 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. Remember to free the storage reserved with the call to strdup. Return Value strdup returns a pointer to the storage space containing the copied string. If it cannot reserve storage strdup returns NULL. ═══ 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 string */ if ((newstr = strdup(string)) != NULL) printf("The new string is: %s\n", newstr); return 0; /**************************************************************************** The output should be: The new string is: this is a copy ****************************************************************************/ } ═══ Related Information ═══ Example of strdup  strcpy - Copy Strings  strncpy - Copy Strings  wcscpy - Copy Wide-Character Strings  wcsncpy - Copy Wide-Character Strings  ═══ 4.276. strerror - Set Pointer to Runtime Error Message ═══ ═══ Format ═══ #include char *strerror(int errnum); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 strerror maps the error number in errnum to an error message string. Return Value strerror returns a pointer to the string. It does not use the program locale in any way. The value of errno may be set to: EILSEQ An encoding error has occurred converting a multibyte character. E2BIG The output buffer is too small. ═══ Example of strerror ═══ /************************************************************************ This example opens a file and prints a runtime error message if an error occurs. ************************************************************************/ #include #include #include #define FILENAME "strerror.dat" int main(void) { FILE *stream; if (NULL == (stream = fopen(FILENAME, "r"))) printf(" %s \n", strerror(errno)); return 0; } ═══ Related Information ═══ Example of strerror  clearerr - Reset Error Indicators.  ferror - Test for Read/Write Errors  perror - Print Error Message  _strerror - Set Pointer to System Error String  ═══ 4.277. _strerror - Set Pointer to System Error String ═══ ═══ Format ═══ #include char *_strerror(char *string); ═══ Description ═══ Language Level: Extension _strerror 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. Return 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:  Your string message  A colon  A space  The system error message for the last library call producing an error  A new-line character (\n). ═══ Example of _strerror ═══ /************************************************************************ This example shows how _strerror can be used with the fopen function. ************************************************************************/ #include #include #define INFILE "_strerro.in" #define OUTFILE "_strerro.out" int main(void) { FILE *fh1,*fh2; fh1 = fopen(INFILE, "r"); if (NULL == fh1) /* the error message goes through stdout not stderr */ printf(_strerror("Open failed on input file")); fh2 = fopen(OUTFILE, "w+"); if (NULL == fh2) 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); remove(OUTFILE); return 0; /**************************************************************************** The output should be: Open failed on input file: The file cannot be found. Open on output file was successful. ****************************************************************************/ } ═══ Related Information ═══ Example of _strerror  clearerr - Reset Error Indicators.  ferror - Test for Read/Write Errors  perror - Print Error Message  strerror - Set Pointer to Runtime Error Message  ═══ 4.278. strfmon - Convert Monetary Value to String ═══ ═══ Format ═══ #include int strfmon(char *s, size_t maxsize, const char *format, ...); ═══ Description ═══ Language Level: XPG4 strfmon places characters into the array pointed to by *s, as controlled by the string pointed to by format. No more than maxsize characters are placed into the array. The character string format contains two types of objects:  Plain characters, which are copied to the output array.  Directives, each of which results in the fetching of zero or more arguments that are converted and formatted. The results are undefined if there are insufficient arguments for the format. If the format is exhausted while arguments remain, the excess arguments are simply ignored. If objects pointed to by s and format overlap, the behavior is undefined. The directive (conversion specification) consists of the following sequence. 1. A % character 2. Optional flags, described below: =f, ^, then +, C, (, then ! 3. Optional field width (may be preceded by -) 4. Optional left precision: #n 5. Optional right precision: .p 6. Required conversion character to indicate what conversion should be performed: i or n. Each directive is replaced by the appropriate characters, as described in the following list: %i The double argument is formatted according to the locale's international currency format (for example, in USA: USD 1,234.56). %n The double argument is formatted according to the locale's national currency format (for example, in USA: $1,234.56). %% is replaced by %. No argument is converted. You can give optional conversion specifications immediately after the initial % of a directive in the following order: Specifier Meaning =f Specifies f as the numeric fill character. This flag is used in conjunction with the maximum digits specification #n (see below). The default numeric fill character is the space character. This option does not affect the other fill operations that always use a space as the fill character. ^ Formats the currency amount without thousands grouping characters. The default is to insert the grouping characters if defined for the current locale. + | C | ( Specifies the style of representing positive and negative currency amounts. You can specify only one of +, C, or (. The + specifies to use the locale's equivalent of + and -. For example, in USA, the empty (null) string if positive and - if negative. C specifies to use the locale's equivalent of DB for negative and CR for positive. The ( specifies to use the locale's equivalent of enclosing negative amounts within parenthesis. If this option is not included, a default specified by the current locale is used. ! Suppresses the currency symbol from the output conversion. [-]w A decimal digit string that specifies a minimum field width in which the result of the conversion is right-justified (or left-justified if the - flag is specified). #n A decimal digit string that specifies a maximum number of digits expected to be formatted to the left of the radix character. You can use this option to keep the formatted output from multiple calls to strfmon aligned in the same columns. You can also use it to fill unused positions with a special character, as in $***123.45. This option causes an amount to be formatted as if it has the number of digits specified by n. If more digit positions are required than specified, this conversion specification is ignored. Digit positions in excess of those actually required are filled with the numeric fill character. (See the =f specification above). If thousands grouping is enabled, the behavior is: 1. Format the number as if it is an n digit number. 2. Insert fill characters to the left of the leftmost digit (for example, $0001234.56 or $***1234.56). 3. Insert the separator character (for example, $0,001,234.56 or $*,**1,234.56). 4. If the fill character is not the digit zero, the separators are replaced by the fill character (for example, $****1,234.56). To ensure alignment, any characters appearing before or after the number in the formatted output, such as currency or sign symbols, are padded with space characters to make their positive and negative formats an equal length. .p A decimal digit string that specifies the number of digits after the radix character. If the value of the precision p is 0, no radix character appears. If this option is not included, a default specified by the current locale is used. The amount being formatted is rounded to the specified number of digits prior to formatting. The LC_MONETARY category of the program's locale affects the behavior of this function, including the monetary radix character (which is different from the numeric radix character affected by the LC_NUMERIC category), the thousands (or alternate grouping) separator, the currency symbols, and formats. The international currency symbol should be in accordance with those specified in ISO 4217 Codes for the representation of currencies and funds. Return Value If the total number of resulting bytes including the terminating null character is not more than maxsize, strfmon returns the number of bytes placed into the array pointed to by s, not including the terminating null character. Otherwise, strfmon returns -1 and the contents of the array are indeterminate. ═══ Example of strfmon ═══ /************************************************************************ This example uses strfmon to format the monetary value for money, then prints the resulting string. ************************************************************************/ #include #include #include #include int main(void) { char string[100]; /* hold the string returned from strfmon() */ double money = 1234.56; if (NULL == setlocale(LC_ALL, "en_us.ibm-850")) { printf("Unable to setlocale().\n"); exit(EXIT_FAILURE); } strfmon(string, 100, "%i", money); printf("International currency format = \"%s\"\n", string); strfmon(string, 100, "%n", money); printf("National currency format = \"%s\"\n", string); return 0; /**************************************************************************** The output should be similar to : International currency format = "USD 1,234.56" National currency format = "$1,234.56" ****************************************************************************/ } ═══ Related Information ═══ Example of strfmon  strftime - Convert to Formatted Time  ═══ 4.279. 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, XPG4, POSIX strftime converts the time and date specification in the timeptr structure into a character string. It then stores the null-terminated string in the array pointed to by dest according to the format string pointed to by format. maxsize specifies the maximum number of characters that can be copied into the array. The format string is a multibyte character string containing:  Conversion specification characters, preceded by a % sign.  Ordinary multibyte characters, which are copied into the array unchanged. If data has the form of a conversion specifier, but is not one of the accepted specifiers, the characters following the % are copied to the output. The characters that are converted are determined by the LC_CTYPE category of the current locale and by the values in the time structure pointed to by timeptr. The time structure pointed to by timeptr is usually obtained by calling the gmtime or localtime function. When objects to be copied overlap, the behavior is undefined. strftime obtains time zone information from an internal structure. You can set the values in this structure by calling either tzset or setlocale. tzset sets the structure according to the information in the TZ environment variable; setlocale sets it according to the LC_TOD category in the current locale. If you do not set the values by calling one of these functions, the defaults used are EST for time zone name, EDT for Daylight Savings time zone name, and 300 minutes for time zone. Return Value If the total number of characters in the resulting string, including the terminating null character, does not exceed maxsize, strftime returns the number of characters (bytes) placed into dest, not including the terminating null character. Otherwise, strftime returns 0 and the content of the string is indeterminate. ═══ Example of strftime ═══ /************************************************************************ This example gets the time and date from localtime, calls strftime to format it, 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); return 0; /**************************************************************************** The output should be similar to: 41 characters placed in string to make: Today is Monday, Sep 16. Time: 06:31 pm ****************************************************************************/ } ═══ Related Information ═══ Example of strftime  Conversion Specifiers Used by strftime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  setlocale - Set Locale  strptime - Convert to Formatted Date and Time  time - Determine Current Time  wcsftime - Convert to Formatted Date and Time  ═══ 4.279.1. Conversion Specifiers Used by strftime ═══ The following table lists the strftime conversion specifiers: ┌──────────────────┬───────────────────────────────────────────────────────────┐ │ SPECIFIER │ MEANING │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %a │ Replace with abbreviated weekday name of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %A │ Replace with full weekday name of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %b │ Replace with abbreviated month name of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %B │ Replace with full month name of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %c │ Replace with date and time of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %C │ Replace with locale's century number (year divided by 100 │ │ │ and truncated) │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %d │ Replace with day of the month (01-31). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %D │ Insert date in mm/dd/yy form, regardless of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %e │ Insert month of the year as a decimal number ("01"-"12"). │ │ │ │ │ │ Under POSIX, it's a 2-character, right-justified, blank- │ │ │ filled field. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %E[cCxXyY] │ If the alternate date/time format is not available, the │ │ │ %E descriptors are mapped to their unextended counter- │ │ │ parts. For example, %EC is mapped to %C. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Ec │ Replace with the locale's alternative date and time rep- │ │ │ resentation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %EC │ Replace with the name of the base year (period) in the │ │ │ locale's alternate representation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Ex │ Replace with the locale's alternative date represen- │ │ │ tation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %EX │ Replace with the locale's alternative time represen- │ │ │ tation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Ey │ Replace with the offset from %EC (year only) in the │ │ │ locale's alternate representation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %EY │ Replace with the full alternative year representation. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %h │ Replace with locale's abbreviated month name. This is the │ │ │ same as %b. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %H │ Replace with hour (24-hour clock) as a decimal number │ │ │ (00-23). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %I │ Replace with hour (12-hour clock) as a decimal number │ │ │ (01-12). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %j │ Replace with day of the year (001-366). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %m │ Replace with month (01-12). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %M │ Replace with minute (00-59). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %n │ Replace with a new line. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %O[deHImMSUwWy] │ │ │ │ │ │ │ If the alternative date/time format is not available, the │ │ │ %O descriptors are mapped to their unextended counter- │ │ │ parts. For example, %Od is mapped to %d. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Od │ Replace with the day of month, using the locale's alter- │ │ │ native numeric symbols, filled as needed with leading │ │ │ zeroes if there is any alternative symbol for zero; oth- │ │ │ erwise fill with leading spaces. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Oe │ Replace with the day of the month, using the locale's │ │ │ alternative numeric symbols, filled as needed with │ │ │ leading spaces. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OH │ Replace with the hour (24-hour clock), using the locale's │ │ │ alternative numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OI │ Replace with the hour (12-hour clock), using the locale's │ │ │ alternative numeric symbols. │ └──────────────────┴───────────────────────────────────────────────────────────┘ ┌──────────────────┬───────────────────────────────────────────────────────────┐ │ %Om │ Replace with the month, using the locale's alternative │ │ │ numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OM │ Replace with the minutes, using the locale's alternative │ │ │ numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OS │ Replace with the seconds, using the locale's alternative │ │ │ numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Ou │ Replace with the weekday as a decimal number (1 to 7), │ │ │ with 1 representing Monday, using the locale's alterna- │ │ │ tive numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OU │ Replace with the week number of the year (00-53), where │ │ │ Sunday is the first day of the week, using the locale's │ │ │ alternative numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ &OV │ Replace with week number of the year (01-53), where │ │ │ Monday is the first day of the week, using the locale's │ │ │ alternative numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Ow │ Replace with the weekday (Sunday=0), using the locale's │ │ │ alternative numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %OW │ Replace with the week number of the year (01-53), where │ │ │ Monday is the first day of the week, using the locale's │ │ │ alternative numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Oy │ Replace with the year (offset from %C) in the locale's │ │ │ alternative representation, using the locale's alterna- │ │ │ tive numeric symbols. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %p │ Replace with the locale's equivalent of AM or PM. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %r │ Replace with a string equivalent to %I:%M:%S %p; or use │ │ │ "t_fmt_ampm" from LC_TIME, if present. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %R │ Replace with time in 24 hour notation (%H:%M) │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %S │ Replace with second (00-61). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %t │ Replace with a tab. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %T │ Replace with a string equivalent to %H:%M:%S. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %u │ Replace with the weekday as a decimal number (1 to 7), │ │ │ with 1 representing Monday. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %U │ Replace with week number of the year (00-53), where │ │ │ Sunday is the first day of the week. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %V │ Replace with week number of the year (01-53), where │ │ │ Monday is the first day of the week. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %w │ Replace with weekday (0-6), where Sunday is 0. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %W │ Replace with week number of the year (00-53), where │ │ │ Monday is the first day of the week. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %x │ Replace with date representation of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %X │ Replace with time representation of locale. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %y │ Replace with year without the century (00-99). │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Y │ Replace with year including the century. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %Z │ Replace with name of time zone, or no characters if time │ │ │ zone is not available. │ ├──────────────────┼───────────────────────────────────────────────────────────┤ │ %% │ Replace with %. │ └──────────────────┴───────────────────────────────────────────────────────────┘ For %Z, the tm_isdst flag in the tm structure passed to strftime specifies whether the time zone is standard or Daylight Savings time. If data has the form of a directive, but is not one of the above, the characters following the % are copied to the output. ═══ 4.280. stricmp - Compare Strings as Lowercase ═══ ═══ Format ═══ #include int stricmp(const char *string1, const char *string2); ═══ Description ═══ Language Level: Extension stricmp compares string1 and string2 without sensitivity for case. All alphabetic characters in the arguments string1 and string2 are converted to lowercase before the comparison. stricmp operates on null-terminated strings. Return Value stricmp 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 ═══ /************************************************************************ 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 output should be: str1 is the same as str2 ****************************************************************************/ } ═══ Related Information ═══ Example of stricmp  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  strcspn - Compare Strings for Substrings  strncmp - Compare Strings  strnicmp - Compare Strings Without Case Sensitivity  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.281. strlen - Determine String Length ═══ ═══ Format ═══ #include size_t strlen(const char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strlen determines the length of string excluding the terminating null character. Return Value strlen returns the length of string. ═══ Example of strlen ═══ /************************************************************************ This example determines the length of the string that is passed to main. ************************************************************************/ #include #include int main(int argc,char **argv) { char *String = "How long is this string?"; printf("Length of string \"%s\" is %i.\n", String, strlen(String)); return 0; /**************************************************************************** The output should be: Length of string "How long is this string?" is 24. ****************************************************************************/ } ═══ Related Information ═══ Example of strlen  mblen - Determine Length of Multibyte Character  strrev - Reverse String  wcslen - Calculate Length of Wide-Character String  ═══ 4.282. strlwr - Convert Uppercase to Lowercase ═══ ═══ Format ═══ #include char *strlwr(char *string); ═══ Description ═══ Language Level: Extension strlwr converts any uppercase letters in the given null-terminated string to lowercase. Other characters are not affected. Return Value strlwr returns a pointer to the converted string. There is no error return. ═══ 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 output should be: Expected result: general assembly strlwr returned: general assembly ****************************************************************************/ } ═══ Related Information ═══ Example of strlwr  strupr - Convert Lowercase to Uppercase  _toascii - _tolower - _toupper - Convert Character  tolower() - toupper() - Convert Character Case  towlower - towupper - Convert Wide Character Case  ═══ 4.283. strncat - Concatenate Strings ═══ ═══ Format ═══ #include char *strncat(char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strncat 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. Return Value strncat returns a pointer to the joined string (string1). ═══ 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); return 0; /**************************************************************************** The output should be: strcat : buffer1 = "computer program" strncat: buffer1 = "computer pr" ****************************************************************************/ } ═══ Related Information ═══ Example of strncat  strcat - Concatenate Strings  strnicmp - Compare Strings Without Case Sensitivity  wcscat - Concatenate Wide-Character Strings  wcsncat - Concatenate Wide-Character Strings  ═══ 4.284. strncmp - Compare Strings ═══ ═══ Format ═══ #include int strncmp(const char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strncmp compares the first count characters of string1 and string2. Return Value strncmp 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be: Comparison of each character strcmp: "abcdefg" is less than "abcfg" Comparison of only the first 3 characters strncmp: "abcdefg" is identical to "abcfg" ****************************************************************************/ } void print_result(int res,char *p_buffer1,char *p_buffer2) { if (0 == res) 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); } ═══ Related Information ═══ Example of strncmp  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  strcoll - Compare Strings Using Collation Rules  strcspn - Compare Strings for Substrings  stricmp - Compare Strings as Lowercase  strnicmp - Compare Strings Without Case Sensitivity  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.285. strncpy - Copy Strings ═══ ═══ Format ═══ #include char *strncpy(char *string1, const char *string2, size_t count); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strncpy 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. Return Value strncpy returns a pointer to string1. ═══ 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); return 0; /**************************************************************************** The output should be: destination is originally = 'abcdefg' After strcpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After strncpy, destination1 becomes '12345fg' ****************************************************************************/ } ═══ Related Information ═══ Example of strncpy  strcpy - Copy Strings  strdup - Duplicate String  strnicmp - Compare Strings Without Case Sensitivity  ═══ 4.286. strnicmp - Compare Strings Without Case Sensitivity ═══ ═══ Format ═══ #include int strnicmp(const char *string1, const char *string2, int n); ═══ Description ═══ Language Level: Extension strnicmp compares, at most, the first n characters of string1 and string2. It operates on null-terminated strings. strnicmp is case insensitive; the uppercase and lowercase forms of a letter are considered equivalent. Return Value 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 ═══ /************************************************************************ 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 output should be: The two strings are equivalent. ****************************************************************************/ } ═══ Related Information ═══ Example of strnicmp  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  stricmp - Compare Strings as Lowercase  strncmp - Compare Strings  wcscmp - Compare Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.287. 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 strnset 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. strset 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). Return Value Both strset and strnset return a pointer to the altered string. There is no error return value. ═══ Example of strnset and strset ═══ /************************************************************************ In this example, strnset sets not more than four characters of a string to the character 'x'. Then the strset function changes any non-null characters of the 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: This is the string: abcdefghi This is the string after strnset: xxxxefghi This is the string after strset: kkkkkkkkk ****************************************************************************/ } ═══ Related Information ═══ Example of strnset and strset  strchr - Search for Character  strpbrk - Find Characters in String  wcschr - Search for Wide Character  wcspbrk - Locate Wide Characters in String  ═══ 4.288. strpbrk - Find Characters in String ═══ ═══ Format ═══ #include char *strpbrk(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strpbrk locates the first occurrence in the string pointed to by string1 of any character from the string pointed to by string2. Return Value strpbrk returns a pointer to the character. If string1 and string2 have no characters in common, a NULL pointer is returned. ═══ 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); return 0; /**************************************************************************** The output should be: The first occurrence of any of the characters "ab" in "A Blue Danube" is "anube" ****************************************************************************/ } ═══ Related Information ═══ Example of strpbrk  strchr - Search for Character  strcspn - Compare Strings for Substrings  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcswcs - Locate Wide-Character Substring  ═══ 4.289. strptime - Convert to Formatted Date and Time ═══ ═══ Format ═══ #include char *strptime(const char *buf, const char *fmt, struct tm *tm); ═══ Description ═══ Language Level: XPG4 strptime uses the format specified by fmt to convert the character string pointed to by buf to values that are stored in the structure pointed to by tm. The *fmt is composed of zero or more directives. Each directive is composed of one of the following:  One or more white-space characters (as specified by the isspace function)  An ordinary character (neither % nor a white-space character)  A conversion specifier. Each conversion specifier consists of a % character followed by a conversion character that specifies the replacement required. There must be white-space or other non-alphanumeric characters between any two conversion specifiers. See Conversion Specifiers Used by strptime for a list of conversion specifiers. For a directive composed of white-space characters, strptime scans input up to the first character that is not white space (which remains unscanned), or until no more characters can be scanned. For a directive that is an ordinary character, strptime scans the next character from the buffer. If the scanned character differs from the one comprising the directive, the directive fails and the differing and subsequent characters remain unscanned. For a series of directives composed of %n, %t, white-space characters, or any combination, strptime scans up to the first character that is not white space (which remains unscanned), or until no more characters can be scanned. For any other conversion specification, strptime scans characters until a character matching the next directive is scanned, or until no more characters can be scanned. It then compares these characters, excepting the one matching the next directive, to the locale values associated with the conversion specifier. If a match is found, strptime sets the appropriate tm structure members to values corresponding to the locale information. Case is ignored when items in buf are matched, such as month or weekday names. If no match is found, strptime fails and no more characters are scanned. Return Value If successful, strptime returns a pointer to the character following the last character parsed. Otherwise, a null pointer is returned. ═══ Example of strptime ═══ /************************************************************************ This example uses strptime to convert a string to the structure xmas, then prints the contents of the structure. ************************************************************************/ #include #include #include int main(void) { struct tm xmas; if (NULL == strptime("12/25/94 12:00:01", "%D %T", &xmas)) { printf("strptime() failed.\n"); exit(EXIT_FAILURE); } printf("tm_sec = %3d\n", xmas.tm_sec ); printf("tm_min = %3d\n", xmas.tm_min ); printf("tm_hour = %3d\n", xmas.tm_hour); printf("tm_mday = %3d\n", xmas.tm_mday); printf("tm_mon = %3d\n", xmas.tm_mon ); printf("tm_year = %3d\n", xmas.tm_year); return 0; /**************************************************************************** The output should be similar to : tm_sec = 1 tm_min = 0 tm_hour = 12 tm_mday = 25 tm_mon = 11 tm_year = 94 ****************************************************************************/ } ═══ Related Information ═══ Example of strptime  Conversion Specifiers Used by strptime  strftime - Convert to Formatted Time  wcsftime - Convert to Formatted Date and Time  ═══ 4.289.1. Conversion Specifiers Used by strptime ═══ The following tables list the conversion specifiers for strptime. ┌───────────────┬─────────────────────────────────────────────────┐ │ SPECIFIER │ MEANING │ ├───────────────┼─────────────────────────────────────────────────┤ │ %a │ Day of week, using locale's abbreviated or full │ │ │ weekday name. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %A │ Day of week, using locale's abbreviated or full │ │ │ weekday name. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %b │ Month, using locale's abbreviated or full month │ │ │ name. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %B │ Month, using locale's abbreviated or full month │ │ │ name. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %c │ Date and time, using locale's date and time. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %C │ Century number (year divided by 100 and trun- │ │ │ cated to an integer) │ ├───────────────┼─────────────────────────────────────────────────┤ │ %d │ Day of the month (1-31; leading zeros permitted │ │ │ but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %D │ Date as %m/%d/%y. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %e │ Day of the month (1-31; leading zeros permitted │ │ │ but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %h │ Month, using locale's abbreviated or full month │ │ │ name. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %H │ Hour (0-23; leading zeros permitted but not │ │ │ required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %I │ Hour (0-12; leading zeros permitted but not │ │ │ required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %j │ Day number of the year (001-366). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %m │ Month number (1-12; leading zeros permitted but │ │ │ not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %M │ Minute (0-59; leading zeros permitted but not │ │ │ required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %n │ Newline character. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %p │ Locale's equivalent of AM or PM. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %r │ Time as %I:%M:%S a.m. or %I:%M:%S p.m. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %R │ Time in 24 hour notation (%H%M) │ ├───────────────┼─────────────────────────────────────────────────┤ │ %S │ Seconds (0-61; leading zeros permitted but not │ │ │ required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %t │ Tab character. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %T │ Time as %H:%M:%S. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %U │ Week number of the year (0-53; where Sunday is │ │ │ the first day of the week; leading zeros per- │ │ │ mitted but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %w │ Weekday (0-6; where Sunday is 0; leading zeros │ │ │ permitted but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %W │ Week number of the year (0-53; where Monday is │ │ │ the first day of the week; leading zeros per- │ │ │ mitted but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %x │ Date, using locale's date format. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %X │ Time, using locale's time format. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %y │ Year within century (0-99; leading zeros per- │ │ │ mitted but not required). │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Y │ Year, including century. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Z │ Time zone name │ ├───────────────┼─────────────────────────────────────────────────┤ │ %% │ Replace with %. │ └───────────────┴─────────────────────────────────────────────────┘ Some directives can be modified by the E or O modifier characters to indicate that an alternative format or specification should be used rather than the one normally used by the unmodified directive. If the alternative format or specification does not exist in the current locale, the behavior will be as if the unmodified directive were used. ┌───────────────┬─────────────────────────────────────────────────┐ │ SPECIFIER │ MEANING │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Ec │ Replace with the locale's alternative date and │ │ │ time representation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %EC │ Replace with the name of the base year (period) │ │ │ in the locale's alternative representation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Ex │ Replace with the locale's alternative date rep- │ │ │ resentation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %EX │ Replace with the locale's alternative time rep- │ │ │ resentation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Ey │ Replace with the offset from %EC (year only) in │ │ │ the locale's alternative representation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %EY │ Replace with the full alternative year repre- │ │ │ sentation. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Od │ Replace with the day of month, using the │ │ │ locale's alternative numeric symbols, filled as │ │ │ needed with leading zeroes if there is any │ │ │ alternative symbol for zero; otherwise, fill │ │ │ with leading spaces. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Oe │ Replace with the day of the month, using the │ │ │ locale's alternative numeric symbols, filled as │ │ │ needed with leading spaces. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OH │ Replace with the hour (24-hour clock), using │ │ │ the locale's alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OI │ Replace with the hour (12-hour clock), using │ │ │ the locale's alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Om │ Replace with the month, using the locale's │ │ │ alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OM │ Replace with the minutes, using the locale's │ │ │ alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OS │ Replace with the seconds, using the locale's │ │ │ alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OU │ Replace with the week number of the year │ │ │ (Sunday as the first day of the week, rules │ │ │ corresponding to %U), using the locale's alter- │ │ │ native numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Ow │ Replace with the weekday (Sunday=0), using the │ │ │ locale's alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %OW │ Replace with the week number of the year │ │ │ (Monday as the first day of the week), using │ │ │ the locale's alternative numeric symbols. │ ├───────────────┼─────────────────────────────────────────────────┤ │ %Oy │ Replace with the year (offset from %C) in the │ │ │ locale's alternative representation, using the │ │ │ locale's alternative numeric symbols. │ └───────────────┴─────────────────────────────────────────────────┘ ═══ 4.290. strrchr - Find Last Occurrence of Character in String ═══ ═══ Format ═══ #include char *strrchr(const char *string, int c); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strrchr finds the last occurrence of c (converted to a character) in string. The ending null character is considered part of the string. Return Value strrchr 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be: The first occurrence of p in 'computer program' is 'puter program' The last occurrence of p in 'computer program' is 'program' ****************************************************************************/ } ═══ Related Information ═══ Example of strrchr  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strspn - Search Strings  wcschr - Search for Wide Character  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcswcs - Locate Wide-Character Substring  ═══ 4.291. strrev - Reverse String ═══ ═══ Format ═══ #include char *strrev(char *string); ═══ Description ═══ Language Level: Extension strrev reverses the order of the characters in the given string. The ending null character (\0) remains in place. Return Value strrev returns a pointer to the altered string. There is no error return value. ═══ Example of strrev ═══ /************************************************************************ This example determines whether a string is a palindrome. A palindrome is a string that reads the same forward and backward. ************************************************************************/ #include #include #include int palindrome(char *string) { char *string2; /* Duplicate string for comparison */ if (NULL == (string2 = strdup(string))) { printf("Storage could not be reserved for string\n"); exit(EXIT_FAILURE); } /* 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; /**************************************************************************** Sample output from program: Please enter a string. level The string is a palindrome. ... or ... Please enter a string. levels The string is not a palindrome. ****************************************************************************/ } ═══ Related Information ═══ Example of strrev  strcat - Concatenate Strings  strcmp - Compare Strings  strcpy - Copy Strings  strdup - Duplicate String  strnset - strset - Set Characters in String  ═══ 4.292. strspn - Search Strings ═══ ═══ Format ═══ #include size_t strspn(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strspn 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. Return Value strspn 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 ═══ /************************************************************************ This example finds the first occurrence in the array string of a character that is not an a, b, or 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); return 0; /**************************************************************************** The output should be: The first 5 characters of "cabbage" are found in "abc" ****************************************************************************/ } ═══ Related Information ═══ Example of strspn  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  ═══ 4.293. strstr - Locate Substring ═══ ═══ Format ═══ #include char *strstr(const char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 strstr finds the first occurrence of string2 in string1. The function ignores the null character (\0) that ends string2 in the matching process. Return Value strstr 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, strstr returns string1. ═══ Example of strstr ═══ /************************************************************************ This example locates the string haystack in the string "needle in a haystack". ************************************************************************/ #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); return 0; /**************************************************************************** The output should be: haystack ****************************************************************************/ } ═══ Related Information ═══ Example of strstr  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  ═══ 4.294. _strtime - Copy Time ═══ ═══ Format ═══ #include char *_strtime(char *time); ═══ Description ═══ Language Level: Extension _strtime copies the current time into the buffer that time points to. 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. Return Value _strtime returns a pointer to the buffer. There is no error return. ═══ 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:47:22 ****************************************************************************/ } ═══ Related Information ═══ Example of _strtime  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  time - Determine Current Time  tzset - Assign Values to Locale Information  ═══ 4.295. strtocoll - Return Collating Element for String ═══ ═══ Format ═══ #include collel_t strtocoll(char *string); ═══ Description ═══ Language Level: Extension strtocoll determines the collating element (collel_t) that represents string. For a string of one character, the collating element always exists, and is the wchar_t of that character. For a string with more than one character, a valid collating element exists if the LC_COLLATE category contains the definition of a sequence of characters that collate as one for the purpose of culture-sensitive string comparison. This many-characters-to-one-collating-element relationship is also called many-to-one mapping. Return Value strtocoll returns the collating element (collel_t value) for string. strtocoll returns (collel_t)-1 in the following cases:  If many-to-one mapping is not defined in the LC_COLLATE category of the current locale.  If the string is not a valid collating element .  If the string has zero length.  If the wchar_t for the first character in the string is greater than the maximum wchar_t value for the characters in the charmap file for the current locale. (This error occurs when the current locale is "C" or where MB_CUR_MAX is 2, and strtocoll is passed a double-byte character, but only single-byte characters are defined in the charmap file for the locale.) ═══ Example of strtocoll ═══ /************************************************************************ This example uses strtocoll to get the start and end collating-elements for the collrange function. ************************************************************************/ #include #include #include #include int main(int argc, char *argv[]) { collel_t s, e, *rp; int i; setlocale(LC_ALL, LC_C_FRANCE); if ((collel_t)-1 == (s = strtocoll(argv[1]))) { printf("'%s' collating element not defined\n", argv[1]); exit(1); } if ((collel_t)-1 == (e = strtocoll(argv[2]))) { printf("'%s' collating element not defined\n", argv[2]); exit(1); } if (-1 == (i = collrange(s, e, &rp))) { printf("Invalid range for '%s' to '%s'\n", argv[1], argv[2]); exit(1); } for (; i > 0; rp++, i--) { if (ismccollel(*rp)) printf("'%s' ", colltostr(*rp)); else if (iswprint(*rp)) printf("'%lc' ", *rp); else printf("'%x' ", *rp); } return 0; /**************************************************************************** Assuming you enter: A z The output should be: 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '[' '\' ']' '^' '_' '`' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' ****************************************************************************/ } ═══ Related Information ═══ Example of strtocoll  cclass - Return Characters in Character Class  collequiv - Return List of Equivalent Collating Elements  collorder - Return List of Collating Elements  collrange - Calculate Range of Collating Elements  colltostr - Return String for Collating Element  getmccoll - Get Next Collating Element from String  getwmccoll - Get Next Collating Element from Wide String  ismccollel - Identify Multi-Character Collating Element  maxcoll - Return Maximum Collating Element  ═══ 4.296. strtod - Convert Character String to Double ═══ ═══ Format ═══ #include double strtod(const char *nptr, char **endptr); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 strtod 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: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬───┬──┬───────────────────────────┬──> │ │ └─white-space─┘ ├─+─┤ ├─digits──┬───┬──┬────────┬─┤ │ │ └─┴─┘ │ └─.─┘ └─digits─┘ │ │ │ └─.──digits─────────────────┘ │ │ │ │ >──┬──────────────────────┬──>< │ │ └─┬─e─┬──┬───┬──digits─┘ │ │ └─E─┘ ├─+─┤ │ │ └─┴─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ The first character that does not fit this form stops the scan. Return Value strtod returns the value of the floating-point number, except when the representation causes an underflow or overflow. For an overflow, it returns -HUGE_VAL or +HUGE_VAL; for 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. strtod does not fail if a character other than a digit follows an E or e read in as an exponent. For example, 100elf will be converted to the floating-point value 100.0. ═══ 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 = %f\n", x); printf(" Stopped scan at %s\n\n", stopstring); string = "100ergs"; x = strtod(string, &stopstring); printf("string = \"%s\"\n", string); printf(" strtod = %f\n", x); printf(" Stopped scan at \"%s\"\n\n", stopstring); return 0; /**************************************************************************** The output should be: 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 ═══ Example of strtod  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  strtoul - Convert String Segment to Unsigned Integer  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  ═══ 4.297. strtok - Tokenize String ═══ ═══ Format ═══ #include char *strtok(char *string1, const char *string2); ═══ Description ═══ Language Level: ANSI, SAA SAA, POSIX, XPG4 strtok 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. Return 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 ═══ /************************************************************************ 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, ",")); return 0; /**************************************************************************** The output should be: token: a string token: of token: token: tokens ****************************************************************************/ } ═══ Related Information ═══ Example of strtok  strcat - Concatenate Strings  strchr - Search for Character  strcmp - Compare Strings  strcpy - Copy Strings  strcspn - Compare Strings for Substrings  strspn - Search Strings  wcstok - Tokenize Wide-Character String  ═══ 4.298. strtol - Convert Character String to Long Integer ═══ ═══ Format ═══ #include long int strtol(const char *nptr, char **endptr, int base); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 strtol 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: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬───┬──┬────┬──┬────────┬──>< │ │ └─white-space─┘ ├─+─┤ ├─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 (octal); the prefix 0x or 0X means base 16 (hexadecimal); using any other digit without a prefix means decimal. Return Value strtol returns the value represented in the string, except when the representation causes an overflow. For 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 ═══ /************************************************************************ 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); } return 0; /**************************************************************************** The output should be: 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 ═══ Example of strtol  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  _ltoa - Convert Long Integer to String  strtod - Convert Character String to Double  strtold - Convert String to Long Double  strtoul - Convert String Segment to Unsigned Integer  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  ═══ 4.299. strtold - Convert String to Long Double ═══ ═══ Format ═══ #include long double strtold(const char *nptr, char **endptr); ═══ Description ═══ Language Level: Extension strtold 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 can follow 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. 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. Return Value If successful, strtold returns the value of the long double number. If it fails, strtold returns 0. For 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 ═══ /************************************************************************ 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 output should be: strtold = -1.2345678000e+13 end pointer at = end of string strtold = nan end pointer at = this cannot be converted ****************************************************************************/ } ═══ Related Information ═══ Example of strtold  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtoul - Convert String Segment to Unsigned Integer  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  Infinity and NaN Support  ═══ 4.300. 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, XPG4 strtoul 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. strtoul 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. strtoul 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 use strtoul, string1 should point to a string with the following form: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬───┬──┬────┬──┬────────┬──>< │ │ └─white-space─┘ ├─+─┤ ├─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 (octal); the prefix 0x or 0X means base 16 (hexadecimal); using any other digit without a prefix means decimal. Return Value strtoul returns the value represented in the string, or 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 ═══ /************************************************************************ 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); return 0; /**************************************************************************** The output should be: string = 1000e13 e strtoul = 8 (base 2) Stopped scan at e13 e ****************************************************************************/ } ═══ Related Information ═══ Example of strtoul  atof - Convert Character String to Float  atoi - Convert Character String to Integer  atol - Convert Character String to Long Integer  _atold - Convert Character String to Long Double  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  _ultoa - Convert Unsigned Long Integer to String  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  ═══ 4.301. strupr - Convert Lowercase to Uppercase ═══ ═══ Format ═══ #include char *strupr(char *string); ═══ Description ═══ Language Level: Extension strupr converts any lowercase letters in string to uppercase. Other characters are not affected. Return Value strupr returns a pointer to the converted string. There is no error return. ═══ 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 output should be: This is a copy of the string with all letters capitalized: DOSWRITE ****************************************************************************/ } ═══ Related Information ═══ Example of strupr  strlwr - Convert Uppercase to Lowercase  _toascii - _tolower - _toupper - Convert Character  tolower() - toupper() - Convert Character Case  towlower - towupper - Convert Wide Character Case  ═══ 4.302. strxfrm - Transform String ═══ ═══ Format ═══ #include size_t strxfrm(char *str1, const char *str2, size_t n); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 strxfrm transforms the string pointed to by str2 and places the resulting string into the array pointed to by str1. The transformation is determined by the program's locale. The transformed string is not necessarily readable, but can be used with the strcmp or strncmp functions. The transformation is such that, if strcmp or strncmp were applied to the two transformed strings, the results would be the same as applying strcoll to the two corresponding untransformed strings. No more than n bytes are placed into the area pointed to by str1, including the terminating null byte. If n is 0, str1 can be a null pointer. Return Value strxfrm returns the length of the transformed string (excluding the null byte). When n is 0 and str1 is a null pointer, the length returned is one less than the number of bytes required to contain the transformed string. If an error occurs, strxfrm function returns (size_t)-1 and sets errno to indicate the error. Note: 1. The string returned by strxfrm contains the weights for each order of the characters within the string. As a result, the string returned may be longer than the input string; it does not contain printable characters. 2. strxfrm calls malloc when the LC_COLLATE category specifies backward on the order_start keyword, the substitute keyword is specified, or the locale has one-to-many mapping. If malloc fails, strxfrm also fails. 3. If the locale supports double-byte characters (MB_CUR_MAX specified as 2), strxfrm validates the multibyte characters. (Previously it did not validate the string.) strxfrm will fail if the string contains invalid multibyte characters. 4. If MB_CUR_MAX is defined as 2, and no collation is defined for DBCS chars in the current locale, the DBCS characters will collate after the single-byte characters. ═══ Example of strxfrm ═══ /************************************************************************ This example uses strxfrm to transform two different strings that have the same collating weight. It then calls strcmp to compare the new strings. ************************************************************************/ #include #include #include int main(void) { char *string1 = "stride ng1"; char *string2 = "stri*ng1"; char *newstring1, *newstring2; int length1, length2; if (NULL == setlocale(LC_ALL, LC_C_FRANCE)) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length1=strxfrm(NULL, string1, 0); length2=strxfrm(NULL, string2, 0); if (NULL == (newstring1 = calloc(length1 + 1, 1)) || NULL == (newstring2 = calloc(length2 + 1, 1))) { printf("insufficient memory\n"); exit(EXIT_FAILURE); } if ((strxfrm(newstring1, string1, length1 + 1) != length1) || (strxfrm(newstring2, string2, length2 + 1) != length2)) { printf("error in string processing\n"); exit(EXIT_FAILURE); } if (0 != strcmp(newstring1, newstring2)) printf("wrong results\n"); else printf("correct results\n"); return 0; /**************************************************************************** The output should be similar to : correct results ****************************************************************************/ } ═══ Related Information ═══ Example of strxfrm  localeconv - Retrieve Information from the Environment  setlocale - Set Locale  strcmp - Compare Strings  strcoll - Compare Strings Using Collation Rules  strncmp - Compare Strings  wcsxfrm - Transform Wide-Character String  ═══ 4.303. swab - Swap Adjacent Bytes ═══ ═══ Format ═══ #include void swab(char *source, char *destination, int n); ═══ Description ═══ Language Level: Extension swab 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. swab is typically used to prepare binary data for transfer to a machine that uses a different byte order. Note: In earlier releases of C Set ++, swab began with an underscore (_swab). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _swab to swab for you. Return Value There is no return value. ═══ Example of swab ═══ /************************************************************************ This example copies n bytes from one location to another, swapping each pair of adjacent bytes: ************************************************************************/ #include #include int main(void) { char from[20] = "hTsii s atsirgn..x "; char to[20]; swab(from, to, 19); /* swap bytes */ printf("%s\n", to); return 0; /**************************************************************************** The output should be: This is a string.. ****************************************************************************/ } ═══ Related Information ═══ Example of swab  fgetc - Read a Character  fputc - Write Character  ═══ 4.304. swprintf - Format and Write Wide Characters to Buffer ═══ ═══ Format ═══ #include int swprintf(wchar_t *wcbuffer, size_t n, const wchar_t *format, argument-list); ═══ Description ═══ Language Level: ANSI 93 swprintf formats and stores a series of wide characters and values into the wide-character buffer wcsbuffer. swprintf is equivalent to sprintf, except that it operates on wide characters. The value n specifies the maximum number of wide characters to be written, including the terminating null character. swprintf converts each entry in the argument-list according to the corresponding wide-character format specifier in format. The format has the same form and function as the format string for printf, with the following exceptions:  %c (without an l prefix) converts an integer argument to wchar_t, as if by calling mbtowc.  %lc converts a wint_t to wchar_t.  %s (without an l prefix) converts an array of multibyte characters to an array of wchar_t, as if by calling mbrtowc. The array is written up to, but not including, the terminating null character, unless the precision specifies a shorter output.  %ls writes an array of wchar_t. The array is written up to, but not including, the terminating null character, unless the precision specifies a shorter output. If you specify a null string for the %s or %ls format specifier, swprintf prints (null). For a complete description of format specifiers, see printf - Print Formatted Characters. A null wide character is added to the end of the wide characters written; the null wide character is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined. In extended mode, swprintf 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. Return Value swprintf returns the number of bytes written in the array, not counting the terminating null wide character. ═══ Example of swprintf ═══ /************************************************************************ This example uses swprintf to format and print several values to buffer. ************************************************************************/ #include #include #define BUF_SIZE 100 int main(void) { wchar_t wcsbuf[BUF_SIZE]; wchar_t wstring[] = L"ABCDE"; int num; num = swprintf(wcsbuf, BUF_SIZE, L"%s", "xyz"); num += swprintf(wcsbuf + num, BUF_SIZE - num, L"%ls", wstring); num += swprintf(wcsbuf + num, BUF_SIZE - num, L"%i", 100); printf("The array wcsbuf contains: \"%ls\"\n", wcsbuf); return 0; /**************************************************************************** The output should be similar to : The array wcsbuf contains: "xyzABCDE100" ****************************************************************************/ } ═══ Related Information ═══ Example of swprintt  printf - Print Formatted Characters  sprintf - Print Formatted Data to Buffer  swscanf - Read Wide Characters from Buffer  vswprintf - Format and Write Wide Characters to Buffer  ═══ 4.305. swscanf - Read Wide Characters from Buffer ═══ ═══ Format ═══ #include int swscanf(const wchar_t *wcsbuffer, const wchar_t *format, argument-list); ═══ Description ═══ Language Level: ANSI 93 swscanf reads wide data from wcsbuffer into the locations given by argument-list. swscanf is equivalent to sscanf, except that it operates on wide characters. Each argument in the argument-list must point to a variable with a type that corresponds to a type specifier in format. The format has the same form and function as the format string for scanf, with the following exceptions:  %c (with no l prefix) converts one or more wchar_t characters (depending on precision) to multibyte characters, as if by calling wcrtomb.  %lc converts one or more wchar_t characters (depending on precision) to an array of wchar_t.  %s (with no l prefix) converts a sequence of non-white-space wchar_t characters to multibyte characters, as if by calling wcrtomb. The array includes the terminating null character.  %ls copies an array of wchar_t, including the terminating null wide character, to an array of wchar_t. For a complete description of format specifiers, see scanf Format Specification Fields. When swscanf reaches the end of the wide character string, it stops parsing and returns a value as indicated below (this behavior is the same as sscanf). If copying takes place between objects that overlap, the behavior is undefined. Return Value swscanf returns the number of input items that were successfully converted and assigned. The value does not include fields that were read but not assigned. If an input failure (such as the end of the string) is encountered before any conversion, swscanf returns EOF. ═══ Example of swscanf ═══ /************************************************************************ This example uses swscanf to scan in wide characters, and then prints them. ************************************************************************/ #include #include int main(void) { wchar_t *tokenstring = L"xyz ГAГBГCГDГE─a 1234"; char string[20]; wchar_t wstring[20]; wchar_t wc; int i; int num; num = swscanf(tokenstring, L"%s %ls %lc %d", string, wstring, &wc, &i); printf("string = %s\n", string ); printf("wstring = %ls\n", wstring ); printf("wc = %lc\n", wc ); printf("i = %d\n", i ); printf("total number of fields scanned: %i\n", num); return 0; /**************************************************************************** The output should be similar to : string = xyz wstring = ГAГBГCГDГE─a wc = 1 i = 234 total number of fields scanned: 4 ****************************************************************************/ } ═══ Related Information ═══ Example of swscanf  scanf - Read Data  scanf Format Specification Fields  sscanf - Read Data  swprintf - Format and Write Wide Characters to Buffer  ═══ 4.306. system - Invoke the Command Processor ═══ ═══ Format ═══ #include int system(char *string); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension system passes the command string to a command processor to be run. The command processor specified in the COMSPEC environment variable is first searched for. 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 are 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. Return Value If the argument is a null pointer, system returns nonzero if a command processor exists, and 0 if it does not. system returns the 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 ═══ /************************************************************************ 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:\\"); return rc; /* The output should be a listing of the root directory on the c: drive */ } ═══ Related Information ═══ Example of system  exit - End Program  _exit - End Process   ═══ 4.307. __sxchg - Exchange Integer Value with Memory ═══ ═══ Format ═══ #include short _Builtin __sxchg(volatile short*lockptr, short value); ═══ Description ═══ Language Level: Extension __sxchg puts the specified value in the memory location pointed to by lockptr, and returns the value that was previously in that location. Use this function to implement fast-RAM semaphores to serialize access to a critical resource (so that only one thread can use it at a time). You can also use OS/2 semaphores to serialize resource access, but they are slower. Typically you would create both a fast-RAM semaphore and an OS/2 semaphore for the resource. For more details about OS/2 semaphores and how to use them, see the Control Program Guide and Reference. To implement a fast-RAM semaphore, allocate a volatile memory location lockptr (for __sxchg, it must be a short), and statically initialize it to 0 to indicate that the resource is free (not being used). To give a thread access to the resource, call __sxchg from the thread to exchange a non-zero value with that memory location. If __sxchg returns 0, the thread can access the resource; it has also set the memory location so that other threads can tell the resource is in use. When your thread no longer needs the resource, call __sxchg again to reset the memory location to 0. If __sxchg returns a non-zero value, another thread is already using the resource, and the calling thread must wait for access. You could then use the OS/2 semaphore to inform your waiting thread when the resource is unlocked by the thread currently using it. It is important that you set the memory to a non-zero value when you are using the resource. You can use the same non-zero value for all threads, or a unique value for each. Note: __sxchg is a built-in function, which means it is implemented as an inline instruction and has no backing code in the library. For this reason:  You cannot take the address of __sxchg.  You cannot parenthesize a call to __sxchg. (Parentheses specify a call to the function's backing code, and __sxchg has none.) Return Value __sxchg returns the previous value stored in the memory location pointed to by lockptr. ═══ Example of __sxchg ═══ /************************************************************************ This example creates five separate threads, each associated with a State. At most two threads can have a State of Eating at the same time. When a thread calls PickUpChopSticks, that function checks the states of the preceding threads to make sure they are not already Eating, If the call to __sxchg is successful, the thread has locked the Lock semaphore and can change its State to Eating. It then calls __sxchg a second time to unlock the semaphore, and returns. If __sxchg cannot lock the semaphore, another thread has it locked. The current thread then suspends itself briefly with DosSleep and tries again. The semaphore is used to ensure that two threads cannot simultaneously change their State to Eating, which would cause a deadlock. (Note that although the semaphore solves the problem of deadlock, it is not an optimal solution; some threads may never get the semaphore or the State of Eating.) Note: You must compile this example with the multithread (/Gm) option. The example runs in an infinite loop; press Ctrl-C to end it. ************************************************************************/ #pragma strings(readonly) #define INCL_DOS #include #include #include #include typedef enum { Thinking, Eating, Hungry } States; #define UNLOCKED 0 #define LOCKED 1 #define NUM_PHILOSOPHERS 5 static volatile short Lock; static States State[NUM_PHILOSOPHERS]; static const int NameMap[NUM_PHILOSOPHERS] = {0, 1, 2, 3, 4}; static const char * const Names[NUM_PHILOSOPHERS] = {"Plato", "Socrates", "Kant", "Hegel", "Nietsche"}; void PickUpChopSticks(int Ident); void PutDownChopSticks(int Ident); void Think(int Ident); void Eat(int Ident); void _Optlink StartPhilosopher(void *pIdent); void _Optlink StartPhilosopher(void *pIdent) { int Ident = *(int *)pIdent; while (1) { State[Ident] = Hungry; printf("%s hungry.\n", Names[Ident]); PickUpChopSticks(Ident); Eat(Ident); PutDownChopSticks(Ident); Think(Ident); } } int main(int argc, char *argv[], char *envp[]) { int i; unsigned long tid; for (i = 0; i < NUM_PHILOSOPHERS; i++) { tid = _beginthread(StartPhilosopher, NULL, 8192, (void *)&NameMap[i]); if (tid == -1) { printf("Unable to start %s.\n", Names[i]); } else { printf("%s started with Thread Id = %d.\n", Names[i], tid); } } DosWaitThread(&tid, DCWW_WAIT); return 0; } void PickUpChopSticks(int Ident) { while (1) { if (State[(Ident + NUM_PHILOSOPHERS - 1) % NUM_PHILOSOPHERS] != Eating && State[(Ident + 1) % NUM_PHILOSOPHERS] != Eating && !__sxchg(&Lock, LOCKED)) { State[Ident] = Eating; __sxchg(&Lock, UNLOCKED); return; } else { DosSleep(1); } } } void PutDownChopSticks(int Ident) { State[Ident] = Thinking; } void Eat(int Ident) { printf("%s eating.\n", Names[Ident]); DosSleep(1); } void Think(int Ident) { printf("%s thinking.\n", Names[Ident]); DosSleep(1); } /**************************************************************************** The output should be similar to : Plato started with Thread Id = 2. Socrates started with Thread Id = 3. Kant started with Thread Id = 4. Hegel started with Thread Id = 5. Nietsche started with Thread Id = 6. Plato hungry. Plato eating. Socrates hungry. Kant hungry. Kant eating. Hegel hungry. Nietsche hungry. Kant thinking. Plato thinking. Plato hungry. Plato eating. Kant hungry. Kant eating. : ****************************************************************************/ ═══ Related Information ═══ Example of __sxchg  __cxchg - Exchange Character Value with Memory  __lxchg - Exchange Integer Value with Memory  ═══ 4.308. tan - Calculate Tangent ═══ ═══ Format ═══ #include double tan(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 tan 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. Return Value tan returns the value of the tangent of x. ═══ Example of tan ═══ /************************************************************************ This example computes x as the tangent of pi/4. ************************************************************************/ #include int main(void) { double pi,x; pi = 3.1415926; x = tan(pi/4.0); printf("tan( %lf ) is %lf\n", pi/4, x); return 0; /**************************************************************************** The output should be: tan( 0.785398 ) is 1.000000 ****************************************************************************/ } ═══ Related Information ═══ Example of tan  atan - atan2 - Calculate Arctangent  cos - Calculate Cosine  _fpatan - Calculate Arctangent  _fptan - Calculate Tangent  sin - Calculate Sine  tanh - Calculate Hyperbolic Tangent  ═══ 4.309. tanh - Calculate Hyperbolic Tangent ═══ ═══ Format ═══ #include double tanh(double x); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 tanh calculates the hyperbolic tangent of x, where x is expressed in radians. Return Value tanh returns the value of the hyperbolic tangent of x. The result of tanh cannot have a range error. ═══ Example of tanh ═══ /************************************************************************ This example computes x as the hyperbolic tangent of pi/4. ************************************************************************/ #include int main(void) { double pi,x; pi = 3.1415926; x = tanh(pi/4); printf("tanh( %lf ) = %lf\n", pi/4, x); return 0; /**************************************************************************** The output should be: tanh( 0.785398 ) = 0.655794 ****************************************************************************/ } ═══ Related Information ═══ Example of tanh  atan - atan2 - Calculate Arctangent  cosh - Calculate Hyperbolic Cosine  _fpatan - Calculate Arctangent  _fptan - Calculate Tangent  sinh - Calculate Hyperbolic Sine  tan - Calculate Tangent  ═══ 4.310. _tcalloc - Reserve Tiled Storage Block ═══ ═══ Format ═══ #include /* also in */ void *_tcalloc(size_t number, size_t size) ═══ Description ═══ Language Level: Extension _tcalloc allocates tiled memory for an array of number elements, each of length size bytes, and initializes all bits of each element to 0. To use _tcalloc, you must compile with the /Gt compiler option. This option maps all calloc calls to _tcalloc (you can also call _tcalloc explicitly). Note: The /Gt option maps all calls to regular memory management functions to their tiled versions. To prevent a call from being mapped, parenthesize the function name. _tcalloc works just like calloc except that it allocates tiled memory instead of regular memory. Tiled memory will not cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size will cross 64K boundaries. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory is limited to 512 MB per process. You can also create your own heaps of tiled memory. See "Memory Management" in the Programming Guide for more information. A debug version of this function, _debug_tcalloc, is also available. Use the /Tm compiler option to map _tcalloc calls to _debug_tcalloc. Return Value _tcalloc 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 ═══ /************************************************************************ This example allocates tiled memory for an array of 100 elements of size char. Note: You must compile this example with the /Gt option to enable tiled memory. ************************************************************************/ #include int main(void) { char *memoryPtr; if (NULL != (memoryPtr = calloc(100, sizeof(char)))) puts("Successfully allocated 100 char of tiled memory."); else puts("Could not allocate tiled memory."); free(memoryPtr); return 0; /**************************************************************************** The output should be similar to : Successfully allocated 100 char of tiled memory. ****************************************************************************/ } ═══ Related Information ═══ Example of _tcalloc  calloc - Reserve and Initialize Storage  _debug_calloc - Allocate and Initialize Memory  _debug_tcalloc - Reserve and Initialize Tiled Memory  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _tfree - Free Tiled Storage Block  _theapmin - Release Unused Tiled Memory  _tmalloc - Reserve Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block  _ucalloc - Reserve and Initialize Memory from User Heap  Differentiating between Memory Management Functions  Managing Memory in the Programming Guide   ═══ 4.311. _tdump_allocated - Get Information about Allocated Tiled Memory ═══ ═══ Format ═══ #include /* also in */ void _tdump_allocated(int nbytes); ═══ Description ═══ Language Level: Extension _tdump_allocated prints information to stderr about each tiled memory block that is currently allocated and was allocated using the tiled debug memory management functions (_debug_tcalloc, _debug_tmalloc, and so on). _tdump_allocated works just like _dump_allocated, but displays information about tiled memory instead of regular memory. Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. _tdump_allocated prints the information to stderr by default. You can change the destination with the _set_crt_msg_handle function. Call _tdump_allocated at points in your code where you want a report of the currently allocated memory. For example, a good place to call _tdump_allocated is a point where most of the memory is already freed and you want to find a memory leak, such as at the end of a program. You can also use _tdump_allocated_delta to display information about only the tiled memory that was allocated since the previous call to _tdump_allocated or _tdump_allocated_delta. To use _tdump_allocated and the tiled debug versions of the memory management functions, specify the /Tm /Gt compiler options. the debug memory and tiled memory compiler options (/Tm /Gt). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. Return Value: There is no return value. ═══ Example of _tdump_allocated ═══ /************************************************************************ This example allocates some memory and then calls _tdump_allocated to display information about the allocated blocks. Note: You must compile this example with the /Tm /Gt options. ************************************************************************/ #include #include #include int main(void) { char *ptr1; if (NULL == (ptr1 = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr1, 'a', 5); _tdump_allocated(10); free(ptr1); return 0; /**************************************************************************** The output should be similar to : ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00080120 Size: 0x0000000A (10) This memory block was (re)allocated at line number 9 in _tdump_alloc.c. Memory contents: 61616161 61AAAAAA AAAA [aaaaaИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _tdump_allocated  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_theapmin - Release Unused Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  _dump_allocated - Get Information about Allocated Memory  _set_crt_msg_handle - Change Runtime Message Output Destination  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _udump_allocated - Get Information about Allocated Memory in Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide   ═══ 4.312. _tdump_allocated_delta - Get Information about Allocated Tiled Memory ═══ ═══ Format ═══ #include /* also in */ void _tdump_allocated_delta(int nbytes); ═══ Description ═══ Language Level: Extension For the heap you specify, _tdump_allocated_delta prints information to stderr about each tiled memory block allocated by a tiled debug memory management function (_debug_tmalloc and so on) since the last call to _tdump_allocated_delta or _tdump_allocated. _tdump_allocated_delta and _tdump_allocated print the same type of information to stderr, but _tdump_allocated displays information about all blocks that have been allocated since the start of your program. _tdump_allocated_delta works just like _dump_allocated_delta, except that it displays information about tiled memory instead of regular memory. Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. _tdump_allocated_delta prints the information to stderr by default. You can change the destination with the _set_crt_msg_handle function. To use _tdump_allocated_delta and the tiled debug versions of the memory management functions, specify the debug memory and tiled memory compiler options (/Tm /Gt). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. Return Value: There is no return value. ═══ Example of _tdump_allocated_delta ═══ /************************************************************************ This example allocates some memory and calls _tdump_allocated to print information about the allocated blocks. It then allocates more memory, and calls _tdump_allocated_delta to print information about the blocks allocated since the call to _tdump_allocated. Note: You must compile this example with the /Tm /Gt options. ************************************************************************/ #include #include int main(void) { char *ptr1, *ptr2; if (NULL == (ptr1 = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr1, 'a', 5); _tdump_allocated(10); if (NULL == (ptr2 = malloc(20))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr2, 'b', 5); _tdump_allocated_delta(10); free(ptr1); free(ptr2); return 0; /**************************************************************************** The output should be similar to : ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00080120 Size: 0x0000000A (10) This memory block was (re)allocated at line number 8 in _tdump_all_d.c. Memory contents: 61616161 61AAAAAA AAAA [aaaaaИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00080160 Size: 0x00000014 (20) This memory block was (re)allocated at line number 15 in _tdump_all_d.c. Memory contents: 62626262 62AAAAAA AAAA [bbbbbИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _tdump_allocated_delta  _dump_allocated_delta - Get Information about Allocated Memory  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_theapmin - Release Unused Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  _tdump_allocated - Get Information about Allocated Tiled Memory  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide   ═══ 4.313. _tell - Get Pointer Position ═══ ═══ Format ═══ #include long _tell(int handle); ═══ Description ═══ Language Level: Extension _tell gets the current position of the file pointer associated with handle. The position is the number of bytes from the beginning of the file. Return Value _tell 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 ═══ /************************************************************************ This example opens the file tell.dat. It then calls _tell to get the current position of the file pointer and report whether the operation is successful. The program then closes tell.dat. ************************************************************************/ #include #include #include #include #define FILENAME "tell.dat" int main(void) { long filePtrPos; int fh; printf("Creating file.\n"); system("echo Sample Program > " FILENAME); if (-1 == (fh = open(FILENAME, O_RDWR|O_APPEND))) { perror("Unable to open " FILENAME); remove(FILENAME); return EXIT_FAILURE; } /* Get the current file pointer position. */ if (-1 == (filePtrPos = _tell(fh))) { perror("Unable to tell"); close(fh); remove(FILENAME); return EXIT_FAILURE; } printf("File pointer is at position %d.\n", filePtrPos); close(fh); remove(FILENAME); return 0; /**************************************************************************** The output should be: Creating file. File pointer is at position 0. ****************************************************************************/ } ═══ Related Information ═══ Example of _tell  fseek - Reposition File Position  ftell - Get Current Position  lseek - Move File Pointer  ═══ 4.314. tempnam - Produce Temporary File Name ═══ ═══ Format ═══ #include char *tempnam(char *dir, char *prefix); ═══ Description ═══ Language Level: XGG4, Extension tempnam creates a temporary file name in another directory. The prefix is the prefix to the file name. tempnam tests for the existence of the file with the given name in the following directories, listed in order of precedence:  If the TMP environment variable is set and the directory specified by TMP exists, the directory is specified by TMP.  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.  If the dir argument is NULL, or dir is the name of nonexistent directory, the directory is pointed to by P_tmpdir (defined in ).  If P_tmpdir does not exist, the directory is the current working directory. Notes: 1. Because tempnam uses malloc to reserve space for the created file name, you must free this space when you no longer need it. 2. In earlier releases of C Set ++, tempnam began with an underscore (_tempnam). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _tempnam to tempnam for you. Return Value tempnam 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 ═══ /*************************************************************************** This example creates a temporary file name using the directory a:\tmp: ************************************************************************/ #include #include int main(void) { char *name1; if ((name1 = tempnam("d:\\tmp", "stq")) != NULL) printf("%s is safe to use as a temporary file.\n", name1); else { printf("Cannot create unique filename\n"); return EXIT_FAILURE; } return 0; /**************************************************************************** The output should be similar to: D:\tmp\stqU3CP2.C2T is safe to use as a temporary file. ****************************************************************************/ } ═══ Related Information ═══ Example of tempnam  malloc - Reserve Storage Block  _rmtmp - Remove Temporary Files  tmpfile - Create Temporary File  tmpnam - Produce Temporary File Name  ═══ 4.315. _tfree - Free Tiled Storage Block ═══ ═══ Format ═══ #include /* also in */ void _tfree(void *ptr); ═══ Description ═══ Language Level: Extension _tfree 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. _tfree works just like free except that it frees tiled memory instead of regular memory. The _tfree function can only be used to free memory allocated by the tiled memory management functions (_tcalloc and so on). To use _tfree, you must compile with the /Gt compiler option. This option maps all free calls to _tfree (you can also call _tfree explicitly). Note: The /Gt option maps all calls to regular memory management functions to their tiled versions. To prevent a call from being mapped, parenthesize the function name. A debug version of this function, _debug_tfree is also available. Use the /Tm option to map _tfree calls to _debug_tfree. For more information about memory management, see "Managing Memory" in the Programming Guide. Return Value There is no return value. ═══ Example of _tfree ═══ /************************************************************************ This example uses _tfree to free a block of tiled memory previously allocated by _tmalloc. Note: You must compile this example with the /Gt option to enable tiled memory. ************************************************************************/ #include int main(void) { char *memoryPtr; if (NULL != (memoryPtr = malloc(100))) puts("Successfully allocated 100 bytes of tiled memory."); else puts("Could not allocate tiled memory."); free(memoryPtr); return 0; /**************************************************************************** The output should be similar to : Successfully allocated 100 bytes of tiled memory. ****************************************************************************/ } ═══ Related Information ═══ Example of _tfree  free - Release Storage Blocks  _debug_free - Release Memory  _debug_tfree - Release Tiled Memory  _tcalloc - Reserve Tiled Storage Block  _theapmin - Release Unused Tiled Memory  _tmalloc - Reserve Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide   ═══ 4.316. _theap_check - Validate User Memory Heap ═══ ═══ Format ═══ #include /* also in */ void _theap_check(void); ═══ Description ═══ Language Level: Extension _theap_check checks all tiled memory blocks in the tiled runtime heap that have been allocated or freed using the tiled debug memory management functions (_debug_tcalloc, _debug_tmalloc, and so on). _theap_check checks that your program has not overwritten tiled memory that has been freed or that is outside the bounds of allocated tiled memory blocks. _theap_check works just like _heap_check except that it checks tiled memory instead of regular memory. When you call a tiled debug memory management function (such as _debug_tmalloc), it calls _theap_check automatically. You can also call _theap_check explicitly. Place calls to _theap_check throughout your code, especially in areas that you suspect have memory problems. Calling _theap_check frequently (explicitly or through the tiled debug memory functions) can increase your program's memory requirements and decrease its execution speed. To reduce the overhead of heap-checking, you can use the DDE4_HEAP_SKIP environment variable to control how often the functions check the heap. For example: SET DDE4_HEAP_SKIP=10 specifies that every tenth call to any debug memory function (regardless of the type or heap) checks the heap. Explicit calls to _theap_check are always performed. For more details on DDE4_HEAP_SKIP, see "Skipping Heap Checks" in the Programming Guide. To use _theap_check and the tiled debug versions of the memory management functions, specify the debug memory and tiled memory compiler options (/Tm /Gt). Note: The /Tm /Gt options map all calls to regular memory management functions to their tiled debug versions. To prevent a call from being mapped, parenthesize the function name. Return Value There is no return value. ═══ Example of _theap_check ═══ /************************************************************************ This example allocates and frees memory from the tiled runtime heap, and then calls _theap_check to check the heap. Note: You must compile this example with the /Gt /Tm options to map the memory management functions to their tiled debug versions. ************************************************************************/ #include #include int main(void) { char *ptr; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } *(ptr - 1) = 'x'; /* overwrites storage that was not allocated */ _theap_check(); free(ptr); return 0; /**************************************************************************** The output should be similar to : Header information of object 0x00080120 was overwritten at 0x0008011c. The first eight bytes of the memory block (in hex) are: AAAAAAAAAAAAAAAA. This memory block was (re)allocated at line number 8 in _theap_chec.c. Heap state was valid at line 8 of _theap_check.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _theap_check  _heap_check - Validate Default Memory Heap  _debug_tcalloc - Reserve and Initialize Tiled Memory  _debug_tfree - Release Tiled Memory  _debug_theapmin - Release Unused Tiled Memory  _debug_tmalloc - Reserve Tiled Memory  _debug_trealloc - Reallocate Tiled Memory Block  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide   ═══ 4.317. _theapmin - Release Unused Tiled Memory ═══ ═══ Format ═══ #include /* also in */ int _theapmin(void); ═══ Description ═══ Language Level: Extension _theapmin returns all unused tiled memory from the runtime heap to the operating system. _theapmin works just like _heapmin, except that it returns only tiled memory; _heapmin returns only regular memory. You can call _theapmin explicitly, or specify the /Gt compiler option to map all _heapmin calls to _theapmin. Note: When you specify /Gt, all calls to regular debug memory management functions (calloc and so on) are mapped to their tiled equivalents. However, if you parenthesize the function calls, they are not mapped. A debug version of this function, _debug_theapmin, is also available. Use the /Tm option to map _theapmin calls to _debug_theapmin. For more information about memory management, see "Managing Memory" in the Programming Guide. Return Value If successful, _theapmin returns 0; otherwise, it returns -1. ═══ Example of _theapmin ═══ /************************************************************************ This example allocates and frees memory from the tiled runtime heap, and then uses _theapmin to return any unused memory to the tiled heap. Note: You must compile this example with the /Gt option to enable tiled memory. ************************************************************************/ #include #include int main(void) { char *ptr; /* Allocate a large object from the system. */ if (NULL == (ptr = malloc(60000))) { puts("Could not allocate memory block.\n"); exit(EXIT_FAILURE); } memset(ptr, 'x', 60000); /* The free will keep large object in runtime. */ free(ptr); /* _theapmin will attempt to return the freed object to the system. */ if (0 != _theapmin()) { puts("_debug_theapmin returns failed.\n"); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _theapmin  _debug_heapmin - Release Unused Memory in the Default Heap  _debug_theapmin - Release Unused Tiled Memory  _heapmin - Release Unused Memory from Default Heap  _tcalloc - Reserve Tiled Storage Block  _tfree - Free Tiled Storage Block  _tmalloc - Reserve Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block  _uheapmin - Release Unused Memory in User Heap  Differentiating between Memory Management Functions  Memory Management in the Programming Guide   ═══ 4.318. _threadstore - Access Thread-Specific Storage ═══ ═══ Format ═══ #include void *_threadstore(void); ═══ Description ═══ Language Level: Extension _threadstore provides access to a private thread pointer that is initialized to NULL. You can assign any thread-specific data structure to this pointer. You can only use _threadstore in multithread programs (compiled with the /Gm+ option). Return Value _threadstore returns the address of the pointer to the defined thread storage space. ═══ Example of _threadstore ═══ /************************************************************************ This example uses _threadstore to point to storage that is local to the thread. It prints the address pointed to by _threadstore. Note: You must compile this example with the multithread option (/Gm+). ************************************************************************/ #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); return 0; } ═══ Related Information ═══ Example of _threadstore  _beginthread - Create New Thread  _endthread - Terminate Current Thread  ═══ 4.319. time - Determine Current Time ═══ ═══ Format ═══ #include time_t time(time_t *timeptr); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 time determines the current calendar time, which is not necessarily the local time localtime. Note: The time and date functions begin at 00:00 Universal Time, January 1, 1970. Return Value time 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. ═══ Example of time ═══ /************************************************************************ This example gets the time and assigns it to ltime. ctime then converts 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)); return 0; /**************************************************************************** The output should be similar to: The time is Thu Jan 12 11:38:37 1995 ****************************************************************************/ } ═══ Related Information ═══ Example of time  asctime - Convert Time to Character String  ctime - Convert Time to Character String  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  _strtime - Copy Time  ═══ 4.320. _tmalloc - Reserve Tiled Storage Block ═══ ═══ Format ═══ #include /* also in */ void _tmalloc(size_t size); ═══ Description ═══ Language Level: Extension _tmalloc allocates tiled memory for an object of size size, the value of which is indeterminate. To use _tmalloc, you must compile with the /Gt compiler option. This option maps all malloc calls to _tmalloc (you can also call _tmalloc explicitly). Note: The /Gt option maps all calls to regular memory management functions to their tiled versions. To prevent a call from being mapped, parenthesize the function name. _tmalloc works just like malloc except that it allocates tiled memory instead of regular memory. Tiled memory will not cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory from the VisualAge C++ runtime heap is limited to 512 MB per process. You can also create your own heaps of tiled memory, which can be larger in size. See Memory Management in the Programming Guide for more information. Memory allocated by _tmalloc can only be freed using _tfree. A debug version of this function, _debug_tmalloc, is also available. Use the /Tm option to map all _tmalloc calls to _debug_tmalloc. Return Value _tmalloc returns a pointer to the allocated tiled memory. If not enough storage is available, or if size is 0, _tmalloc returns NULL. ═══ Example of _tmalloc ═══ /************************************************************************ This example uses _tmalloc to allocate 100 bytes of tiled memory. Note: You must compile this example with the /Gt option to enable tiled memory. ************************************************************************/ #include int main(void) { char *memoryPtr; if (NULL != (memoryPtr = malloc(100))) puts("Successfully allocated 100 bytes of tiled memory."); else puts("Could not allocate tiled memory."); free(memoryPtr); return 0; /**************************************************************************** The output should be similar to: Successfully allocated 100 bytes of tiled memory. ****************************************************************************/ } ═══ Related Information ═══ Example of _tmalloc  _debug_malloc - Allocate Memory  _debug_tmalloc - Reserve Tiled Memory  malloc - Reserve Storage Block  _tcalloc - Reserve Tiled Storage Block  _tdump_allocated - Get Information about Allocated Tiled Memory  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _tfree - Free Tiled Storage Block  _trealloc - Reallocate Tiled Storage Block  _umalloc - Reserve Memory Blocks from User Heap  Differentiating between Memory Management Functions  "Managing Memory in the Programming Guide   ═══ 4.321. _tmem_init - Initialize Memory Functions for Subsystem DLL ═══ ═══ Format ═══ int _tmem_init(void); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _tmem_init initializes the tiled memory functions for subsystem DLLs. (If your subsystem DLL does not use tiled memory, call _rmem_init instead of _tmem_init.) Although subsystems do not require a runtime environment (and therefore do not call _CRT_init), they do require the library memory functions. For DLLs that do use a runtime environment, the memory functions are initialized with the environment by _CRT_init. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn initializes the tiled memory functions for you. However, if you are writing your own subsystem _DLL_InitTerm function (for example, to perform actions other than memory initialization and termination), you must call _tmem_init from your version of _DLL_InitTerm before you can call any other library functions. If your DLL contains C++ code, you must also call __ctordtorInit after _tmem_init to ensure that static constructors and destructors are initialized properly. __ctordtorInit is defined in the runtime startup code as: void __ctordtorInit(void); Return Value If the memory functions were successfully initialized, _tmem_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. ═══ Related Information ═══  Building Subsystem DLLs in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _CRT_term - Terminate DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ 4.322. _tmem_term - Terminate Memory Functions for Subsystem DLL ═══ ═══ Format ═══ int _tmem_term(void); /* no header file - defined in runtime startup code */ ═══ Description ═══ Language Level: Extension _tmem_term terminates the tiled memory functions for subsystem DLLs. It is only needed for DLLs that used tiled memory and that statically link to the runtime library. By default, all DLLs call the VisualAge C++ _DLL_InitTerm function, which in turn calls the termination functions for you. However, if you are writing your own _DLL_InitTerm function (for example, to perform actions other than memory initialization and termination), and your DLL statically links to the C runtime libraries, you need to call _rmem_term from your subsystem _DLL_InitTerm function. (For DLLs with a runtime environment, this termination is done by _CRT_term. If your subsystem DLL does not use tiled memory, call _rmem_term instead of _tmem_term.) If your DLL contains C++ code, you must also call __ctordtorTerm before you call _tmem_term to ensure that static constructors and destructors are terminated correctly. __ctordtorTerm is defined in the runtime startup code as: void __ctordtorTerm(void); Once you have called _tmem_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. Return Value _tmem_term returns 0 if the memory functions were successfully terminated. A return value of -1 indicates an error. ═══ Related Information ═══  Building Subsystem DLLs in the Programming Guide  _CRT_init - Initialize DLL Runtime Environment  _CRT_term - Terminate DLL Runtime Environment  _DLL_InitTerm - Initialize and Terminate DLL Environment  _rmem_init - Initialize Memory Functions for Subsystem DLL  _rmem_term - Terminate Memory Functions for Subsystem DLL  _tmem_init - Initialize Memory Functions for Subsystem DLL ═══ 4.323. tmpfile - Create Temporary File ═══ ═══ Format ═══ #include FILE *tmpfile(void); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 tmpfile creates a temporary binary file. The file is automatically removed when it is closed or when the program is terminated. tmpfile opens the temporary file in wb+ mode. Return Value tmpfile 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 ═══ /************************************************************************ This example creates a temporary file, and if successful, writes tmpstring to it. At program termination, the file is removed. ************************************************************************/ #include #include FILE *stream; char tmpstring[] = "This is the string to be temporarily written"; int main(void) { if (NULL == (stream = tmpfile())) { perror("Cannot make a temporary file"); return EXIT_FAILURE; } else fprintf(stream, "%s", tmpstring); return 0; } ═══ Related Information ═══ Example of tmpfile  fopen - Open Files  tmpnam - Produce Temporary File Name  tempnam - Produce Temporary File Name  _rmtmp - Remove Temporary Files  ═══ 4.324. tmpnam - Produce Temporary File Name ═══ ═══ Format ═══ #include char *tmpnam(char *string); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 tmpnam 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 . tmpnam 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. Return Value tmpnam returns a pointer to the name. If it cannot create a unique name; it returns NULL. ═══ 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"); return 0; /**************************************************************************** The output should be similar to: d:\tmp\acc00000.CTN can be used as a file name. ****************************************************************************/ } ═══ Related Information ═══ Example of tmpnam  fopen - Open Files  remove - Delete File  tempnam - Produce Temporary File Name  ═══ 4.325. _toascii - _tolower - _toupper - Convert Character ═══ ═══ Format ═══ #include int _toascii(int c); int _tolower(int c); int _toupper(int c); ═══ Description ═══ Language Level: Extension _toascii converts c to a character in the ASCII character set, by setting all but the low-order 7 bits to 0. If c already represents an ASCII character, _toascii does not change it. _tolower converts c to the corresponding lowercase letter, if possible. _toupper converts c to the corresponding uppercase letter, if possible. Important Use _tolower and _toupper only when you know that c is uppercase A to Z or lowercase a to z, respectively. Otherwise the results are undefined. These functions are not affected by the current locale. These are all macros, and do not correctly handle arguments with side effects. For portability, use the tolower and toupper functions defined by the ANSI/ISO standard, instead of the _tolower and _toupper macros. Return Value _toascii, _tolower, and _toupper return the possibly converted character c. If the character passed to _toascii is an ASCII character, _toascii returns the character unchanged. There is no error return. ═══ Example of _toascii - _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: 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 ═══ Example of _toascii - _tolower - _toupper  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  _iscsym - _iscsymf - Test Integer  tolower() - toupper() - Convert Character Case  towlower - towupper - Convert Wide Character Case  ═══ 4.326. tolower() - toupper() - Convert Character Case ═══ ═══ Format ═══ #include int tolower(int C); int toupper(int c); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 tolower converts the uppercase letter C to the corresponding lowercase letter. toupper converts the lowercase letter c to the corresponding uppercase letter. The character mapping is determined by the LC_CTYPE category of the current locale. Return Value Both functions return the converted character. If the character c does not have a corresponding lowercase of uppercase character, the functions return c unchanged. ═══ Example of tolower - toupper ═══ /************************************************************************ This example uses toupper and tolower to modify characters between code 0 and code 7f. ************************************************************************/ #include #include int main(void) { int ch; /* print hex values of characters */ for (ch = 0; ch <= 0x7f; ch++) { printf("toupper=%#04x\n", toupper(ch)); printf("tolower=%#04x\n", tolower(ch)); putchar('\n'); } return 0; } ═══ Related Information ═══ Example of tolower - toupper  isalnum to isxdigit - Test Integer Value  isascii - Test Integer Values  _iscsym - _iscsymf - Test Integer  _toascii - _tolower - _toupper - Convert Character  towlower - towupper - Convert Wide Character Case  ═══ 4.327. towlower - towupper - Convert Wide Character Case ═══ ═══ Format ═══ #include wint_t towlower(wint_t wc); wint_t towupper(wint_t wc); ═══ Description ═══ Language Level: ANSI 93, POSIX towlower converts the uppercase letter wc to the corresponding lowercase letter. towupper converts the lowercase letter wc to the corresponding uppercase letter. The character mapping is determined by the LC_CTYPE category of current locale. Return Value Both functions return the converted character. If the wide character wc does not have a corresponding lowercase or uppercase character, the functions return wc unchanged. ═══ Example of towlower and towupper ═══ /************************************************************************ This example uses towlower and towupper to convert characters between 0 and 0x7f. ************************************************************************/ #include #include int main(void) { wint_t w_ch; for (w_ch = 0; w_ch <= 0x7f; w_ch++) { printf ("towupper : %#04x %#04x, ", w_ch, towupper(w_ch)); printf ("towlower : %#04x %#04x\n", w_ch, towlower(w_ch)); } return 0; /**************************************************************************** The output should be similar to : . : towupper : 0x41 0x41, towlower : 0x41 0x61 towupper : 0x42 0x42, towlower : 0x42 0x62 towupper : 0x43 0x43, towlower : 0x43 0x63 towupper : 0x44 0x44, towlower : 0x44 0x64 towupper : 0x45 0x45, towlower : 0x45 0x65 . : towupper : 0x61 0x41, towlower : 0x61 0x61 towupper : 0x62 0x42, towlower : 0x62 0x62 towupper : 0x63 0x43, towlower : 0x63 0x63 towupper : 0x64 0x44, towlower : 0x64 0x64 towupper : 0x65 0x45, towlower : 0x65 0x65 : ****************************************************************************/ } ═══ Related Information ═══ Example of towlower - towupper   tolower() - toupper() - Convert Character Case  _toascii - _tolower - _toupper - Convert Character ═══ 4.328. _trealloc - Reallocate Tiled Storage Block ═══ ═══ Format ═══ #include /* also in */ void _trealloc(void *ptr, size_t size); ═══ Description ═══ Language Level: Extension _trealloc 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. To use _trealloc, you must compile with the /Gt compiler option. This option maps all realloc calls to _trealloc (you can also call _trealloc explicitly). Note: The /Gt option maps all calls to regular memory management functions to their tiled versions. To prevent a call from being mapped, parenthesize the function name. _trealloc works just like realloc except that it reallocates tiled memory instead of regular memory. Tiled memory will not to cross 64K boundaries, as long as the object is less than 64K in size. Objects larger than 64K in size are aligned on 64K boundaries, but will also cross 64K boundaries. If you have objects that may be accessed by 16-bit code, you should store them in tiled memory. Tiled memory from the VisualAge C++ runtime heap is limited to 512 MB per process. You can also create your own heaps of tiled memory, which can be larger in size. See Memory Management in the Programming Guide for more information. _trealloc can only reallocate memory 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. A debug version of this function, _debug_trealloc, is also available. Use the /Tm compiler option to map all _trealloc calls to _debug_trealloc. Return Value _trealloc returns a pointer to the reallocated tiled memory. If not enough storage is available or if size is 0, _trealloc returns NULL and the original block does not change. ═══ Example of _trealloc ═══ /************************************************************************ This example uses _trealloc to reallocate a block of tiled memory previously allocated by _tmalloc. Note: You must compile this example with the /Gt option to enable tiled memory. ************************************************************************/ #include int main(void) { char *memoryPtr; if (NULL == (memoryPtr = malloc(100))) { puts("Could not allocate tiled memory."); exit(EXIT_FAILURE); } if (NULL == (memoryPtr = realloc(memoryPtr, 1000))) { puts("Unable to reallocate tiled memory."); exit(EXIT_FAILURE); } else puts("Successfully reallocated 1000 bytes of tiled memory."); free(memoryPtr); return 0; /**************************************************************************** The output should be similar to: Successfully reallocated 1000 bytes of tiled memory. ****************************************************************************/ } ═══ Related Information ═══ Example of _trealloc  _debug_calloc - Allocate and Initialize Memory  _debug_trealloc - Reallocate Tiled Memory Block  _msize - Return Number of Bytes Allocated  realloc - Change Reserved Storage Block Size  _tcalloc - Reserve Tiled Storage Block  _tmalloc - Reserve Tiled Storage Block  _tfree - Free Tiled Storage Block  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide   ═══ 4.329. tzset - Assign Values to Locale Information ═══ ═══ Format ═══ #include void tzset(void); ═══ Description ═══ Language Level: XPG4, Extension tzset 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 putenv before calling tzset. Notes:  In earlier releases of C Set ++, tzset began with an underscore (_tzset). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _tzset to tzset for you.  The time and date functions begin at 00:00 Coordinated Universal Time, January 1, 1970. Return Value There is no return value. ═══ Example of tzset ═══ /************************************************************************ This example uses putenv and tzset to set the time zone to Central Time. ************************************************************************/ #include #include #include int main(void) { time_t currentTime; struct tm *ts; /* Get the current time */ (void)time(¤tTime); printf("The GMT time is %s", 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"); } printf("**** Changing to Central Time ****\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"); } return 0; /**************************************************************************** The output should be similar to: The GMT time is Fri Jan 13 21:49:26 1995 The local time is Fri Jan 13 16:49:26 1995 Daylight Saving Time is not in effect. **** Changing to Central Time **** The local time is Fri Jan 13 15:49:26 1995 Daylight Saving Time is not in effect. ****************************************************************************/ } ═══ Related Information ═══ Example of tzset  asctime - Convert Time to Character String  _ftime - Store Current Time  gmtime - Convert Time  localtime - Convert Time  mktime - Convert Local Time  putenv - Modify Environment Variables  strftime - Convert to Formatted Time  time - Determine Current Time  ═══ 4.330. _uaddmem - Add Memory to a Heap ═══ ═══ Format ═══ #include Heap_t _uaddmem(Heap_t heap, void *block, size_t size, int clean); ═══ Description ═══ Language Level: Extension _uaddmem adds a block of memory of size bytes into the specified user heap (created with _ucreate). Before calling _uaddmem, you must first get the block from the operating system, typically by using an OS/2 API like DosAllocMem or by allocating it statically. (See the Control Program Guide and Reference for details on OS/2 APIs for memory management.) If the memory block has been initialized to 0, specify _BLOCK_CLEAN for the clean parameter. If not, specify !_BLOCK_CLEAN. (This information makes calloc and _ucalloc more efficient). Note: Memory returned by DosAllocMem is initialized to 0. For fixed-size heaps, you must return all the blocks you added with _uaddmem to the system. (For expandable heaps, these blocks are returned by your release_fn when you call _udestroy.) For more information about creating and using heaps, see "Managing Memory" in the Programming Guide. Note: For every block of memory you add, a small number of bytes from it are used to store internal information. To reduce the total amount of overhead, it is better to add a few large blocks of memory than many small blocks. Return Value _uaddmem returns a pointer to the heap the memory was added to. If the heap specified is not valid, _uaddmem returns NULL. ═══ Example of _uaddmem ═══ /************************************************************************ The following example creates a heap myheap, and then uses _uaddmem to add memory to it. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include int main(void) { void *initial_block, *extra_chunk; APIRET rc; Heap_t myheap; char *p1, *p2; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem for initial block failed: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create a fixed size heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, NULL, NULL))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } p1 = _umalloc(myheap, 100); /* Call DosAllocMem to get another block of memory */ if (0 != (rc = DosAllocMem(&extra_chunk, 10 * 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem for extra chunk failed: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Add the second chunk of memory to user heap */ if (myheap != _uaddmem(myheap, extra_chunk, 10 * 65536, _BLOCK_CLEAN)) { puts("_uaddmem failed."); exit(EXIT_FAILURE); } p2 = _umalloc(myheap, 100000); free(p1); free(p2); if (0 != _uclose(myheap)) { puts("_uclose failed"); exit(EXIT_FAILURE); } if (0 != DosFreeMem(initial_block) || 0 != DosFreeMem(extra_chunk)) { puts("DosFreeMem error."); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _uaddmem  _ucreate - Create a Memory Heap  _udestroy - Destroy a Heap  _uheapmin - Release Unused Memory in User Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.331. _ucalloc - Reserve and Initialize Memory from User Heap ═══ ═══ Format ═══ #include void *_ucalloc(Heap_t heap, size_t num, size_t size); ═══ Description ═══ Language Level: Extension _ucalloc allocates memory for an array of num elements, each of length size bytes, from the heap you specify. It then initializes all bits of each element to 0. _ucalloc works just like calloc except that you specify the heap to use; calloc always allocates from the default heap. A debug version of this function, _debug_ucalloc, is also provided. If the heap does not have enough memory for the request, _ucalloc calls the getmore_fn that you specified when you created the heap with _ucreate. To reallocate or free memory allocated with _ucalloc, use the non-heap-specific realloc and free. These functions always check what heap the memory was allocated from. Return Value _ucalloc returns a pointer to the reserved space. If size or num was specified as zero, or if your getmore_fn cannot provide enough memory, _ucalloc returns NULL. Passing _ucalloc a heap that is not valid results in undefined behavior. ═══ Example of _ucalloc ═══ /************************************************************************ This example creates a heap myheap and then uses _ucalloc to allocate memory from it. ************************************************************************/ #include #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _ucalloc(myheap, 100, 1))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } memset(ptr, 'x', 10); free(ptr); return 0; } ═══ Related Information ═══ Example of _ucalloc  calloc - Reserve and Initialize Storage  _debug_ucalloc - Reserve and Initialize Memory from User Heap  free - Release Storage Blocks  realloc - Change Reserved Storage Block Size  _ucreate - Create a Memory Heap  _umalloc - Reserve Memory Blocks from User Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.332. _uclose - Close Heap from Use ═══ ═══ Format ═══ #include int _uclose(Heap_t heap); ═══ Description ═══ Language Level: Extension _uclose closes a heap when a process will not use it again. After you close a heap, any attempt in the current process to allocate or return memory to it will have undefined results. _uclose affects only the current process; if the heap is shared, other processes may still be able to access it. Once you have closed the heap, use _udestroy to destroy it and return all its memory to the operating system. Note: If the heap is shared, you must close it in all processes that share it before you destroy it, or undefined results will occur. You cannot close the VisualAge C++ runtime heap (_RUNTIME_HEAP). For more information about creating and using heaps, see "Managing Memory" in the Programming Guide. Return Value: If successful, _uclose returns 0. A nonzero return value indicates failure. Passing _uclose a heap that is not valid results in undefined behavior. ═══ Example of _uclose ═══ /************************************************************************ This example creates and opens a heap, and then performs operations on it. It then calls _uclose to close the heap before destroying it. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include int main(void) { void *initial_block; APIRET rc; Heap_t myheap; char *p; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create a fixed size heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, NULL, NULL))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } p = _umalloc(myheap, 100); memset(p, 'x', 10); free(p); if (0 != _uclose(myheap)) { puts("_uclose failed"); exit(EXIT_FAILURE); } if (0 != (rc = DosFreeMem(initial_block))) { printf("DosFreeMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _uclose  _uopen - Open Heap for Use  _udestroy - Destroy a Heap  _ucreate - Create a Memory Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.333. _ucreate - Create a Memory Heap ═══ ═══ Format ═══ #include Heap_t _ucreate(void *block, size_t initsz, int clean, int memtype, void *(*getmore_fn)(Heap_t, size_t *, int *) void (*release_fn)(Heap_t, void *, size_t); ═══ Description ═══ Language Level: Extension _ucreate creates your own memory heap that you can allocate and free memory from, just like the VisualAge C++ runtime heap. Before you call _ucreate, you must first get the initial block of memory for the heap. You can get this block by calling an OS/2 API (such as DosAllocMem or or DosAllocSharedMem) or by statically allocating it. (See the CP Programming Guide and Reference for more information on the OS/2 APIs.) Note: You must also return this initial block of memory to the system after you destroy the heap. When you call _ucreate, you pass it the following parameters: block The pointer to the initial block you obtained. initsz The size of the initial block, which must be at least _HEAP_MIN_SIZE bytes (defined in ). If you are creating a fixed-size heap, the size must be large enough to satisfy all memory requests your program will make of it. clean The macro _BLOCK_CLEAN, if the memory in the block has been initialized to 0, or !_BLOCK_CLEAN, if the memory has not been touched. This improves the efficiency of _ucalloc; if the memory is already initialized to 0, _ucalloc does not need to initialize it. Note: DosAllocMem initializes memory to 0 for you. You can also use memset to initialize the memory; however, memset also commits all the memory at once, an action that could slow overall performance. memtype A macro indicating the type of memory in your heap: _HEAP_REGULAR (regular) or _HEAP_TILED (tiled). If you want the memory to be shared, specify _HEAP_SHARED as well (for example, _HEAP_REGULAR | _HEAP_SHARED). Tiled memory blocks will not cross 64K boundaries, so the data in them can be used in 16-bit programs. Shared memory can be shared between different processes. For more information on different types of memory, see the Programming Guide and the Control Program Guide and Reference. Note: Make sure that when you get the initial block, you request the same type of memory that you specify for memtype. getmore_fn A function you provide to get more memory from the system (typically using OS/2 APIs or static allocation). To create a fixed-size heap, specify NULL for this parameter. release_fn A function you provide to return memory to the system (typically using DosFreeMem). To create a fixed-size heap, specify NULL for this parameter. If you create a fixed-size heap, the initial block of memory must be large enough to satisfy all allocation requests made to it. Once the block is fully allocated, further allocation requests to the heap will fail. If you create an expandable heap, the getmore_fn and release_fn allow your heap to expand and shrink dynamically. When you call _umalloc (or a similar function) for your heap, if not enough memory is available in the block, it calls the getmore_fn you provide. Your getmore_fn then gets more memory from the system and adds it to the heap, using any method you choose. Your getmore_fn must have the following prototype: void *(*getmore_fn)(Heap_t uh, size_t *size, int *clean); where: uh Is the heap to get memory for. size Is the size of the allocation request passed by _umalloc. You probably want to return enough memory at a time to satisfy several allocations; otherwise, every subsequent allocation has to call getmore_fn. You should return multiples of 64K (the smallest size that DosAllocMem returns). Make sure you update the size parameter if you return more than the original request. clean Within getmore_fn, you must set this variable either to _BLOCK_CLEAN, to indicate that you initialized the memory to 0, or to !_BLOCK_CLEAN, to indicate that the memory is untouched. Note: Make sure your getmore_fn allocates the right type of memory for the heap. When you call _uheapmin to coalesce the heap or _udestroy to destroy it, these functions call the release_fn you provide to return the memory to the system. function. Your release_fn must have the following prototype: void (*release_fn)(Heap_t uh, void *block, size_t size); The heap uh the block is from, the block to be returned, and its size are passed to release_fn by _uheapmin or _udestroy. For more information about creating and using heaps, see the "Managing Memory" in the Programming Guide. Return Value: If successful, _ucreate returns a pointer to the heap created. If errors occur, _ucreate returns NULL. ═══ Example of _ucreate ═══ /************************************************************************ This example uses _ucreate to create an expandable heap. The functions for expanding and shrinking the heap are get_fn and release_fn. The program then opens the heap and performs operations on it, and then closes and destroys the heap. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include static void *get_fn(Heap_t usrheap, size_t *length, int *clean) { void *p; /* Round up to the next chunk size */ *length = ((*length) / 65536) * 65536 + 65536; *clean = _BLOCK_CLEAN; DosAllocMem(&p, *length, PAG_COMMIT | PAG_READ | PAG_WRITE); return (p); } static void release_fn(Heap_t usrheap, void *p, size_t size) { DosFreeMem(p); return; } int main(void) { void *initial_block; APIRET rc; Heap_t myheap; char *ptr; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create an expandable heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, get_fn, release_fn))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } /* Force user heap to grow */ ptr = _umalloc(myheap, 100000); _uclose(myheap); if (0 != _udestroy(myheap, _FORCE)) { puts("_udestroy failed."); exit(EXIT_FAILURE); } if (0 != (rc = DosFreeMem(initial_block))) { printf("DosFreeMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _ucreate  _uaddmem - Add Memory to a Heap  _ucalloc - Reserve and Initialize Memory from User Heap  _uclose - Close Heap from Use  _udestroy - Destroy a Heap  _uheapmin - Release Unused Memory in User Heap  _umalloc - Reserve Memory Blocks from User Heap  _uopen - Open Heap for Use  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.334. _udefault - Change the Default Heap ═══ ═══ Format ═══ #include Heap_t _udefault(Heap_t heap); ═══ Description ═══ Language Level: Extension _udefault makes the heap you specify become the default heap. All calls to memory management functions that do not specify a heap (including malloc and calloc) then allocate memory from the heap. This change affects only the thread where you called _udefault. The initial default heap is the VisualAge C++ runtime heap. To restore or explicitly set the VisualAge C++ runtime heap as the default, call _udefault with the argument _RUNTIME_HEAP. You can also use _udefault to find out which heap is being used as the default by specifying NULL for the heap parameter. The default heap remains the same. For more information about creating and using heaps, see "Managing Memory" in the Programming Guide. Return Value: _udefault returns a pointer to the former default heap. You can save this pointer and use it later to restore the original heap. If the call is unsuccessful, _udefault returns NULL. Passing _udefault a heap that is not valid results in undefined behavior. ═══ Example of _udefault ═══ /************************************************************************ This example creates a fixed-size heap myheap and uses _udefault to make it the default heap. The call to malloc then allocates memory from myheap. The second call to _udefault restores the original default heap. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include int main(void) { void *initial_block; APIRET rc; Heap_t myheap, old_heap; char *p; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create a fixed size heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, NULL, NULL))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } /* myheap is used as default heap */ old_heap = _udefault(myheap); /* malloc will allocate memory from myheap */ p = malloc(100); memset(p, 'x', 10); /* Restore original default heap */ _udefault(old_heap); free(p); if (0 != _uclose(myheap)) { puts("_uclose failed"); exit(EXIT_FAILURE); } if (0 != (rc = DosFreeMem(initial_block))) { printf("DosFreeMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _udefault  calloc - Reserve and Initialize Storage  malloc - Reserve Storage Block  _mheap - Query Memory Heap for Allocated Object  _ucreate - Create a Memory Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.335. _udestroy - Destroy a Heap ═══ ═══ Format ═══ #include int _udestroy(Heap_t heap, int force); ═══ Description ═══ Language Level: Extension _udestroy destroys the heap you specify. It also returns the heap's memory to the system by calling the release_fn you supplied to _ucreate when you created the heap. If you did not supply a release_fn, _udestroy simply marks the heap as destroyed so no further operations can be performed. You must then return all the memory in the heap to the system. Note: Whether or not you provide a release_fn, you must always return the initial block of memory (that you provided to _ucreate) to the system. The force parameter controls the behavior of _udestroy if all allocated objects from the heap have not been freed. If you specify _FORCE for this parameter, _udestroy destroys the heap regardless of whether allocated objects remain in that process or in any other process that shares the heap. If you specify !_FORCE, the heap will not be destroyed if any objects are still allocated from it. Typically, you call _uclose to close the heap before you destroy it. After you have destroyed a heap, any attempt to access it will have undefined results. You cannot destroy the VisualAge C++ runtime heap (_RUNTIME_HEAP). Return Value _udestroy returns 0 whether the heap was destroyed or not. If the heap passed to it is not valid, _udestroy returns a nonzero value. ═══ Example of _udestroy ═══ /************************************************************************ This example creates and opens a heap, performs operations on it, and then closes it. The program then calls _udestroy with the _FORCE parameter to force the destruction of the heap. _udestroy calls release_fn to return the memory to the system. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include static void *get_fn(Heap_t usrheap, size_t *length, int *clean) { void *p; /* Round up to the next chunk size */ *length = ((*length) / 65536) * 65536 + 65536; *clean = _BLOCK_CLEAN; DosAllocMem(&p, *length, PAG_COMMIT | PAG_READ | PAG_WRITE); return (p); } static void release_fn(Heap_t usrheap, void *p, size_t size) { DosFreeMem(p); return; } int main(void) { void *initial_block; APIRET rc; Heap_t myheap; char *ptr; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create an expandable heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, get_fn, release_fn))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } /* Force user heap to grow */ ptr = _umalloc(myheap, 100000); _uclose(myheap); if (0 != _udestroy(myheap, _FORCE)) { puts("_udestroy failed."); exit(EXIT_FAILURE); } if (0 != (rc = DosFreeMem(initial_block))) { printf("DosFreeMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _udestroy  _uaddmem - Add Memory to a Heap  _ucreate - Create a Memory Heap  _uopen - Open Heap for Use  _uclose - Close Heap from Use  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  ═══ 4.336. _udump_allocated - Get Information about Allocated Memory in Heap ═══ ═══ Format ═══ #include void _udump_allocated(Heap_t heap, int nbytes); ═══ Description ═══ Language Level: Extension For the heap you specify, _udump_allocated prints information to stderr about each memory block that is currently allocated and was allocated using the debug memory management functions (_debug_ucalloc, _debug_umalloc, and so on). _udump_allocated works just like _dump_allocated, except that you specify the heap to use; _dump_allocated always displays information about the default heap. Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. _udump_allocated prints the information to stderr by default. You can change the destination with the _set_crt_msg_handle function. Call _udump_allocated at points in your code where you want a report of the currently allocated memory. For example, a good place to call _udump_allocated is a point where most of the memory is already freed and you want to find a memory leak, such as at the end of a program. You can also use _udump_allocated_delta to display information about only the memory that was allocated since the previous call to _udump_allocated or _udump_allocated_delta. To use _udump_allocated and the debug versions of the memory management functions, specify the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Return Value: There is no return value. Passing _udump_allocated a heap that is not valid results in undefined behavior. ═══ Example of _udump_allocated ═══ /************************************************************************ This example creates a heap, performs some operations on it, and then calls _udump_allocated to print out information about the allocated memory blocks. Note: You must compile this example with the /Tm option to enable the debug memory management functions. ************************************************************************/ #include #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _umalloc(myheap, 10))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } memset(ptr, 'a', 5); _udump_allocated(myheap, 10); free(ptr); return 0; /**************************************************************************** The output should be similar to : ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00073890 Size: 0x0000000A (10) This memory block was (re)allocated at line number 14 in _udump_alloc.c. Memory contents: 61616161 61AAAAAA AAAA [aaaaaИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _udump_allocated  _debug_ucalloc - Reserve and Initialize Memory from User Heap  _debug_umalloc - Reserve Memory Blocks from User Heap  _debug_realloc - Reallocate Memory Block  _debug_free - Release Memory  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _set_crt_msg_handle - Change Runtime Message Output Destination  _tdump_allocated - Get Information about Allocated Tiled Memory  _udump_allocated_delta - Get Information about Allocated Memory in Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.337. _udump_allocated_delta - Get Information about Allocated Memory in Heap ═══ ═══ Format ═══ #include void _udump_allocated_delta(Heap_t heap, int nbytes); ═══ Description ═══ Language Level: Extension For the heap you specify, _udump_allocated_delta prints information to stderr about each memory block allocated by a debug memory management function (_debug_umalloc and so on) since the last call to _udump_allocated_delta or _udump_allocated. _udump_allocated_delta and _udump_allocated print the same type of information to stderr, but _udump_allocated displays information about all blocks that have been allocated since the start of your program. _udump_allocated_delta works just like _dump_allocated_delta, except that you specify the heap to use; _dump_allocated_delta always displays information about the default heap. Use nbytes to specify how many bytes of each memory block are to be printed. If nbytes is: Negative value Prints all bytes of each block. 0 Prints no bytes. Positive value Prints the specified number of bytes or the entire block, whichever is smaller. _udump_allocated_delta prints the information to stderr by default. You can change the destination with the _set_crt_msg_handle function. To use _udump_allocated_delta and the debug versions of the memory management functions, specify the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Return Value: There is no return value. Passing _udump_allocated_delta a heap that is not valid results in undefined behavior. ═══ Example of _udump_allocated_delta ═══ /************************************************************************ This example creates a heap and allocates memory from it. It then calls _udump_allocated to display information about the allocated memory. After performing more memory operations, it calls _udump_allocated_delta to display information about the memory allocated since the call to _udump_allocated Note: You must compile this example with the /Tm option to enable the debug memory management functions. ************************************************************************/ #include #include #include #include int main(void) { Heap_t myheap; char *ptr1, *ptr2; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr1 = _umalloc(myheap, 10))) { puts("Cannot allocate first memory block from user heap."); exit(EXIT_FAILURE); } memset(ptr1, 'a', 5); _udump_allocated(myheap, 10); if (NULL == (ptr2 = _umalloc(myheap, 20))) { puts("Cannot allocate second memory block from user heap."); exit(EXIT_FAILURE); } memset(ptr2, 'b', 5); printf("\nResults of _udump_allocated_delta are:\n"); _udump_allocated_delta(myheap, 10); free(ptr1); free(ptr2); return 0; /**************************************************************************** The output should be similar to : ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x00073890 Size: 0x0000000A (10) This memory block was (re)allocated at line number 14 in _udump_alloc_d.c. Memory contents: 61616161 61AAAAAA AAAA [aaaaaИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Results of _udump_allocated_delta are: ------------------------------------------------------------------------------- START OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- Address: 0x000738D0 Size: 0x00000014 (20) This memory block was (re)allocated at line number 21 in _udump_alloc_d.c. Memory contents: 62626262 62AAAAAA AAAA [bbbbbИИИИИ ] ------------------------------------------------------------------------------- END OF DUMP OF ALLOCATED MEMORY BLOCKS ------------------------------------------------------------------------------- ****************************************************************************/ } ═══ Related Information ═══ Example of _udump_allocated_delta  _dump_allocated - Get Information about Allocated Memory  _dump_allocated_delta - Get Information about Allocated Memory  _debug_umalloc - Reserve Memory Blocks from User Heap  _debug_ucalloc - Reserve and Initialize Memory from User Heap  _debug_realloc - Reallocate Memory Block  _set_crt_msg_handle - Change Runtime Message Output Destination  _tdump_allocated_delta - Get Information about Allocated Tiled Memory  _udump_allocated - Get Information about Allocated Memory in Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.338. _uheap_check - Validate User Memory Heap ═══ ═══ Format ═══ #include void _uheap_check(Heap_t heap); ═══ Description ═══ Language Level: Extension _uheap_check checks all memory blocks in the heap you specify that have been allocated or freed using the heap-specific debug versions of the memory management functions (_debug_ucalloc, _debug_umalloc, and so on). _uheap_check checks that your program has not overwritten freed memory blocks or memory outside the bounds of allocated blocks. _uheap_check works just like _heap_check, except that you specify the heap to check; _heap_check always checks the default heap. When you call a heap-specific debug memory management function (such as _debug_umalloc), it calls _uheap_check automatically. You can also call _uheap_check explicitly. Place calls to _uheap_check throughout your code, especially in areas that you suspect have memory problems. Calling _uheap_check frequently (explicitly or through the tiled debug memory functions) can increase your program's memory requirements and decrease its execution speed. To reduce the overhead of heap-checking, you can use the DDE4_HEAP_SKIP environment variable to control how often the functions check the heap. For example: SET DDE4_HEAP_SKIP=10 specifies that every tenth call to any debug memory function (regardless of the type or heap) checks the heap. Explicit calls to _uheap_check are always performed. For more details on DDE4_HEAP_SKIP, see "Skipping Heap Checks" in the Programming Guide. To use _uheap_check and the debug versions of the memory management functions, specify the debug memory (/Tm) compiler option. Note: The /Tm option maps all calls to memory management functions (including tiled and heap-specific versions) to their debug counterparts. To prevent a call from being mapped, parenthesize the function name. Return Value There is no return value. ═══ Example of _uheap_check ═══ /************************************************************************ This example creates a heap and allocates memory from it. It then calls _uheap_check to check the the memory in the heap. Note: You must compile this example with the /Tm option to map the _ucalloc calls to _debug_ucalloc. ************************************************************************/ #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _ucalloc(myheap, 100, 1))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } memset(ptr, 'x', 105); /* overwrite storage that was not allocated */ _uheap_check(myheap); free(ptr); return 0; /**************************************************************************** The output should be similar to : End of allocated object 0x00073890 was overwritten at 0x000738f4. The first eight bytes of the memory block (in hex) are: 7878787878787878. This memory block was (re)allocated at line number 13 in _uheap_check.c. Heap state was valid at line 13 of _uheap_check.c. Memory error detected at line 19 of _uheap_check.c. ****************************************************************************/ } ═══ Related Information ═══ Example of _uheap_check  _heap_check - Validate Default Memory Heap  _debug_ucalloc - Reserve and Initialize Memory from User Heap  _debug_umalloc - Reserve Memory Blocks from User Heap  _debug_realloc - Reallocate Memory Block  _debug_free - Release Memory  _uheapchk - Validate Memory Heap  _uheapset - Validate and Set Memory Heap  _uheap_walk - Return Information about Memory Heap  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.339. _uheapchk - Validate Memory Heap ═══ ═══ Format ═══ #include int _uheapchk(Heap_t heap); ═══ Description ═══ Language Level: Extension _uheapchk checks the heap you specify for minimal consistency by checking all allocated and freed objects on the heap. _uheapchk works just like _heapchk, except that you specify the heap to check; _heapchk always checks the default heap. Note: Using the _uheapchk, _uheapset, and _uheap_walk functions (and their equivalents for the default heap) may add overhead to each object allocated from the heap. Return Value _uheapchk returns one of the following values, defined in both and : _HEAPBADBEGIN The heap specifed is not valid. It may have been closed or destroyed. _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. ═══ Example of _uheapchk ═══ /************************************************************************ This example creates a heap and performs memory operations on it. It then calls _uheapchk to validate the heap. ************************************************************************/ #include #include #include int main(void) { Heap_t myheap; char *ptr; int rc; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _ucalloc(myheap, 100, 1))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } *(ptr - 1) = 'x'; /* overwrite storage that was not allocated */ if (_HEAPOK != (rc = _uheapchk(myheap))) { switch(rc) { case _HEAPEMPTY: puts("The heap has not been initialized."); break; case _HEAPBADNODE: puts("A memory node is corrupted or the heap is damaged."); break; case _HEAPBADBEGIN: puts("The heap specified is not valid."); break; } exit(rc); } free(ptr); return 0; /**************************************************************************** The output should be similar to : A memory node is corrupted or the heap is damaged. ****************************************************************************/ } ═══ Related Information ═══ Example of _uheapchk  _heapchk - Validate Default Memory Heap  _heapmin - Release Unused Memory from Default Heap  _uheapset - Validate and Set Memory Heap  _uheap_walk - Return Information about Memory Heap  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.340. _uheapmin - Release Unused Memory in User Heap ═══ ═══ Format ═══ #include int _uheapmin(Heap_t heap); ═══ Description ═══ Language Level: Extension _uheapmin returns all unused memory blocks from the heap you specify to the operating system. _uheapmin works just like _heapmin, except that you specify the heap to use; _heapmin always uses the default heap. A debug version of this function, _debug_uheapmin, is also provided. To return the memory, _uheapmin calls the release_fn you supplied when you created the heap with _ucreate. If you did not supply a release_fn, _uheapmin has no effect and simply returns 0. Return Value If successful, _uheapmin returns 0. A nonzero return value indicates failure. Passing _uheapmin a heap that is not valid has undefined results. ═══ Example of _uheapmin ═══ /************************************************************************ This example creates a heap and then allocates and frees a large block of memory from it. It then calls _uheapmin to return free blocks of memory to the system. ************************************************************************/ #include #include int main(void) { if (_heapmin()) printf("_heapmin failed.\n"); else printf("_heapmin was successful.\n"); return 0; /**************************************************************************** The output should be: _heapmin was successful. ****************************************************************************/ } ═══ Related Information ═══ Example of _heapmin  _heapmin - Release Unused Memory from Default Heap  _debug_uheapmin - Release Unused Memory in User Heap  _theapmin - Release Unused Tiled Memory  _ucreate - Create a Memory Heap  Differentiating between Memory Management Functions  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.341. _uheapset - Validate and Set Memory Heap ═══ ═══ Format ═══ #include int _heapset(Heap_t heap, unsigned int fill); ═══ Description ═══ Language Level: Extension _uheapset checks the heap you specify for minimal consistency by checking all allocated and freed objects on the heap (similar to _uheapchk). It then sets each byte of the heap's free objects to the value of fill. Using _uheapset can help you locate problems where your program continues to use a freed pointer to an object. After you set the free heap to a specific value, when your program tries to interpret the set values in the freed object as data, unexpected results occur, indicating a problem. _uheapset works just like _heapset, except that you specify the heap to check; _heapset always checks the default heap. Note: Using the _uheapchk, _uheapset, and _uheap_walk functions (and their equivalents for the default heap) may add overhead to each object allocated from the heap. Return Value _uheapset returns one of the following values, defined in both and : _HEAPBADBEGIN The heap specified is not valid. It may have been closed or destroyed. _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. ═══ Example of _uheapset ═══ /************************************************************************ This example creates a heap and allocates and frees memory from it. It then calls _uheapset to set the freed memory to a value. ************************************************************************/ #include #include #include int main (void) { char *ptr; int rc; if (NULL == (ptr = malloc(10))) { puts("Could not allocate memory block."); exit(EXIT_FAILURE); } memset(ptr,'A',5); free(ptr); if (_HEAPOK != (rc = _heapset('X'))) { switch(rc) { case _HEAPEMPTY: puts("The heap has not been initialized."); break; case _HEAPBADNODE: puts("A memory node is corrupted or the heap is damaged."); break; case _HEAPBADBEGIN: puts("The heap specified is not valid."); break; } exit(rc); } return 0; } ═══ Related Information ═══ Example of _heapset  _heapmin - Release Unused Memory from Default Heap  _heapset - Validate and Set Default Heap  _uheapchk - Validate Memory Heap  _uheap_walk - Return Information about Memory Heap  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.342. _uheap_walk - Return Information about Memory Heap ═══ ═══ Format ═══ #include int _uheap_walk(Heap_t heap, int (*callback_fn)(const void *object, size_t size, int flag, int status, const char* file, int line) ); ═══ Description ═══ Language Level: Extension _uheap_walk traverses the heap you specify, and, for each allocated or freed object, it calls the callback_fn function that you provide. _uheap_walk works just like _heap_walk, except that you specify the heap to be traversed; _heap_walk always traverses the default heap. For each object, _uheap_walk passes your function: object A pointer to the object. size The size of the object. flag The value _USEDENTRY, if the object is currently allocated, or _FREEENTRY, if the object has been freed. (Both values are defined in .) status One of the following values, defined in both and , depending on the status of the object: _HEAPBADBEGIN The heap specified is not valid. It may have been closed or destroyed. _HEAPBADNODE A memory node is corrupted, or the heap is damaged. _HEAPEMPTY The heap has not been initialized. _HEAPOK The heap appears to be consistent. file The name of the file where the object was allocated or freed. line The line where the object was allocated or freed. _uheap_walk provides information about all objects, regardless of which memory management functions were used to allocate them. However, the file and line information are only available if the object was allocated and freed using the debug versions of the memory management functions. Otherwise, file is NULL and line is 0. _uheap_walk calls callback_fn for each object until one of the following occurs:  All objects have been traversed.  callback_fn returns a nonzero value to _heap_walk.  It cannot continue because of a problem with the heap. You may want to code your callback_fn to return a nonzero value if the status of the object is not _HEAPOK. Even if callback_fn returns 0 for an object that is corrupted, _heap_walk cannot continue because of the state of the heap and returns to its caller. You can use callback_fn to process information from _uheap_walk in various ways. For example, you may want to print the information to a file, or use it to generate your own error messages. You can use the information to look for memory leaks and objects incorrectly allocated or freed from the heap. It can be especially useful to call _uheap_walk when _uheapchk returns an error. Note: 1. Using the _uheapchk, _uheapset, and _uheap_walk functions (and their equivalents for the default heap) may add overhead to each object allocated from the heap 2. _uheap_walk locks the heap while it traverses it, to ensure that no other operations use the heap until _uheap_walk finishes. As a result, in your callback_fn, you cannot call any critical functions in the runtime library, either explicitly or by calling another function that calls a critical function. See the Programming Guide for a list of critical functions. Return Value _uheap_walk returns the last value of status to the caller. ═══ Example of _uheap_walk ═══ /************************************************************************ This example creates a heap and performs memory operations on it. _uheap_walk then traverses the heap and calls callback_function for each memory object. The callback_function prints a message about each memory block. ************************************************************************/ #include #include #include int callback_function(const void *pentry, size_t sz, int useflag, int status, const char *filename, size_t line) { if (_HEAPOK != status) { puts("status is not _HEAPOK."); exit(status); } if (_USEDENTRY == useflag) printf("allocated %p %u\n", pentry, sz); else printf("freed %p %u\n", pentry, sz); return 0; } int main(void) { Heap_t myheap; char *p1, *p2, *p3; /* User default heap as user heap */ myheap = _udefault(NULL); if (NULL == (p1 = _umalloc(myheap, 100)) || NULL == (p2 = _umalloc(myheap, 200)) || NULL == (p3 = _umalloc(myheap, 300))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } free(p2); puts("usage address size\n----- ------- ----"); _uheap_walk(myheap, callback_function); free(p1); free(p3); return 0; /**************************************************************************** The output should be similar to : usage address size ----- ------- ---- allocated 73A20 300 allocated 738C0 100 : : freed 73930 224 ****************************************************************************/ } ═══ Related Information ═══ Example of _uheap_walk  _heapmin - Release Unused Memory from Default Heap  _heap_walk - Return Information about Default Heap  _uheapchk - Validate Memory Heap  _uheapset - Validate and Set Memory Heap  "Managing Memory" in the Programming Guide  "Debugging Your Heaps" in the Programming Guide  ═══ 4.343. _ultoa - Convert Unsigned Long Integer to String ═══ ═══ Format ═══ #include char *_ultoa(unsigned long value, char *string, int radix); ═══ Description ═══ Language Level: Extension _ultoa 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. 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). Return Value _ultoa returns a pointer to string. There is no error return value. ═══ 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[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 output should be: 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 ═══ Example of _ultoa  _ecvt - Convert Floating-Point to Character  _fcvt - Convert Floating-Point to String  _gcvt - Convert Floating-Point to String  _itoa - Convert Integer to String  _ltoa - Convert Long Integer to String  ═══ 4.344. _umalloc - Reserve Memory Blocks from User Heap ═══ ═══ Format ═══ #include void *_umalloc(Heap_t heap, size_t size); ═══ Description ═══ Language Level: Extension _umalloc allocates a memory block of size bytes from the heap you specify. Unlike _ucalloc, _umalloc does not initialize all bits to 0. _umalloc works just like malloc, except that you specify the heap to use; malloc always allocates from the default heap. A debug version of this function, _debug_umalloc, is also provided. If the heap does not have enough memory for the request, _umalloc calls the getmore_fn that you specified when you created the heap with _ucreate. To reallocate or free memory allocated with _umalloc, use the non-heap-specific realloc and free. These functions always check what heap the memory was allocated from. Return Value _umalloc returns a pointer to the reserved space. If size was specified as 0, or if your getmore_fn cannot provide enough memory, _umalloc returns NULL. Passing _umalloc a heap that is not valid results in undefined behavior. ═══ Example of _umalloc ═══ /************************************************************************ This example creates a heap and uses _umalloc to allocate memory from the heap. ************************************************************************/ #include #include #include int main(void) { Heap_t myheap; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _umalloc(myheap, 100))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } free(ptr); return 0; } ═══ Related Information ═══ Example of _umalloc  calloc - Reserve and Initialize Storage  _debug_umalloc - Reserve Memory Blocks from User Heap  free - Release Storage Blocks  malloc - Reserve Storage Block  realloc - Change Reserved Storage Block Size  _ucalloc - Reserve and Initialize Memory from User Heap  _ucreate - Create a Memory Heap  "Managing Memory" in the Programming Guide  ═══ 4.345. umask - Sets File Mask of Current Process ═══ ═══ Format ═══ #include #include int umask(int pmode); ═══ Description ═══ Language Level: XPG4, Extension umask sets the file permission mask of the environment for the currently running process 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 possible values for pmode are defined in : 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. Note: In earlier releases of C Set ++, umask began with an underscore (_umask). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _umask to umask for you. Return Value umask 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. ═══ 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 output should be: Default system startup mask is 0. ****************************************************************************/ } ═══ Related Information ═══ Example of umask  chmod - Change File Permission Setting  creat - Create New File  open - Open File  _sopen - Open Shared File   ═══ 4.346. ungetc - Push Character onto Input Stream ═══ ═══ Format ═══ #include int ungetc(int c, FILE *stream); ═══ Description ═══ Language Level: ANSI, SAA, POSIX, XPG4 ungetc pushes the unsigned character c back onto the given input stream. However, only one sequential character 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. The character c cannot be the EOF character. Characters placed on the stream by ungetc will be erased if fseek, fsetpos, rewind, or fflush is called before the character is read from the stream. Return Value ungetc returns the integer argument c converted to an unsigned char, or EOF if c cannot be pushed back. ═══ Example of ungetc ═══ /************************************************************************ In this example, the while statement reads decimal digits from an input data stream by using arithmetic statements to composethe 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) { int ch; unsigned int result = 0; while (EOF != (ch = getc(stdin)) && isdigit(ch)) result = result * 10 + ch -'0'; if (EOF != ch) /* Push back the nondigit character onto the input stream */ ungetc(ch, stdin); printf("Input number : %d\n", result); return 0; /**************************************************************************** For the following input: 12345s The output should be: Input number : 12345 ****************************************************************************/ } ═══ Related Information ═══ Example of ungetc  getc - getchar - Read a Character  fflush - Write Buffer to File  fseek - Reposition File Position  fsetpos - Set File Position  putc - putchar - Write a Character  rewind - Adjust Current File Position  _ungetch - Push Character Back to Keyboard  ═══ 4.347. _ungetch - Push Character Back to Keyboard ═══ ═══ Format ═══ #include int _ungetch(int c); ═══ Description ═══ Language Level: Extension _ungetch pushes the character c back to the keyboard, causing c to be the next character read. _ungetch fails if called more than once before the next read operation. The character c cannot be the EOF character. Return Value If successful, _ungetch returns the character c. A return value of EOF indicates an error. ═══ 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; printf("Type in some letters.\n"); printf("If you type in an 'x', the program ends.\n"); for (; ; ) { ch = _getch(); if ('x' == ch) { _ungetch(ch); break; } _putch(ch); } ch = _getch(); printf("\nThe last character was '%c'.", ch); return 0; /**************************************************************************** Here is the output from a sample run: 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 ═══ Example of _ungetch  _cscanf - Read Data from Keyboard  _getch - _getche - Read Character from Keyboard  _putch - Write Character to Screen  ungetc - Push Character onto Input Stream  ═══ 4.348. ungetwc - Push Wide Character onto Input Stream ═══ ═══ Format ═══ #include #include wint_t ungetwc(wint_t wc, FILE *stream); ═══ Description ═══ Language Level: XPG4 ungetwc pushes the wide character by wc back onto the input stream. The pushed-back wide characters will be returned by subsequent reads on that stream in the reverse order of their pushing. A successful intervening call (on the stream) to a file positioning function (fseek, fsetpos, or rewind) discards any pushed-back wide characters for the stream. The external storage corresponding to the stream is unchanged. There is always at least one wide character of push-back. If the value of wc is WEOF, the operation fails and the input stream is unchanged. A successful call to the ungetwc function clears the EOF indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back wide characters is the same as it was before the wide characters were pushed back. For a text stream, the file position indicator is backed up by one wide character. This affects ftell, fflush, fseek (with SEEK_CUR), and fgetpos. For a binary stream, the position indicator is unspecified until all characters are read or discarded, unless the last character is pushed back, in which case the file position indicator is backed up by one wide character. This affects ftell, fseek (with SEEK_CUR), fgetpos, and fflush. After calling ungetwc, flush the buffer or reposition the stream pointer before calling a read function for the stream, unless EOF has been reached. After a read operation on the stream, flush the buffer or reposition the stream pointer before calling ungetwc. Note: 1. Under VisualAge C++, only 1 wide character may be pushed back. 2. The position on the stream after a successful call to ungetwc is one wide character prior to the current position. Return Value ungetwc returns the wide character pushed back after conversion, or WEOF if the operation fails. ═══ Example of ungetwc ═══ /************************************************************************ This example reads in wide characters from stream, and then calls ungetwc to push the characters back to the stream. ************************************************************************/ #include #include #include int main(void) { FILE *stream; wint_t wc; wint_t wc2; unsigned int result = 0; if (NULL == (stream = fopen("ungetwc.dat", "r+"))) { printf("Unable to open file.\n"); exit(EXIT_FAILURE); } while (WEOF != (wc = fgetwc(stream)) && iswdigit(wc)) result = result * 10 + wc - L'0'; if (WEOF != wc) ungetwc(wc, stream); /* Push the nondigit wide character back */ /* get the pushed back character */ if (WEOF != (wc2 = fgetwc(stream))) { if (wc != wc2) { printf("Subsequent fgetwc does not get the pushed back character.\n"); exit(EXIT_FAILURE); } printf("The digits read are '%i'\n" "The character being pushed back is '%lc'", result, wc2); } return 0; /**************************************************************************** Assuming the file ungetwc.dat contains: 12345ABCDE67890XYZ The output should be similar to : The digits read are '12345' The character being pushed back is 'A' ****************************************************************************/ } ═══ Related Information ═══ Example of ungetwc  fflush - Write Buffer to File  fseek - Reposition File Position  fsetpos - Set File Position  getwc - Read Wide Character from Stream  putwc - Write Wide Character  ungetc - Push Character onto Input Stream  _ungetch - Push Character Back to Keyboard  ═══ 4.349. unlink - Delete File ═══ ═══ Format ═══ #include /* also in */ int unlink(const char *pathname); ═══ Description ═══ Language Level: XPG4, Extension unlink deletes the file specified by pathname. Portability Note For portability, use the ANSI/ISO function remove. instead of unlink. Note: In earlier releases of C Set ++, unlink began with an underscore (_unlink). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _unlink to unlink for you. Return Value unlink returns 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 ═══ /************************************************************************ This example deletes the file tmpfile from the system or prints an error message if unable to delete it. ************************************************************************/ #include int main(void) { if (-1 == unlink("tmpfile")) perror("Cannot delete tmpfile"); else printf("tmpfile has been successfully deleted\n"); return 0; /**************************************************************************** If the file "tmpfile" exists, the output should be: tmpfile has been successfully deleted ****************************************************************************/ } ═══ Related Information ═══ Example of unlink  remove - Delete File  _rmtmp - Remove Temporary Files  ═══ 4.350. _uopen - Open Heap for Use ═══ ═══ Format ═══ #include int _uopen(Heap_t heap); ═══ Description ═══ Language Level: Extension _uopen allows the current process to use the heap you specify. If the heap is shared, you must call _uopen in each process that will allocate or free from the heap. See "Managing Memory" in the Programming Guide for more information about sharing heaps, and about creating and using heaps in general. Return Value If successful, _uopen returns 0. A nonzero return code indicates failure. Passing _uopen a heap that is not valid results in undefined behavior. ═══ Example of _uopen ═══ /************************************************************************ This example creates a fixed-size heap, then uses _uopen to open it. The program then performs operations on the heap, and closes and destroys it. ************************************************************************/ #define INCL_DOSMEMMGR /* Memory Manager values */ #include #include /* Get flags for memory management */ #include #include #include int main(void) { void *initial_block; APIRET rc; Heap_t myheap; char *p; /* Call DosAllocMem to get the initial block of memory */ if (0 != (rc = DosAllocMem(&initial_block, 65536, PAG_WRITE | PAG_READ | PAG_COMMIT))) { printf("DosAllocMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } /* Create a fixed size heap starting with the block declared earlier */ if (NULL == (myheap = _ucreate(initial_block, 65536, _BLOCK_CLEAN, _HEAP_REGULAR, NULL, NULL))) { puts("_ucreate failed."); exit(EXIT_FAILURE); } if (0 != _uopen(myheap)) { puts("_uopen failed."); exit(EXIT_FAILURE); } p = _umalloc(myheap, 100); free(p); if (0 != _uclose(myheap)) { puts("_uclose failed"); exit(EXIT_FAILURE); } if (0 != (rc = DosFreeMem(initial_block))) { printf("DosFreeMem error: return code = %ld\n", rc); exit(EXIT_FAILURE); } return 0; } ═══ Related Information ═══ Example of _uopen  _uaddmem - Add Memory to a Heap  _uclose - Close Heap from Use  _ucreate - Create a Memory Heap  "Managing Memory" in the Programming Guide  ═══ 4.351. _ustats - Get Information about Heap ═══ ═══ Format ═══ #include int _ustats(Heap_t heap, _HEAPSTATS *hpinfo); ═══ Description ═══ Language Level: Extension _ustats gets information about the heap you specify and stores it in the hpinfo structure you pass to it. The _HEAPSTATS structure type is defined in . The members it contains and the information that _ustats stores in each is as follows: _provided How much memory the heap holds (excluding memory used for overhead for the heap) _used How much memory is currently allocated from the heap _tiled Whether the memory is tiled (_tiled is 1) or not (_tiled is 0) _shared Whether the memory is shared (_shared is 1) or not (_shared is 0) _maxfree The size of the largest contiguous piece of memory available on the heap Return Value If successful, _ustats returns 0. A nonzero return code indicates failure. Passing _ustats a heap that is not valid results in undefined behavior. ═══ Example of _ustats ═══ /************************************************************************ This example creates a heap and allocates memory from it. It then calls _ustats to print out information about the heap. ************************************************************************/ #include #include #include int main(void) { Heap_t myheap; _HEAPSTATS myheap_stat; char *ptr; /* Use default heap as user heap */ myheap = _udefault(NULL); if (NULL == (ptr = _umalloc(myheap, 100))) { puts("Cannot allocate memory from user heap."); exit(EXIT_FAILURE); } if (0 != _ustats(myheap, &myheap_stat)) { puts("_ustats failed."); exit(EXIT_FAILURE); } printf ("_provided: %u\n", myheap_stat._provided); printf ("_used : %u\n", myheap_stat._used); printf ("_tiled : %u\n", myheap_stat._tiled); printf ("_shared : %u\n", myheap_stat._shared); printf ("_max_free: %u\n", myheap_stat._max_free); free(ptr); return 0; /**************************************************************************** The output should be similar to : _provided: 65264 _used : 14304 _tiled : 0 _shared : 0 _max_free: 50960 ****************************************************************************/ } ═══ Related Information ═══ Example of _ustats  _mheap - Query Memory Heap for Allocated Object  _ucreate - Create a Memory Heap  "Managing Memory" in the Programming Guide  ═══ 4.352. utime - Set Modification Time ═══ ═══ Format ═══ #include #include int utime(char *pathname, struct utimbuf *times); ═══ Description ═══ Language Level: XPG4, xtension utime 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. utime accepts only even numbers of seconds. If you enter an odd number of seconds, the function rounds it down. Note: In earlier releases of C Set ++, utime began with an underscore (_utime). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _utime to utime for you. Return Value utime returns 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. You must open the file to change its modification time. ENOENT The file path name was not found, or the file name was incorrectly specified. ═══ Example of utime ═══ /************************************************************************ This example sets the last modification time of file utime.dat to the current time. It prints an error message if it cannot. ************************************************************************/ #include #include #include #include #include #define FILENAME "utime.dat" int main(void) { struct utimbuf ubuf; struct stat statbuf; FILE *fp; /* File pointer */ /* creating file, whose date will be changed by calling utime */ fp = fopen(FILENAME, "w"); /* write Hello World in the file */ fprintf(fp, "Hello World\n"); /* close file */ fclose(fp); /* seconds to current date from 1970 Jan 1 */ /* Fri Dec 31 23:59:58 1999 */ ubuf.modtime = 946702799; /* changing file modification time */ if (-1 == utime(FILENAME, &ubuf)) { perror("utime failed"); remove(FILENAME); return EXIT_FAILURE; } /* display the modification time */ if (0 == stat(FILENAME, &statbuf)) printf("The file modification time is %s", ctime(&statbuf.st_mtime)); else printf("File could not be found\n"); remove(FILENAME); return 0; /**************************************************************************** The output should be: The file modification time is Fri Dec 31 23:59:58 1999 ****************************************************************************/ } ═══ Related Information ═══ Example of utime  fstat - Information about Open File  stat - Get Information about File or Directory   ═══ 4.353. 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 va_arg, va_end, and va_start access the arguments to a function when it takes a fixed number of required arguments and a variable number of optional arguments. All three of these are macros. You declare required arguments as ordinary parameters to the function and access the arguments through the parameter names. va_start 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 va_start before va_arg. Corresponding va_start and va_end macros must be in the same function. va_arg 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. va_arg 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. va_end is needed to indicate the end of parameter scanning. Return Value va_arg returns the current argument. va_end and va_start do not return a value. ═══ 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"); return 0; } 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); /**************************************************************************** The output should be: Day: Sat Day: Sun Day: Mon Day: Mon Day: Tues Day: Wed Day: Thurs Day: Fri ****************************************************************************/ } ═══ Related Information ═══ Example of va_arg - va_end - va_start  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  ═══ 4.354. vfprintf - Print Argument Data to Stream ═══ ═══ Format ═══ #include #include int vfprintf(FILE *stream, const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension vfprintf formats and writes a series of characters and values to the output stream. vfprintf works just like 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. vfprintf converts each entry in the argument list according to the corresponding format specifier in format. The format has the same form and function as the format string for printf. For a description of the format string, see printf - Print Formatted Characters. 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 you specify a null string for the %s or %ls format specifier, vfprintf prints (null). (In previous releases of C Set ++, vfprintf produced no output for a null string.) Return Value If successful, vfprintf returns the number of bytes written to stream. If an error occurs, the function returns a negative value. ═══ Example of vfprintf ═══ /************************************************************************ This example prints out a variable number of strings to the file vfprintf.out. ************************************************************************/ #include #include #define FILENAME "vfprintf.o" void vout(FILE *stream, char *fmt,...); char fmt1[] = "%s %s %s %s\n"; int main(void) { FILE *stream; stream = fopen(FILENAME, "w"); vout(stream, fmt1, "Sat", "Sun", "Mon", "Tue"); fclose(stream); return 0; /**************************************************************************** After running the program, the output file should contain: Sat Sun Mon Tue ****************************************************************************/ } void vout(FILE *stream, char *fmt,...) { va_list arg_ptr; va_start(arg_ptr, fmt); vfprintf(stream, fmt, arg_ptr); va_end(arg_ptr); } ═══ Related Information ═══ Example of vfprintf  fprintf - Write Formatted Data to a Stream  printf - Print Formatted Characters  va_arg - va_end - va_start - Access Function Arguments  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer  Infinity and NaN Support   ═══ 4.355. vprintf - Print Argument Data ═══ ═══ Format ═══ #include #include int vprintf(const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension vprintf formats and prints a series of characters and values to stdout. vprintf works just like 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. vprintf converts each entry in the argument list according to the corresponding format specifier in format. The format has the same form and function as the format string for printf. For a description of the format string, see printf - Print Formatted Characters. 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 you specify a null string for the %s or %ls format specifier, vfprintf prints (null). (In previous releases of C Set ++, vprintf produced no output for a null string.) Return Value If successful, vprintf returns the number of bytes written to stdout. If an error occurs, vprintf returns a negative value. ═══ Example of vprintf ═══ /************************************************************************ This example prints out a variable number of strings to stdout. ************************************************************************/ #include #include void vout(char *fmt, ...); int main(void) { char fmt1[] = "%s %s %s\n"; vout(fmt1, "Sat", "Sun", "Mon"); return 0; /**************************************************************************** The output should be: Sat Sun Mon ****************************************************************************/ } void vout(char *fmt, ...) { va_list arg_ptr; va_start(arg_ptr, fmt); vprintf(fmt, arg_ptr); va_end(arg_ptr); } ═══ Related Information ═══ Example of vprintf  printf - Print Formatted Characters  va_arg - va_end - va_start - Access Function Arguments  vfprintf - Print Argument Data to Stream  vsprintf - Print Argument Data to Buffer  vswprintf - Format and Write Wide Characters to Buffer  Infinity and NaN Support   ═══ 4.356. vsprintf - Print Argument Data to Buffer ═══ ═══ Format ═══ #include #include int vsprintf(char *target-string, const char *format, va_list arg_ptr); ═══ Description ═══ Language Level: ANSI, SAA, XPG4, Extension vsprintf formats and stores a series of characters and values in the buffer target-string. vsprintf works just like sprintf, 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, sprintf can have a list of arguments, but the number of arguments in that list is fixed when you compile the program. vsprintf converts each entry in the argument list according to the corresponding format specifier in format. The format has the same form and function as the format string for printf. For a description of the format string, see printf - Print Formatted Characters. 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 you specify a null string for the %s or %ls format specifier, vsprintf prints (null). (In previous releases of C Set ++, vsprintf produced no output for a null string.) Return Value If successful, vsprintf returns the number of bytes written to target-string. If an error occurs, vsprintf returns a negative value. ═══ 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", string); return 0; /**************************************************************************** The output should be: The string is: Sat Sun Mon ****************************************************************************/ } void vout(char *string, char *fmt,...) { va_list arg_ptr; va_start(arg_ptr, fmt); vsprintf(string, fmt, arg_ptr); va_end(arg_ptr); } ═══ Related Information ═══ Example of vsprintf  printf - Print Formatted Characters  sprintf - Print Formatted Data to Buffer  swprintf - Format and Write Wide Characters to Buffer  va_arg - va_end - va_start - Access Function Arguments  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vswprintf - Format and Write Wide Characters to Buffer  Infinity and NaN Support   ═══ 4.357. vswprintf - Format and Write Wide Characters to Buffer ═══ ═══ Format ═══ #include #include int vswprintf(wchar_t *wcsbuffer, size_t n, const wchar_t *format, va_list argptr); ═══ Description ═══ Language Level: ANSI 93 vswprintf formats and stores a series of wide characters and values in the buffer wcsbuffer. vswprintf works just like swprintf, except that argptr points to a list of wide-character arguments whose number can vary from call to call. These arguments should be initialized by va_start for each call. In contrast, swprintf can have a list of arguments, but the number of arguments in that list are fixed when you compile in the program. The value n specifies the maximum number of wide characters to be written, including the terminating null character. vswprintf converts each entry in the argument list according to the corresponding wide-character format specifier in format. The format has the same form and function as the format string for printf, with the following exceptions:  %c (without an l prefix) converts an integer argument to wchar_t, as if by calling mbtowc.  %lc converts a wint_t to wchar_t.  %s (without an l prefix); converts an array of multibyte characters to an array of wchar_t, as if by calling mbrtowc. The array is written up to, but not including, the terminating null character, unless the precision specifies a shorter output.  %ls writes an array of wchar_t. The array is written up to, but not including, the terminating null character, unless the precision specifies a shorter output. For a complete description of format specifiers, see printf - Print Formatted Characters. A null wide character is added to the end of the wide characters written; the null wide character is not counted as part of the returned value. If copying takes place between objects that overlap, the behavior is undefined. If you specify a null string for the %s or %ls format specifier, vswprintf prints (null). Return Value vswprintf returns the number of bytes written in the array, not counting the terminating null wide character. ═══ Example of vswprintf ═══ /************************************************************************ This example creates a function vout that takes a variable number of wide-character arguments and uses vswprintf to print them to wcstr. ************************************************************************/ #include #include #include wchar_t *format3 = L"%ls %d %ls"; wchar_t *format5 = L"%ls %d %ls %d %ls"; void vout(wchar_t *wcs, size_t n, wchar_t *fmt, ...) { va_list arg_ptr; va_start(arg_ptr, fmt); vswprintf(wcs, n, fmt, arg_ptr); va_end(arg_ptr); return; } int main(void) { wchar_t wcstr[100]; vout(wcstr, 100, format3, L"ONE", 2L, L"THREE"); printf("%ls\n", wcstr); vout(wcstr, 100, format5, L"ONE", 2L, L"THREE", 4L, L"FIVE"); printf("%ls\n", wcstr); return 0; /**************************************************************************** The output should be similar to : ONE 2 THREE ONE 2 THREE 4 FIVE ****************************************************************************/ } ═══ Related Information ═══ Example of vswprintf  printf - Print Formatted Characters  swprintf - Format and Write Wide Characters to Buffer  vfprintf - Print Argument Data to Stream  vprintf - Print Argument Data  vsprintf - Print Argument Data to Buffer   ═══ 4.358. wait - Wait for Child Process ═══ ═══ Format ═══ #include int wait (int *stat_loc); ═══ Description ═══ Language Level: XPG4, Extension wait 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, wait 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 Control Program Guide and Reference for details about DosWaitChild return status codes. Note: In earlier releases of C Set ++, wait began with an underscore (_wait). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _wait to wait for you. Return Value 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 A child process ended unexpectedly. ═══ 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 (-1 == (pid = wait(&stat_child))) perror("error in _spawnl"); /* display error status message */ else printf("child process %d just ran.\n", pid); 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"); return 0; } Then the output should be similar to: child2.exe is an executable file child process 2423 just ran. return information was 0x0 ****************************************************************************/ } ═══ Related Information ═══ Example of wait  _cwait - Wait for Child Process  execl - _execvpe - Load and Run Child Process  exit - End Program  _exit - End Process  _spawnl - _spawnvpe - Start and Run Child Processes  ═══ 4.359. wcrtomb - Convert Wide Character to Multibyte Character ═══ ═══ Format ═══ #include int wcrtomb(char *dest, wchar_t wc, mbstate_t *ps); ═══ Description ═══ Language Level: ANSI 93 wcrtomb is a restartable version of wctomb, and performs the same function. It first determines the length of the wide character pointed to by wc. It then converts the wide character to the corresponding multibyte character, and stores the converted character in the location pointed to by dest, if dest is not a null pointer. A maximum of MB_CUR_MAX bytes are stored. With wcrtomb, you can switch from one multibyte string to another. On systems that support shift states, ps represents the initial shift state of the string (0). If you read in only part of the string, wcrtomb sets ps to the string's shift state at the point you stopped. You can then call wcrtomb again for that string and pass in the updated ps value to continue reading where you left off. Note: Because OS/2 does not have shift states, the ps parameter is provided only for compatibility with other ANSI/ISO platforms. VisualAge C++ ignores the value passed for ps. The behavior of wcrtomb is affected by the LC_CTYPE category of the current locale. Return Value If dest is a null pointer, wcrtomb returns 0. If dest is not a null pointer, wcrtomb returns the number of bytes stored in dest. If wc is not a valid wide character, wcrtomb sets errno to EILSEQ and returns -1. ═══ Example of wcrtomb ═══ /************************************************************************ This example uses wcrtomb to convert two wide-character strings to multibyte strings. ************************************************************************/ #include #include #include #include #define SIZE 20 int main(void) { wchar_t wcs1[] = L"abc"; wchar_t wcs2[] = L"A\x8142" L"C"; mbstate_t ss1 = 0; mbstate_t ss2 = 0; size_t length1 = 0; size_t length2 = 0; char mb1[SIZE], mb2[SIZE]; int i; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } for (i = 0; i <=2; ++i) { length1 += wcrtomb(mb1 + length1, *(wcs1 + i), &ss1); length2 += wcrtomb(mb2 + length2, *(wcs2 + i), &ss2); } mb1[length1] = 0; mb2[length2] = 0; printf("The first multibyte string is: <%s>\n", mb1); printf("The second multibyte string is: <%s>\n", mb2); return 0; /**************************************************************************** The output should be similiar to : The first multibyte string is: The second multibyte string is: ****************************************************************************/ } ═══ Related Information ═══ Example of wcrtomb  mblen - Determine Length of Multibyte Character  mbrlen - Calculate Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  wcsrtombs - Convert Wide-Character String to Multibyte String  wctomb - Convert Wide Character to Multibyte Character  ═══ 4.360. wcscat - Concatenate Wide-Character Strings ═══ ═══ Format ═══ #include wchar_t *wcscat(wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcscat appends a copy of the string pointed to by string2 to the end of the string pointed to by string1. wcscat 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. Return Value wcscat returns a pointer to the concatenated string1. ═══ 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); return 0; /**************************************************************************** The output should be: buffer1 = computer program ****************************************************************************/ } ═══ Related Information ═══ Example of wcscat  strcat - Concatenate Strings  strncat - Concatenate Strings  wcsncat - Concatenate Wide-Character Strings  ═══ 4.361. wcschr - Search for Wide Character ═══ ═══ Format ═══ #include wchar_t *wcschr(const wchar_t *string, wchar_t character); ═══ Description ═══ Language Level: SAA, XPG4 wcschr searches the wide-character string for the occurrence of character. The character can be a wchar_t null character (\0); the wchar_t null character at the end of string is included in the search. wcschr 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. Return Value wcschr 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 ═══ /************************************************************************* 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); return 0; /**************************************************************************** The output should be: The first occurrence of p in 'computer program' is 'puter program' ****************************************************************************/ } ═══ Related Information ═══ Example of wcschr  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcscspn - Find Offset of First Wide-Character Match  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  ═══ 4.362. wcscmp - Compare Wide-Character Strings ═══ ═══ Format ═══ #include int wcscmp(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcscmp compares two wide-character strings. wcscmp operates on null-terminated wchar_t strings; 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. Return Value wcscmp 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 ═══ /************************************************************************* 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 (0 == result) 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); return 0; /**************************************************************************** The output should be: "abcdef" is less than "abcdefg" ****************************************************************************/ } ═══ Related Information ═══ Example of wcscmp  strcmp - Compare Strings  strcmpi - Compare Strings Without Case Sensitivity  stricmp - Compare Strings as Lowercase  strnicmp - Compare Strings Without Case Sensitivity  wcsncmp - Compare Wide-Character Strings  ═══ 4.363. wcscoll - Compare Wide-Character Strings ═══ ═══ Format ═══ #include int wcscoll(const wchar_t *wcstr1, const wchar_t *wcstr2); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcscoll compares the wide-character string pointed to by wcstr1 to the wide-character string pointed to by wcstr2, both interpreted according to the information in the LC_COLLATE category of the current locale. wcscoll differs from the wcscmp function. wcscoll performs a comparison between two wide-character strings based on language collation rules as controlled by the LC_COLLATE category. In contrast, wcscmp performs a wide-character code to wide-character code comparison. Return Value wcscoll returns an integer value indicating the relationship between the strings, as listed below: Value Meaning Less than 0 wcstr1 less than wcstr2 0 wcstr1 equivalent to wcstr2 Greater than 0 wcstr1 greater than wcstr2 If wcs1 or wcs2 contain characters outside the domain of the collating sequence, wcscoll sets errno to EILSEQ. If an error occurs, wcscoll sets errno to a nonzero value. There is no error return value. ═══ Example of wcscoll ═══ /************************************************************************ This example uses wcscoll to compare two wide-character strings. ************************************************************************/ #include #include #include #include int main(void) { wchar_t *wcs1 = L"A wide string"; wchar_t *wcs2 = L"a wide string"; int result; if (NULL == setlocale(LC_ALL, LC_C_JAPAN)) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } result = wcscoll(wcs1, wcs2); if (0 == result) printf("\"%ls\" is identical to \"%ls\"\n", wcs1, wcs2); else if (0 > result) printf("\"%ls\" is less than \"%ls\"\n", wcs1, wcs2); else printf("\"%ls\" is greater than \"%ls\"\n", wcs1, wcs2); return 0; /**************************************************************************** The output should be similar to : "A wide string" is identical to "a wide string" ****************************************************************************/ } ═══ Related Information ═══ Example of wcscoll  strcoll - Compare Strings Using Collation Rules  setlocale - Set Locale  wcscmp - Compare Wide-Character Strings  ═══ 4.364. wcscpy - Copy Wide-Character Strings ═══ ═══ Format ═══ #include wchar_t *wcscpy(wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcscpy copies the contents of string2 (including the ending wchar_t null character) into string1. wcscpy operates on null-terminated wchar_t strings; string arguments to this function should contain a wchar_t null character marking the end of the string. Boundary checking is not performed. Return Value wcscpy returns a pointer to string1. ═══ 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", return_string); return 0; /**************************************************************************** The output should be: destination is originally = "And this is the destination string" After wcscpy, destination becomes "This is the source string" ****************************************************************************/ } ═══ Related Information ═══ Example of wcscpy  strcpy - Copy Strings  strdup - Duplicate String  strncpy - Copy Strings  wcsncpy - Copy Wide-Character Strings  ═══ 4.365. wcscspn - Find Offset of First Wide-Character Match ═══ ═══ Format ═══ #include size_t wcscspn(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcscspn 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. wcscspn operates on null-terminated wchar_t strings; string arguments to this function should contain a wchar_t null character marking the end of the string. Return Value wcscspn returns the number of wchar_t characters in the segment. ═══ 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); return 0; /**************************************************************************** The output should be: The first 10 characters in the string "This is the source string" are not in the string "axle"? ****************************************************************************/ } ═══ Related Information ═══ Example of wcscspn  strcspn - Compare Strings for Substrings  strspn - Search Strings  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  ═══ 4.366. wcsftime - Convert to Formatted Date and Time ═══ ═══ Format ═══ #include size_t wcsftime(wchar_t *wdest, size_t maxsize, const wchar_t *format, const struct tm *timeptr); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcsftime converts the time and date specification in the timeptr structure into a wide-character string. It then stores the null-terminated string in the array pointed to by wdest according to the format string pointed to by format. maxsize specifies the maximum number of wide characters that can be copied into the array. wcsftime works just like strftime, except that it uses wide characters. The format string is a multibyte character string containing:  Conversion specification characters.  Ordinary wide characters, which are copied into the array unchanged. The characters that are converted are determined by the LC_CTYPE category of the current locale and by the values in the time structure pointed to by timeptr. The time structure pointed to by timeptr is usually obtained by calling the gmtime or localtime function. For details on the conversion specifiers you can use in the format string, see Conversion Specifiers Used by strftime. Return Value If the total number of wide characters in the resulting string, including the terminating null wide character, does not exceed maxsize, wcsftime returns the number of wide characters placed into wdest, not including the terminating null wide character. Otherwise, wcsftime returns 0 and the contents of the array are indeterminate. ═══ Example of wcsftime ═══ /************************************************************************ This example obtains the date and time using localtime, formats the information with wcsftime, and prints the date and time. ************************************************************************/ #include #include #include int main(void) { struct tm *timeptr; wchar_t dest[100]; time_t temp; size_t rc; temp = time(NULL); timeptr = localtime(&temp); rc = wcsftime(dest, sizeof(dest)-1, L" Today is %A," L" %b %d.\n Time: %I:%M %p", timeptr); printf("%d characters placed in string to make:\n\n%ls\n", rc, dest); return 0; /**************************************************************************** The output should be similar to : 43 characters placed in string to make: Today is Thursday, Nov 10. Time: 04:56 PM ****************************************************************************/ } ═══ Related Information ═══ Example of wcsftime  gmtime - Convert Time  localtime - Convert Time  strftime - Convert to Formatted Time  Conversion Specifiers Used by strftime  strptime - Convert to Formatted Date and Time  ═══ 4.367. wcsid - Determine Character Set ID for Wide Character ═══ ═══ Format ═══ #include int wcsid(const wchar_t c); ═══ Description ═══ Language Level: Extension wcsid determines the character set identifier for the specified wide character wc. You can specify character set identifiers for each character in the charmap file for a locale. For more information about character set identifiers and charmap files, see the section on internationalization in the Programming Guide. Return Value wcsid returns the character set identifier for the wide character, or -1 if the wide character is not valid. ═══ Example of wcsid ═══ /************************************************************************ This example uses wcsid to get the character set identifier for the wide character A. ************************************************************************/ #include #include int main(void) { wchar_t wc = L'A'; int rc; rc = wcsid(wc); printf("wide character '%c' is in character set id %i\n", wc, rc); return 0; /**************************************************************************** The output should be similar to : wide character 'A' is in character set id 0 ****************************************************************************/ } ═══ Related Information ═══ Example of wcsid   csid - Determine Character Set ID for Multibyte Character ═══ 4.368. wcslen - Calculate Length of Wide-Character String ═══ ═══ Format ═══ #include size_t wcslen(const wchar_t *string); ═══ Description ═══ Language Level: SAA, XPG4 wcslen computes the number of wide characters in the string pointed to by string. Return Value wcslen returns the number of wide characters in string, excluding the terminating wchar_t null character. ═══ Example of wcslen ═══ /************************************************************************* This example computes the length of the wide-character string string. ************************************************************************/ #include #include int main(void) { wchar_t *string = L"abcdef"; printf("Length of \"%ls\" is %i\n", string, wcslen(string)); return 0; /**************************************************************************** The output should be: Length of "abcdef" is 6 ****************************************************************************/ } ═══ Related Information ═══ Example of wcslen  mblen - Determine Length of Multibyte Character  strlen - Determine String Length  ═══ 4.369. wcsncat - Concatenate Wide-Character Strings ═══ ═══ Format ═══ #include wchar_t *wcsncat(wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA, XPG4 wcsncat appends up to count wide characters from string2 to the end of string1, and appends a wchar_t null character to the result. wcsncat operates on null-terminated wide-character strings; string arguments to this function should contain a wchar_t null character marking the end of the string. Return Value wcsncat returns string1. ═══ Example of wcsncat ═══ /************************************************************************* This example demonstrates the difference between wcscat and wcsncat. wcscat appends the entire second string to the first; 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); return 0; /**************************************************************************** The output should be: wcscat : buffer1 = "computer program" wcsncat: buffer1 = "computer pr" ****************************************************************************/ } ═══ Related Information ═══ Example of wcsncat  strncat - Concatenate Strings  strcat - Concatenate Strings  wcscat - Concatenate Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  wcsncpy - Copy Wide-Character Strings  ═══ 4.370. wcsncmp - Compare Wide-Character Strings ═══ ═══ Format ═══ #include int wcsncmp(const wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA, XPG4 wcsncmp compares up to count wide characters in string1 to string2. wcsncmp operates on null-terminated wide-character strings; string arguments to this function should contain a wchar_t null character marking the end of the string. Return Value wcsncmp 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 wcsncmp ═══ /************************************************************************* This example demonstrates the difference between wcscmp, which compares the entire strings, and wcsncmp, which compares only a specified number of wide characters in the strings. ************************************************************************/ #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); return 0; /**************************************************************************** The output should be: Comparison of each character wcscmp: "abcdefg" is less than "abcfg" Comparison of only the first 3 characters wcsncmp: "abcdefg" is identical to "abcfg" ****************************************************************************/ } void print_result(int res,wchar_t *p_buffer1,wchar_t *p_buffer2) { if (0 == res) 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); } ═══ Related Information ═══ Example of wcsncmp  strncmp - Compare Strings  strcmp - Compare Strings  strcoll - Compare Strings Using Collation Rules  strcmpi - Compare Strings Without Case Sensitivity  stricmp - Compare Strings as Lowercase  strnicmp - Compare Strings Without Case Sensitivity  wcscmp - Compare Wide-Character Strings  wcsncat - Concatenate Wide-Character Strings  wcsncpy - Copy Wide-Character Strings  ═══ 4.371. wcsncpy - Copy Wide-Character Strings ═══ ═══ Format ═══ #include wchar_t *wcsncpy(wchar_t *string1, const wchar_t *string2, size_t count); ═══ Description ═══ Language Level: SAA, XPG4 wcsncpy 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. wcsncpy operates on null-terminated wide-character strings; string arguments to this function should contain a wchar_t null character marking the end of the string. Return Value wcsncpy returns a pointer to string1. ═══ Example of wcsncpy ═══ /************************************************************************* This example demonstrates the difference between wcscpy, which copies the entire wide-character string, and wcsncpy, which copies a specified number of wide characters from the string. ************************************************************************/ #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", return_string); /* 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", return_string); return 0; /**************************************************************************** The output should be: destination is originally = 'abcdefg' After wcscpy, destination becomes '123456789' destination1 is originally = 'abcdefg' After wcsncpy, destination1 becomes '12345fg' ****************************************************************************/ } ═══ Related Information ═══ Example of wcsncpy  strcpy - Copy Strings  strncpy - Copy Strings  wcscpy - Copy Wide-Character Strings  wcsncat - Concatenate Wide-Character Strings  wcsncmp - Compare Wide-Character Strings  ═══ 4.372. wcspbrk - Locate Wide Characters in String ═══ ═══ Format ═══ #include wchar_t *wcspbrk(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcspbrk locates the first occurrence in the string pointed to by string1 of any wide character from the string pointed to by string2. Return Value wcspbrk returns a pointer to the character. If string1 and string2 have no wide characters in common, wcspbrk returns NULL. ═══ Example of wcspbrk ═══ /************************************************************************ This example uses wcspbrk to find the first occurrence of either a of b in the array string. ************************************************************************/ #include #include int main(void) { wchar_t *result; wchar_t *string = L"A 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); return 0; /**************************************************************************** The output should be similar to: The first occurrence of any of the characters "ab" in "A Blue Danube" is "anube" ****************************************************************************/ } ═══ Related Information ═══ Example of wcspbrk  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscmp - Compare Wide-Character Strings  wcscspn - Find Offset of First Wide-Character Match  wcsncmp - Compare Wide-Character Strings  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  ═══ 4.373. wcsrchr - Locate Wide Character in String ═══ ═══ Format ═══ #include wchar_t *wcsrchr(const wchar_t *string, wchar_t character); ═══ Description ═══ Language Level: SAA, XPG4 wcsrchr 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. Return Value wcsrchr returns a pointer to the character, or a NULL pointer if character does not occur in the string. ═══ 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); return 0; /**************************************************************************** The output should be: The first occurrence of p in 'computer program' is 'puter program' The last occurrence of p in 'computer program' is 'program' ****************************************************************************/ } ═══ Related Information ═══ Example of wcsrchr  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  wcspbrk - Locate Wide Characters in String  ═══ 4.374. wcsrtombs - Convert Wide-Character String to Multibyte String ═══ ═══ Format ═══ #include size_t wcsrtombs (char *dest, const wchar_t **src, size_t len, mbstate_t *ps); ═══ Description ═══ Language Level: ANSI 93 wcsrtombs is a restartable version of wcstombs, and performs the same function. It converts a sequence of wide characters from the array indirectly pointed to by src into a sequence of corresponding multibyte characters. and then stores the converted characters into the array pointed to by dest. Conversion continues up to and including the terminating wchar_t null character. The terminating wchar_t null character is also stored. Conversion stops earlier if a sequence of bytes does not form a valid multibyte character, or when len codes have been stored into the array pointed to by dest. Each conversion takes places as if by a call to the wcrtomb function. wcsrtombs assigns the object pointed to by src either a null pointer (if conversion stopped because a terminating null character was reached) or the address just past the last wide character converted. With wcsrtombs, you can switch from one multibyte string to another. On systems that support shift states, ps represents the initial shift state of the string (0). If you read in only part of the string, wcsrtombs sets ps to the string's shift state at the point you stopped. You can then call wcsrtombs again for that string and pass in the updated ps value to continue reading where you left off. Note: Because OS/2 does not have shift states, the ps parameter is provided only for compatibility with other ANSI/ISO platforms. VisualAge C++ ignores the value passed for ps. The behavior of wcsrtombs is affected by the LC_CTYPE category of the current locale. Return Value wcsrtombs returns the number of bytes in the resulting multibyte character sequence pointed to by dest. If dest is a null pointer, the value of len is ignored and wcsrtombs returns the number of elements required for the converted wide characters. If the input string contains an invalid wide character, wcsrtombs sets errno to EILSEQ and returns (size_t)-1. ═══ Example of wcsrtombs ═══ /************************************************************************ This example uses wcsrtombs to convert two wide-character strings to multibyte character strings. ************************************************************************/ #include #include #include #include #define SIZE 20 int main(void) { wchar_t wcs1[] = L"abc"; wchar_t wcs2[] = L"A\x8142" L"C"; const wchar_t *pwcs1 = wcs1; const wchar_t *pwcs2 = wcs2; mbstate_t ss1 = 0; mbstate_t ss2 = 0; char mb1[SIZE], mb2[SIZE]; if (NULL == setlocale(LC_ALL, "ja_jp.ibm-932")) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } wcsrtombs(mb1, &pwcs1, SIZE, &ss1); wcsrtombs(mb2, &pwcs2, SIZE, &ss2); printf("The first multibyte string is: <%s>\n", mb1); printf("The second multibyte string is: <%s>\n", mb2); return 0; /**************************************************************************** The output should be similiar to : The first multibyte string is: The second multibyte string is: ****************************************************************************/ } ═══ Related Information ═══ Example of wcsrtombs  mblen - Determine Length of Multibyte Character  mbrlen - Calculate Length of Multibyte Character  mbrtowc - Convert Multibyte Character to Wide Character  mbsrtowcs - Convert Multibyte String to Wide-Character String  mbstowcs - Convert Multibyte String to Wide-Character String  wcrtomb - Convert Wide Character to Multibyte Character  wcstombs - Convert Wide-Character String to Multibyte String  ═══ 4.375. wcsspn - Search Wide-Character Strings ═══ ═══ Format ═══ #include size_t wcsspn(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcsspn scans string1 for the wide characters contained in string2. It stops when it encounters a character in string1 that is not in string2. Return Value wcsspn returns the number of wide characters from string2 that it found in string1. ═══ Example of wcsspn ═══ /************************************************************************ This example finds the first occurrence in the array string of a wide character that is not an a, b, or 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); return 0; /**************************************************************************** The output should be: The first 5 characters of "cabbage" are found in "abc" ****************************************************************************/ } ═══ Related Information ═══ Example of wcsspn  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  wcswcs - Locate Wide-Character Substring  wcspbrk - Locate Wide Characters in String  ═══ 4.376. wcsstr - Locate Wide-Character Substring ═══ ═══ Format ═══ #include wchar_t *wcsstr(const wchar_t *wcs1, const wchar_t *wcs2); ═══ Description ═══ Language Level: ANSI 93 wcsstr locates the first occurrence of wcs2 in wcs1. In the matching process, wcsstr ignores the wchar_t null character that ends wcs2. The behavior of wcsstr is affected by the LC_CTYPE category of the current locale. Return Value wcsstr returns a pointer to the beginning of the first occurrence of wcs2 in wcs1. If wcs2 does not appear in wcs1, wcsstr returns NULL. If wcs2 points to a wide-character string with zero length, wcsstr returns wcs1. ═══ Example of wcsstr ═══ /************************************************************************ This example uses wcsstr to find the first occurrence of hay in the wide-character string needle in a haystack. ************************************************************************/ #include #include int main(void) { wchar_t *wcs1 = L"needle in a haystack"; wchar_t *wcs2 = L"hay"; printf("result: \"%ls\"\n", wcsstr(wcs1, wcs2)); return 0; /**************************************************************************** The output should be similar to : result: "haystack" ****************************************************************************/ } ═══ Related Information ═══ Example of wcsstr  strstr - Locate Substring  wcschr - Search for Wide Character  wcsrchr - Locate Wide Character in String  wcswcs - Locate Wide-Character Substring  ═══ 4.377. wcstod - Convert Wide-Character String to Double ═══ ═══ Format ═══ #include double wcstod(const wchar_t *nptr, wchar_t **endptr); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcstod converts the wide-character string pointed to by nptr to a double value. The nptr parameter points to a sequence of characters that can be interpreted as a numerical value of type double. wcstod stops reading the string at the first character that it cannot recognize as part of a number. This character can be the wchar_t null character at the end of the string. wcstod expects nptr to point to a string with the following form: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬───┬──┬───────────────────────────┬──> │ │ └─white-space─┘ ├─+─┤ ├─digits──┬───┬──┬────────┬─┤ │ │ └─┴─┘ │ └─.─┘ └─digits─┘ │ │ │ └─.──digits─────────────────┘ │ │ │ │ >──┬──────────────────────┬──>< │ │ └─┬─e─┬──┬───┬──digits─┘ │ │ └─E─┘ ├─+─┤ │ │ └─┴─┘ │ │ │ └──────────────────────────────────────────────────────────────────────────────┘ Note: The character used for the decimal point (shown as . in the above diagram) depends on the LC_NUMERIC category of the current locale. In locales other than the "C" locale, additional implementation-defined subject sequence forms may be accepted. The behavior of wcstod is affected by the LC_CTYPE category of the current locale. Return Value wcstod function returns the converted double value. If no conversion could be performed, wcstod returns 0. If the correct value is outside the range of representable values, wcstod returns +HUGE_VAL or -HUGE_VAL (according to the sign of the value), and sets errno to ERANGE. If the correct value would cause underflow, wcstod returns 0 and sets errno to ERANGE. If the string nptr points to is empty or 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 wcstod ═══ /************************************************************************ This example uses wcstod to convert the string wcs to a floating-point value. ************************************************************************/ #include #include int main(void) { wchar_t *wcs = L"3.1415926This stopped it"; wchar_t *stopwcs; printf("wcs = \"%ls\"\n", wcs); printf(" wcstod = %f\n", wcstod(wcs, &stopwcs)); printf(" Stop scanning at \"%ls\"\n", stopwcs); return 0; /**************************************************************************** The output should be similar to : wcs = "3.1415926This stopped it" wcstod = 3.141593 Stop scanning at "This stopped it" ****************************************************************************/ } ═══ Related Information ═══ Example of wcstod  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  strtoul - Convert String Segment to Unsigned Integer  wcstol - Convert Wide-Character to Long Integer  wcstoul - Convert Wide-Character String to Unsigned Long  ═══ 4.378. wcstok - Tokenize Wide-Character String ═══ ═══ Format ═══ #include wchar_t *wcstok(wchar_t *wcs1, const wchar_t *wcs2, wchar_t **ptr); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcstok reads wcs1 as a series of zero or more tokens and wcs2 as the set of wide characters serving as delimiters for the tokens in wcs1. A sequence of calls to wcstok locates the tokens inside wcs1. The tokens can be separated by one or more of the delimiters from wcs2. The third argument points to a wide-character pointer that you provide where wcstok stores information necessary for it to continue scanning the same string. When wcstok is first called for the wide-character string wcs1, it searches for the first token in wcs1, skipping over leading delimiters. wcstok returns a pointer to the first token. To read the next token from wcs1, call wcstok with NULL as the first parameter (wcs1). This NULL parameter causes wcstok to search for the next token in the previous token string. Each delimiter is replaced by a null character to terminate the token. wcstok always stores enough information in the pointer ptr so that subsequent calls, with NULL as the first paramter and the unmodified pointer value as the third, will start searching right after the previously returned token. You can change the set of delimiters (wcs2) from call to call. The behavior of wcstok function is affected by the LC_CTYPE category of the current locale. Return Value wcstok function returns a pointer to the first wide character of the token, or a null pointer if there is no token. In later calls with the same token string, strtok returns a pointer to the next token in the string. When there are no more tokens, strtok returns NULL. ═══ Example of wcstok ═══ /************************************************************************ This example uses wcstok to locate the tokens in the wide-character string str1. ************************************************************************/ #include #include int main(void) { static wchar_t str1[] = L"?a??b,,,#c"; static wchar_t str2[] = L"\t \t"; wchar_t *t, *ptr1, *ptr2; t = wcstok(str1, L"?", &ptr1); /* t points to the token L"a" */ printf("t = '%ls'\n", t); t = wcstok(NULL, L",", &ptr1); /* t points to the token L"?b" */ printf("t = '%ls'\n", t); t = wcstok(str2, L" \t,", &ptr2); /* t is a null pointer */ printf("t = '%ls'\n", t); t = wcstok(NULL, L"#,", &ptr1); /* t points to the token L"c" */ printf("t = '%ls'\n", t); t = wcstok(NULL, L"?", &ptr1); /* t is a null pointer */ printf("t = '%ls'\n", t); return 0; /**************************************************************************** The output should be similar to : t = 'a' t = '?b' t = '(null)' t = 'c' t = '(null)' ****************************************************************************/ } ═══ Related Information ═══ Example of wcstok  strtok - Tokenize String  ═══ 4.379. wcstol - Convert Wide-Character to Long Integer ═══ ═══ Format ═══ #include long int wcstol(const wchar_t *nptr, wchar_t **endptr, int base); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcstol converts the wide-character string pointed to by nptr to a long integer value. nptr points to a sequence of wide characters that can be interpreted as a numerical value of type long int. wcstol stops reading the string at the first wide character that it cannot recognize as part of a number. This character can be the wchar_t null character 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 wcstol, nptr should point to a string with the following form: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬───┬──┬────┬──┬────────┬──>< │ │ └─white-space─┘ ├─+─┤ ├─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 (octal); the prefix 0x or 0X means base 16 (hexadecimal); using any other digit without a prefix means decimal. In locales other than the "C" locale, additional implementation-defined forms may be accepted. The behavior of wcstol is affected by the LC_CTYPE category of the current locale. Return Value wcstol returns the converted long integer value. If no conversion could be performed, wcstol returns 0. If the correct value is outside the range of representable values, wcstol returns LONG_MAX or LONG_MIN returned (according to the sign of the value), and sets errno to ERANGE. If the string nptr points to is empty or 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 wcstol ═══ /************************************************************************ This example uses wcstol to convert the wide-character string wcs to a long integer value. ************************************************************************/ #include #include int main(void) { wchar_t *wcs = L"10110134932"; wchar_t *stopwcs; long l; int base; printf("wcs = \"%ls\"\n", wcs); for (base=2; base<=8; base*=2) { l = wcstol(wcs, &stopwcs, base); printf(" wcstol = %ld\n" " Stopped scan at \"%ls\"\n\n", l, stopwcs); } return 0; /**************************************************************************** The output should be similar to : wcs = "10110134932" wcstol = 45 Stopped scan at "34932" wcstol = 4423 Stopped scan at "4932" wcstol = 2134108 Stopped scan at "932" ****************************************************************************/ } ═══ Related Information ═══ Example of wcstol  atol - Convert Character String to Long Integer  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  strtoul - Convert String Segment to Unsigned Integer  wcstod - Convert Wide-Character String to Double  wcstoul - Convert Wide-Character String to Unsigned Long  ═══ 4.380. wcstombs - Convert Wide-Character String to Multibyte String ═══ ═══ Format ═══ #include size_t wcstombs(char *dest, const wchar_t *string, size_t n); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 wcstombs converts the wide-character string pointed to by string into the multibyte array pointed to by dest. The conversion stops after n bytes in dest are filled or after a wide null character is encountered. Only complete multibyte characters are stored in dest. If the lack of space in dest would cause a partial multibyte character to be stored, wcstombs stores fewer than n bytes and discards the invalid character. The behavior of wcstombs is affected by the LC_CTYPE category of the current locale. Return Value If successful, wcstombs returns the number of bytes converted and stored in dest, not counting the terminating null character. The string pointed to by dest ends with a null character unless wcstombs returns the value n. If it encounters an invalid wide character, wcstombs returns (size_t)-1. If the area pointed to by dest is too small to contain all the wide characters represented as multibyte characters, wcstombs returns the number of bytes containing complete multibyte characters. If dest is a null pointer, the value of len is ignored and wcstombs returns the number of elements required for the converted wide characters. ═══ Example of wcstombs ═══ /************************************************************************ In this example, wcstombs converts a wide-character string to a multibyte character 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 #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); return 0; /**************************************************************************** The output should be: 6 characters were converted. The converted string is "string" 3 characters were converted. The converted string is "str" ****************************************************************************/ } ═══ Related Information ═══ Example of wcstombs  mbstowcs - Convert Multibyte String to Wide-Character String  wcslen - Calculate Length of Wide-Character String  wcsrtombs - Convert Wide-Character String to Multibyte String  wctomb - Convert Wide Character to Multibyte Character  ═══ 4.381. wcstoul - Convert Wide-Character String to Unsigned Long ═══ ═══ Format ═══ #include unsigned long int wcstoul(const wchar_t *nptr, wchar_t **endptr, int base); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 wcstoul converts the wide-character string pointed to by nptr to an unsigned long integer value. nptr points to a sequence of wide characters that can be interpreted as a numerical value of type unsigned long int. wcstoul stops reading the string at the first wide character that it cannot recognize as part of a number. This character can be the wchar_t null character 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 wcstoul, nptr should point to a string with the following form: ┌──────────────────────────────────────────────────────────────────────────────┐ │ │ │ >>──┬─────────────┬──┬────┬──┬────────┬──>< │ │ └─white-space─┘ ├─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 (octal); the prefix 0x or 0X means base 16 (hexadecimal); using any other digit without a prefix means decimal. In locales other than the "C" locale, additional implementation-defined subject sequence forms may be accepted. If the subject sequence is empty or does not have the expected form, no conversion is performed and wcstoul stores the value of nptr in the object pointed to by endptr, provided that endptr is not a null pointer. The behavior of wcstoul is affected by the LC_CTYPE category of the current locale. Return Value wcstoul returns the converted unsigned long integer value. If no conversion could be performed, wcstoul returns 0. If the correct value is outside the range of representable values, wcstoul returns ULONG_MAX and sets errno to ERANGE. If the string nptr points to is empty or 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 wcstoul ═══ /************************************************************************ This example uses wcstoul to convert the string wcs to an unsigned long integer value. ************************************************************************/ #include #include #define BASE 2 int main(void) { wchar_t *wcs = L"1000e13 camels"; wchar_t *endptr; unsigned long int answer; answer = wcstoul(wcs, &endptr, BASE); printf("The input wide string used: '%ls'\n" "The unsigned long int produced: %lu\n" "The substring of the input wide string that was not" " converted to unsigned long: '%ls'\n", wcs, answer, endptr); return 0; /**************************************************************************** The output should be similar to : The input wide string used: '1000e13 camels' The unsigned long int produced: 8 The substring of the input wide string that was not converted to unsigned long: 'e13 camels' ****************************************************************************/ } ═══ Related Information ═══ Example of wcstoul  strtod - Convert Character String to Double  strtol - Convert Character String to Long Integer  strtol - Convert Character String to Long Integer  strtold - Convert String to Long Double  wcstod - Convert Wide-Character String to Double  wcstol - Convert Wide-Character to Long Integer  ═══ 4.382. wcswcs - Locate Wide-Character Substring ═══ ═══ Format ═══ #include wchar_t *wcswcs(const wchar_t *string1, const wchar_t *string2); ═══ Description ═══ Language Level: SAA, XPG4 wcswcs locates the first occurrence of string2 in the wide-character string pointed to by string1. In the matching process, wcswcs ignores the wchar_t null character that ends string2. Return Value wcswcs returns a pointer to the located string or NULL if the string is not found. If string2 points to a string with zero length, wcswcs returns string1. ═══ 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); return 0; /**************************************************************************** The output should be: The first occurrence of pr in 'computer program' is 'program' ****************************************************************************/ } ═══ Related Information ═══ Example of wcswcs  strchr - Search for Character  strcspn - Compare Strings for Substrings  strpbrk - Find Characters in String  strrchr - Find Last Occurrence of Character in String  strspn - Search Strings  wcschr - Search for Wide Character  wcscspn - Find Offset of First Wide-Character Match  wcspbrk - Locate Wide Characters in String  wcsrchr - Locate Wide Character in String  wcsspn - Search Wide-Character Strings  ═══ 4.383. wcswidth - Determine Display Width of Wide-Character String ═══ ═══ Format ═══ #include int wcswidth (const wchar_t *wcs, size_t n); ═══ Description ═══ Language Level: XPG4 wcswidth determines the number of printing positions occupied on a display device by a graphic representation of n wide characters in the string pointed to by wcs (or fewer than n wide characters, if a null wide character is encountered before n characters have been exhausted). The number is independent of its location on the device. The behavior of wcswidth is affected by the LC_CTYPE category. Return Value wcswidth returns the number of printing positions occupied by the wide-character string. If wcs points to a null wide character, wcswidth returns 0. If any wide character in wcs is not a printing character, wcswidth returns -1. Note: Under VisualAge C++, the printing width is 0 for a null character, 1 for each single-byte character, and 2 for each double-byte character. ═══ Example of wcswidth ═══ /************************************************************************ This example uses wcswidth to calculate the display width of ABC. ************************************************************************/ #include #include int main(void) { wchar_t *wcs = L"ABC"; printf("wcs has a width of: %d\n", wcswidth(wcs,3)); return 0; /**************************************************************************** The output should be similar to : wcs has a width of: 3 ****************************************************************************/ } ═══ Related Information ═══ Example pf wcswidth  wcwidth - Determine Display Width of Wide Character  ═══ 4.384. wcsxfrm - Transform Wide-Character String ═══ ═══ Format ═══ #include size_t wcsxfrm(wchar_t *wcs1, const wchar_t *wcs2, size_t n); ═══ Description ═══ Language Level: ANSI 93, XPG4 wcsxfrm transforms the wide-character string pointed to by wcs2 to values that represent character collating weights and places the resulting wide-character string into the array pointed to by wcs1. The transformation is determined by the program's locale. The transformed string is not necessarily readable, but can be used with the wcscmp function. The transformation is such that if wcscmp were applied to two transformed wide-character strings, the results would be the same as applying the wcscoll function to the two corresponding untransformed strings. No more than n elements are placed into the resulting array pointed to by wcs1, including the terminating null wide character. If n is 0, wcs1 can be a null pointer. If copying takes place between objects that overlap, the behavior is undefined. The behavior of wcsxfrm is controlled by the LC_COLLATE category of the current locale. Return Value wcsxfrm returns the length of the transformed wide-character string (excluding the terminating null wide character). If the value returned is n or more, the contents of the array pointed to by wcs1 are indeterminate. If wcs1 is a null pointer, wcsxfrm returns the number of elements required to contain the transformed wide string. If wcs2 contains invalid wide characters, wcsxfrm returns (size_t)-1. The transformed values of the invalid characters are either less than or greater than the transformed values of valid wide characters, depending on the option chosen for the particular locale definition. If wcs2 contains wide characters outside the domain of the collating sequence. wcsxfrm sets errno to EILSEQ. ═══ Example of wcsxfrm ═══ /************************************************************************ This example uses wcsxfrm to transform two different strings with the same collating weight. It then uses wcscmp to compare the new strings. ************************************************************************/ #include #include #include #include int main(void) { wchar_t *string1 = L"stride ng1"; wchar_t *string2 = L"stri*ng1"; wchar_t *newstring1, *newstring2; int length1, length2; if (NULL == setlocale(LC_ALL, LC_C_FRANCE)) { printf("setlocale failed.\n"); exit(EXIT_FAILURE); } length1 = wcsxfrm(NULL, string1, 0); length2 = wcsxfrm(NULL, string2, 0); if (NULL == (newstring1 = calloc(length1 + 1, sizeof(wchar_t))) || NULL == (newstring2 = calloc(length2 + 1, sizeof(wchar_t)))) { printf("insufficient memory\n"); exit(EXIT_FAILURE); } if ((wcsxfrm(newstring1, string1, length1 + 1) != length1) || (wcsxfrm(newstring2, string2, length2 + 1) != length2)) { printf("error in string processing\n"); exit(EXIT_FAILURE); } if (0 != wcscmp(newstring1, newstring2)) printf("wrong results\n"); else printf("correct results\n"); return 0; /**************************************************************************** The output should be similar to : correct results ****************************************************************************/ } ═══ Related Information ═══ Example of wcsxfrm  strxfrm - Transform String  wcscmp - Compare Wide-Character Strings  wcscoll - Compare Wide-Character Strings  ═══ 4.385. wctob - Convert Wide Character to Byte ═══ ═══ Format ═══ #include #include int wctob(wint_t wc); ═══ Description ═══ Language Level: ANSI 93 wctob determines whether wc corresponds to a member of the extended character set, whose multibyte character has a length of 1 byte The behavior of wctob is affected by the LC_CTYPE category of the current locale. Return Value If c corresponds to a multibyte character with a length of 1 byte, wctob returns the single-byte representation. Otherwise, wctob returns EOF. ═══ Example of wctob ═══ /************************************************************************ This example uses wctob to test if the wide character A is a valid single-byte character. ************************************************************************/ #include #include int main(void) { wint_t wc = L'A'; if (wctob(wc) == wc) printf("%lc is a valid single byte character\n", wc); else printf("%lc is not a valid single byte character\n", wc); return 0; /**************************************************************************** The output should be similar to : A is a valid single byte character ****************************************************************************/ } ═══ Related Information ═══ Example of wctob  mbtowc - Convert Multibyte Character to Wide Character  wctomb - Convert Wide Character to Multibyte Character  wcstombs - Convert Wide-Character String to Multibyte String  ═══ 4.386. wctomb - Convert Wide Character to Multibyte Character ═══ ═══ Format ═══ #include int wctomb(char *string, wchar_t wc); ═══ Description ═══ Language Level: ANSI, SAA, XPG4 wctomb converts the wide character wc into a multibyte character and stores it in the location pointed to by string. wctomb stores a maximum of MB_CUR_MAX characters in string. The behavior of wctomb is affected by the LC_CTYPE category of the current locale. Return Value wctomb returns the length in bytes of the multibyte character. If wc is not a valid multibyte character, wctomb returns -1. If string is a NULL pointer, wctomb returns 0. Note: On platforms that support shift states, wctomb can also return a nonzero value to indicate that the multibyte encoding is state dependent. Because VisualAge C++ does not support state-dependent encoding, wctomb always returns 0 when string is NULL. ═══ Example of wctomb ═══ /************************************************************************ This example calls wctomb to convert the wide character c to a multibyte 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); return 0; /**************************************************************************** The output should be: The number of bytes that comprise the multibyte character is 1 And the converted string is "c" ****************************************************************************/ } ═══ Related Information ═══ Example of wctomb  mbtowc - Convert Multibyte Character to Wide Character  wcrtomb - Convert Wide Character to Multibyte Character  wcslen - Calculate Length of Wide-Character String  wcsrtombs - Convert Wide-Character String to Multibyte String  wcstombs - Convert Wide-Character String to Multibyte String  wctob - Convert Wide Character to Byte  ═══ 4.387. wctype - Get Handle for Character Property Classification ═══ ═══ Format ═══ #include wctype_t wctype(const char *property); ═══ Description ═══ Language Level: ANSI 93, XPG4 wctype returns a handle for the specified character class from the LC_CTYPE category. You can then use this handle with the iswctype function to determine if a given wide character belongs to that class. The following strings correspond to the standard (basic) character classes or properties: ┌───────────────────┬───────────────────┬───────────────────┬──────────────────┐ │ " │ " │ " │ " │ │ "alnum" │ "cntrl" │ "lower" │ "space" │ │ "alpha" │ "digit" │ "print" │ "upper" │ │ "blank" " │ "graph" " │ "punct" " │ "xdigit" " │ └───────────────────┴───────────────────┴───────────────────┴──────────────────┘ These classes are described in isalnum to isxdigit - Test Integer Value and iswalnum to iswxdigit - Test Wide Integer Value. You can also give the name of a user-defined class, as specified in a locale definition file, as the property argument. The behavior of this wide-character function is affected by the LC_CTYPE category of the current locale. Return Value wctype returns a value of type wctype_t that represents the property and can be used in calls to iswctype. If the given property is not valid for the current locale (LC_CTYPE category), wctype returns 0. Values returned by wctype are valid until a call to setlocale that modifies the LC_CTYPE category. ═══ Example of wctype ═══ /************************************************************************ This example uses wctype to return each standard property, and calls iswctype to test a wide character against each property. ************************************************************************/ #include #include #define UPPER_LIMIT 0xFF int main(void) { int wc; for (wc = 0; wc <= UPPER_LIMIT; wc++) { printf("%#4x ", wc); printf("%c", iswctype(wc, wctype("print")) ? wc : ' '); printf("%s", iswctype(wc, wctype("alnum")) ? " AN" : " "); printf("%s", iswctype(wc, wctype("alpha")) ? " A " : " "); printf("%s", iswctype(wc, wctype("blank")) ? " B " : " "); printf("%s", iswctype(wc, wctype("cntrl")) ? " C " : " "); printf("%s", iswctype(wc, wctype("digit")) ? " D " : " "); printf("%s", iswctype(wc, wctype("graph")) ? " G " : " "); printf("%s", iswctype(wc, wctype("lower")) ? " L " : " "); printf("%s", iswctype(wc, wctype("punct")) ? " PU" : " "); printf("%s", iswctype(wc, wctype("space")) ? " S " : " "); printf("%s", iswctype(wc, wctype("print")) ? " PR" : " "); printf("%s", iswctype(wc, wctype("upper")) ? " U " : " "); printf("%s", iswctype(wc, wctype("xdigit")) ? " X " : " "); putchar('\n'); } return 0; /**************************************************************************** The output should be similar to : : 0x1f C 0x20 B S PR 0x21 ! G PU PR 0x22 " G PU PR 0x23 # G PU PR 0x24 $ G PU PR 0x25 % G PU PR 0x26 & G PU PR 0x27 ' G PU PR 0x28 ( G PU PR 0x29 ) G PU PR 0x2a * G PU PR 0x2b + G PU PR 0x2c , G PU PR 0x2d - G PU PR 0x2e . G PU PR 0x2f / G PU PR 0x30 0 AN D G PR X 0x31 1 AN D G PR X 0x32 2 AN D G PR X 0x33 3 AN D G PR X 0x34 4 AN D G PR X 0x35 5 AN D G PR X : ****************************************************************************/ } ═══ Related Information ═══ Example of wctype  iswalnum to iswxdigit - Test Wide Integer Value  iswctype - Test for Character Property  ═══ 4.388. wcwidth - Determine Display Width of Wide Character ═══ ═══ Format ═══ #include int wcwidth (const wint_t wc); ═══ Description ═══ Language Level: XPG4 wcwidth determines the number of printing positions that a graphic representation of wc occupies on a display device. Each of the printing wide characters occupies its own number of printing positions on a display device. The number is independent of its location on the device. The behavior of wcwidth is affected by the LC_CTYPE category. Return Value wcwidth returns the number of printing positions occupied by wc. If wc is a null wide character, wcwidth returns 0. If wc is not a printing wide character, wc returns -1. Note: Under VisualAge C++, the printing width is 0 for a null character, 1 for a single-byte character, and 2 for a double-byte character. ═══ Example of wcwidth ═══ /************************************************************************ This example determines the printing width for the wide character A. ************************************************************************/ #include #include int main(void) { wint_t wc = L'A'; printf("%lc has a width of %d\n", wc, wcwidth(wc)); return 0; /**************************************************************************** The output should be similar to : A has a width of 1 ****************************************************************************/ } ═══ Related Information ═══ Example of wcwidth  wcswidth - Determine Display Width of Wide-Character String  ═══ 4.389. write - Writes from Buffer to File ═══ ═══ Format ═══ #include int write(int handle, const void *buffer, unsigned int count); ═══ Description ═══ Language Level: XPG4, Extension write 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. Note: In earlier releases of C Set ++, write began with an underscore (_write). Because it is defined by the X/Open standard, the underscore has been removed. For compatibility, VisualAge C++ will map _write to write for you. Return Value write 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 ═══ /************************************************************************ This example writes the contents of the character array buffer to the output file whose handle is fh. ************************************************************************/ #include #include #include #include #include #define FILENAME "write.dat" int main(void) { int fh; char buffer[20]; memset(buffer, 'a', 20); /* initialize storage */ printf("\nCreating " FILENAME ".\n"); system("echo Sample Program > " FILENAME); if (-1 == (fh = open(FILENAME, O_RDWR|O_APPEND))) { perror("Unable to open " FILENAME); return EXIT_FAILURE; } if (5 != write(fh, buffer, 5)) { perror("Unable to write to " FILENAME); close(fh); return EXIT_FAILURE; } printf("Successfully appended 5 characters.\n"); close(fh); return 0; /**************************************************************************** The program should create a file "write.dat" containing: Sample Program aaaaa The output should be: Creating write.dat. Successfully appended 5 characters. ****************************************************************************/ } ═══ Related Information ═══ Example of write  creat - Create New File  fread - Read Items  fwrite - Write Items  lseek - Move File Pointer  open - Open File  read - Read Into Buffer  _sopen - Open Shared File  _tell - Get Pointer Position  ═══ 5. 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 you change the default calling convention (using one of the /M options), you must include the appropriate header files with the declarations of the library functions that you use. This section describes each include file, explains its contents, and lists the functions that are declared in the file.                                       ═══ Related Information ═══  #include ═══ 5.1. ═══ The 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 ═══  #define  #ifndef  Include Files  #include ═══ 5.2. ═══ The include file declares the following built-in and intrinsic functions: _alloca _clear87 _control87 _crotl _crotr _disable _enable _facos _fasin _fcos _fcossin _fpatan _fptan _fsin _fsincos _fyl2x _fyl2xp1 _f2xm1 _getTIBvalue _inp _inpd _inpw _interrupt _lrotl _lrotr _outp _outpd _outpw _rotl _rotr _srotl _srotr __parmdwords _status87 _clear87, _control87, and _status87 are also defined in . _alloca is also defined in and . The functions _inp, _inpd, _inpw, _outp, _outpd, and _outpw are also defined in . also includes a declaration for the type size_t. ═══ Related Information ═══  Intrinsic Functions  Include Files  #include ═══ 5.3. ═══ The include file declares functions that retrieve information about the current locale's collating properties: cclass collequiv collorder collrange colltostr getmccoll getwmccoll ismccollel maxcoll strtocoll ═══ Related Information ═══  Locales in the Programming Guide   setlocale - Set Locale  Include Files  #include ═══ 5.4. ═══ The include file defines 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 ═══    Include Files  #include ═══ 5.5. ═══ The include file defines functions used in character classification. The functions defined in are: isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper In extended mode, also includes definitions for the following VisualAge C++ extensions: isascii _iscsym _iscsymf _toascii _tolower _toupper In the VisualAge C++ compiler, the functions are all implemented as macros. ═══ Related Information ═══  Include Files  #include ═══ 5.6. ═══ The include file defines functions that control directories and drives. The functions defined in are: chdir _chdrive _getcwd _getdcwd _getdrive mkdir rmdir ═══ Related Information ═══  Include Files  #include ═══ 5.7. ═══ The include file defines symbolic macro names, such as EDOM and ERANGE, for runtime errors, 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 ═══  Runtime Return Codes and Messages   Include Files  #include ═══ 5.8. ═══ The include file defines constants used by the open and _sopen functions. Definitions for these two functions are included in . Additional definitions for _sopen are provided in . ═══ Related Information ═══    Include Files  #include ═══ 5.9. ═══ The include file defines 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, also defines the macros that represent infinity and NaN (not-a-number) values, and defines 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 ═══  Infinity and NaN Support  Floating-Point Variables  Include Files  #include ═══ 5.10. ═══ The include file declares the iconv_open, iconv, and iconv_close functions to convert characters from one character set definition to another. The ICONV utility also uses these functions. iconv.h also declares the iconv_t type, which is a pointer to an object capable of storing the information about the opened converters used. ═══ Related Information ═══  Include Files  iconv Utility in the User's Guide. ═══ 5.11. ═══ The include file defines 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 . Constants required by the open and _sopen functions are provided in . Additional constants used by _sopen are defined in . The unlink function is also defined in . ═══ Related Information ═══        Include Files  #include ═══ 5.12. ═══ The include file declares the nl_langinfo function. The include file also defines the macros that, in turn, define constants that are used to identify the information queried in the current locale, and the nl_item type, which is the type of the constants. The following macros are defined: ABDAY_1 Abbreviated first day of the week ABDAY_2 Abbreviated second day of the week ABDAY_3 Abbreviated third day of the week ABDAY_4 Abbreviated fourth day of the week ABDAY_5 Abbreviated fifth day of the week ABDAY_6 Abbreviated sixth day of the week ABDAY_7 Abbreviated seventh day of the week ABMON_1 Abbreviated first month ABMON_2 Abbreviated second month ABMON_3 Abbreviated third month ABMON_4 Abbreviated fourth month ABMON_5 Abbreviated fifth month ABMON_6 Abbreviated sixth month ABMON_7 Abbreviated seventh month ABMON_8 Abbreviated eighth month ABMON_9 Abbreviated ninth month ABMON_10 Abbreviated tenth month ABMON_11 Abbreviated eleventh month ABMON_12 Abbreviated twelfth month AM_STR String for morning CODESET Current encoded character set of the process CRNCYSTR Currency symbol D_FMT String for formatting date D_T_FMT String for formatting date and time DAY_1 Name of the first day of the week DAY_2 Name of the second day of the week DAY_3 Name of the third day of the week DAY_4 Name of the fourth day of the week DAY_5 Name of the fifth day of the week DAY_6 Name of the sixth day of the week DAY_7 Name of the seventh day of the week MON_1 Name of the first month MON_2 Name of the second month MON_3 Name of the third month MON_4 Name of the fourth month MON_5 Name of the fifth month MON_6 Name of the sixth month MON_7 Name of the seventh month MON_8 Name of the eighth month MON_9 Name of the ninth month MON_10 Name of the tenth month MON_11 Name of the eleventh month MON_12 Name of the twelfth month NOEXPR Negative response expression PM_STR String for afternoon RADIXCHAR Radix character T_FMT String for formatting time T_FMT_AMPM String for morning or afternoon time format THOUSEP Separator for thousands YESEXPR Affirmative response expression ═══ Related Information ═══   setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.13. ═══ The include file declares the LOCALDEF utility. Do not include it in your source code. ═══ Related Information ═══  LOCALDEF Utility in the User's Guide  Introduction to Locale in the Programming Guide  Include Files ═══ 5.14. ═══ The include file defines constants that specify the ranges of integer and character data types, such as the maximum value for an object of type char. ═══ Related Information ═══  Characters  Integers  Include Files  #include ═══ 5.15. ═══ The include file declares the LOCALDEF utility. Do not include it in your source code. ═══ Related Information ═══  LOCALDEF Utility in the User's Guide  Introduction to Locale in the Programming Guide  Include Files ═══ 5.16. ═══ The include file declares the localdtconv, localeconv, and setlocale library functions, which are useful for changing the C locale when you are creating applications for international users. also declares the lconv structure. The table below shows the elements of the lconv structure as well as the defaults for the C locale. ┌──────────────────────┬────────────────────────────────┬────────────┐ │ ELEMENT │ PURPOSE OF ELEMENT │ DEFAULT │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Decimal-point character used │ "." │ │ *decimal_point" │ to format nonmonetary quanti- │ │ │ │ ties. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Character used to separate │ "" │ │ *thousands_sep" │ 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 for- │ │ │ │ matted nonmonetary quantities. │ │ │ │ The value of each character in │ │ │ │ the string determines the │ │ │ │ number of digits in a group. │ │ │ │ A value of "CHAR_MAX" indi- │ │ │ │ cates that there are no │ │ │ │ further groupings. 0 indi- │ │ │ │ cates that the previous │ │ │ │ element is to be used for the │ │ │ │ remainder of the digits. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ International currency symbol │ "" │ │ *int_curr_symbol" │ for the current locale. The │ │ │ │ first three characters contain │ │ │ │ the alphabetic international │ │ │ │ currency symbol. The fourth │ │ │ │ character (usually a space) is │ │ │ │ the character used to separate │ │ │ │ the international currency │ │ │ │ symbol from the monetary quan- │ │ │ │ tity. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Local currency symbol of the │ "" │ │ *currency_symbol" │ current locale. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Decimal-point character used │ "." │ │ *mon_decimal_point" │ to format monetary quantities. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Separator for digits in for- │ "" │ │ *mon_thousands_sep" │ matted monetary quantities. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char *mon_grouping" │ String indicating the size of │ "" │ │ │ each group of digits in for- │ │ │ │ matted monetary quantities. │ │ │ │ The value of each character in │ │ │ │ the string determines the │ │ │ │ number of digits in a group. │ │ │ │ A value of "CHAR_MAX" indi- │ │ │ │ cates that there are no │ │ │ │ further groupings. 0 indi- │ │ │ │ cates that the previous │ │ │ │ element is to be used for the │ │ │ │ remainder of the digits. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ String indicating the positive │ "" │ │ *positive_sign" │ sign used in monetary quanti- │ │ │ │ ties. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ String indicating the negative │ "" │ │ *negative_sign" │ sign used in monetary quanti- │ │ │ │ ties. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ The number of displayed digits │ "UCHAR_MAX"│ │ int_frac_digits" │ to the right of the decimal │ │ │ │ place for internationally for- │ │ │ │ matted monetary quantities. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char frac_digits" │ Number of digits to the right │ "UCHAR_MAX"│ │ │ of the decimal place in mone- │ │ │ │ tary quantities. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char p_cs_precedes" │ 1 if the "currency_symbol" │ "UCHAR_MAX"│ │ │ precedes the value for a non- │ │ │ │ negative formatted monetary │ │ │ │ quantity; 0 if it does not. │ │ └──────────────────────┴────────────────────────────────┴────────────┘ ┌──────────────────────┬────────────────────────────────┬────────────┐ │ "char │ 1 if the "currency_symbol" is │ "UCHAR_MAX"│ │ p_sep_by_space" │ separated by a space from the │ │ │ │ value of a nonnegative for- │ │ │ │ matted monetary quantity; 0 if │ │ │ │ it does not; 2 if a space sep- │ │ │ │ arates the symbol and the sign │ │ │ │ string-if adjacent. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char n_cs_precedes" │ 1 if the "currency_symbol" │ "UCHAR_MAX"│ │ │ precedes the value for a nega- │ │ │ │ tive formatted monetary quan- │ │ │ │ tity; 0 if it does not. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ 1 if the "currency_symbol" is │ "UCHAR_MAX"│ │ n_sep_by_space" │ separated by a space from the │ │ │ │ value of a negative formatted │ │ │ │ monetary quantity; 0 if it │ │ │ │ does not; 2 if a space sepa- │ │ │ │ rates the symbol and the sign │ │ │ │ string-if adjacent. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char p_sign_posn" │ Value indicating the position │ "UCHAR_MAX"│ │ │ of the "positive_sign" for a │ │ │ │ nonnegative formatted monetary │ │ │ │ quantity. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char n_sign_posn" │ Value indicating the position │ "UCHAR_MAX"│ │ │ of the "negative_sign" for a │ │ │ │ negative formatted monetary │ │ │ │ quantity. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Negative-valued monetary │ """" │ │ *left_parenthesis" │ symbol. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char │ Negative-valued monetary │ """" │ │ *right_parenthesis" │ symbol. │ │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char *debit_sign" │ Debit_sign characters. │ "" │ ├──────────────────────┼────────────────────────────────┼────────────┤ │ "char *credit_sign" │ Credit_sign characters. │ "" │ └──────────────────────┴────────────────────────────────┴────────────┘ declares the dtconv structure: struct dtconv { char *abbrev_month_names[12]; /* Abbreviated month names */ char *month_names[12]; /* full month names */ char *abbrev_day_names[7]; /* Abbreviated day names */ char *day_names[7]; /* full day names */ char *date_time_format; /* date and time format */ char *date_format; /* date format */ char *time_format; /* time format */ char *am_string; /* AM string */ char *pm_string; /* PM string */ char *time_format_ampm; /* long date format */ }; The information in each field is equivalent to calling nl_langinfo with these keywords: Keyword Element abmon abbrev_month_names mon month_names abday abbrev_day_names day day_names d_t_fmt date_time_format d_fmt date_format t_fmt time_format am_pm am_string am_pm pm_string t_fmt_ampm time_format_ampm also contains definitions for the following macros: LC_ALL LC_NUMERIC LC_COLLATE LC_TIME LC_CTYPE LC_SYNTAX LC_MESSAGES LC_MONETARY LC_TOD NULL It also contains definitions for the LC_C_* macros, which are provided for compatibility with C Set ++ V2.0. The aspects of a program related to national language, or to cultural characteristics (such as time zone, currency symbols, and sorting order of characters), can be customized at run time using different locales, to suit users' requirements at those locales. The methods for doing so are discussed in the internationalization chapters of the Programming Guide. ═══ Related Information ═══   setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.17. ═══ The include file defines the following memory allocation functions: _alloca calloc _debug_calloc _debug_free _debug_malloc _debug_heapmin _debug_realloc _debug_tcalloc _debug_tfree _debug_theapmin _debug_tmalloc _debug_trealloc _dump_allocated _dump_allocated_delta free _heap_check malloc _mheap _msize realloc _tcalloc _tdump_allocated _tdump_allocated_delta _tfree _theap_check _theapmin _tmalloc _trealloc It also includes a definition for the type size_t. calloc, free, malloc, and realloc are also defined in , as are _alloca and _heapmin. The tiled and debug versions of the memory management functions are also defined in . Heap-specific versions of the memory management functions are defined in . Note: To use the tiled functions, you must compile with the tiled memory (/Gt) option. To use the debug functions, you must compile with the debug memory (/Tm) option. To use the tiled debug functions, you must compile with both the tiled memory and debug memory options (/Gt /Tm). See Differentiating between Memory Management Functions for more information about the different types of memory management functions. also defines a number of far and near pointer macros to the corresponding standard library function. These macros are: _fcalloc _ffree _fheapmin _fmalloc _frealloc _ncalloc _nfree _nheapmin _nmalloc _nrealloc These macros are also defined in . ═══ Related Information ═══    Include Files  #include ═══ 5.18. ═══ The include file declares 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: The Bessel functions are a group of functions named _j0, _j1, _jn, _y0, _y1, and _yn. also includes definitions for the following VisualAge C++ extensions: _atold _cabs _matherr The _atold function is also defined in . 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 , 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 ═══   Include Files  #include ═══ 5.19. ═══ The include file defines the following buffer manipulation functions: memccpy memchr memcmp memcpy memicmp memmove memset Definitions of these functions are also provided in . The include file also defines a number of far and near pointer macros to the corresponding standard library function. These macros are: _fmemccpy _fmemchr _fmemcmp _fmemcpy _fmemicmp _fmemset These macros are also defined in . ═══ Related Information ═══   Include Files  #include ═══ 5.20. ═══ The include file declares the strfmon function. ═══ Related Information ═══   setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.21. ═══ The include file defines the nl_item type for the nl_langinfo function. ═══ Related Information ═══    setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.22. ═══ The include file defines 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, _endthread, abort, exit, and system are also provided in . ═══ Related Information ═══   Include Files  #include ═══ 5.23. ═══ The include file declares the type size_t and defines the following regular expression functions: regcomp regerror regexec regfree also declares the regex_t type, which is capable of storing a compiled regular expression, and the following macros: REG_EXTENDED REG_ICASE REG_NEWLINE REG_NOSUB Values of the cflags parameter of the regcomp function REG_NOTBOL REG_NOTEOL Values of the eflags parameter of the regexec function REG_* Values of the errcode parameter of the regerror function ═══ Related Information ═══  Include Files  #include ═══ 5.24. ═══ The include file defines the following search functions: bsearch lfind lsearch qsort It also defines the type size_t. Definitions for bsearch and qsort are also provided in . ═══ Related Information ═══   Include Files  #include ═══ 5.25. ═══ The include file declares 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 ═══  Include Files  #include ═══ 5.26. ═══ The include file defines constants used by the following functions: creat fdopen open _sopen The definitions for the above functions are also included in . Additional constants for open and _sopen are provided in . ═══ Related Information ═══    Include Files  #include ═══ 5.27. ═══ The include file defines the values for signals and declares the signal and raise functions. also defines the following macros: SIGABRT SIGBREAK SIG_DFL SIG_ERR SIGFPE SIG_IGN SIGILL SIGINT SIGSEGV SIGTERM SIGUSR1 SIGUSR2 SIGUSR3 also defines the type sig_atomic_t. ═══ Related Information ═══  Include Files  #include ═══ 5.28. ═══ The include file defines macros that allow you access to arguments in functions with variable-length argument lists: va_arg, va_start, and va_end. also defines the type va_list. ═══ Related Information ═══  Include Files  #include ═══ 5.29. ═══ The include file defines 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. 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 . 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) In extended mode, also contains definitions of the global variables errno and _threadid. errno is also defined in for extended mode, and in in ANSI and SAA modes. ═══ Related Information ═══     Include Files  #include ═══ 5.30. ═══ The include file defines constants, macros, and types, and declares 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, also defines the following extensions: _fcloseall _fgetchar fileno _flushall _fputchar _rmtmp _set_crt_msg_handle tempnam unlink The unlink function is also defined in . 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 . The FILE structure type is defined in . 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 . 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 for use with fgetpos and fsetpos. ═══ Related Information ═══      Include Files  #include ═══ 5.31. ═══ The include file declares 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, also defines the following standard extensions: _alloca _atold _beginthread _crotl _crotr _debug_calloc _debug_free _debug_heapmin _debug_malloc _debug_realloc _debug_tcalloc _debug_tfree _debug_theapmin _debug_tmalloc _debug_trealloc _dump_allocated _dump_allocated_delta _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 _srotl _srotr strtold swab _tcalloc _tdump_allocated _tdump_allocated_delta _tfree _theap_check _theapmin _threadstore _tmalloc _trealloc _ultoa Note: 1. To use the debug memory management functions (_debug_calloc, _dump_allocated, and so on), you must compile with the debug memory (/Tm) option. 2. To use the tiled memory management functions (_tcalloc and so on) you must compile with the tiled memory (/Gt) option. 3. To use tiled debug functions (_debug_tcalloc, _tdump_allocated, and so on), you must compile with the debug memory and tiled memory options (/Tm /Gt). For a description of how these functions differ, see Differentiating between Memory Management Functions. For more information about the memory management functions, see Memory Management in the Programming Guide. also contains definitions for the following macros: 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 . 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 integral expression 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 . In extended mode, also defines the following global variables: _doserrno _environ errno onexit_t _osmajor _osminor _osmode The variable errno is also defined in . The variable _doserrno and the SAA definition of errno are provided in . also 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 . ═══ Related Information ═══      Include Files  #include ═══ 5.32. ═══ The 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, also defines the following standard extensions: memccpy memicmp strcmpi strdup _strerror stricmp strlwr strnicmp strnset strrev strset strupr The memxxxx functions are also included in . also defines the macro NULL and the type size_t. These definitions are also provided in . NULL is also defined in . 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 . ═══ Related Information ═══      Include Files  #include ═══ 5.33. ═══ The include file defines 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 . Other low-level I/O functions are defined in . ═══ Related Information ═══    Include Files  #include ═══ 5.34. ═══ The include file defines the _ftime function and also defines the type time_t and the structure timeb. ═══ Related Information ═══  Include Files  #include ═══ 5.35. ═══ The include file defines the following types: ino_t time_t dev_t off_t These types are also defined in . ═══ Related Information ═══   Include Files  #include ═══ 5.36. ═══ The include file defines the utime function, the structure utimbuf, and the type time_t. ═══ Related Information ═══  Include Files  #include ═══ 5.37. ═══ The include file declares the time and date functions: asctime clock ctime difftime gmtime localtime mktime strftime time In extended mode, also defines the standard extensions _strdate, _strtime, and _tzset. also provides:  A structure tm containing the components of a calendar time. See gmtime - Convert Time for a list of the members of the tm structure.  A macro CLOCKS_PER_SEC equal to the number per second of the value returned by the clock function.  Types clock_t, time_t, and size_t.  The NULL pointer value. For more information on NULL and the type size_t, see . also defines the global variables _daylight, _timezone, and _tzname. ═══ Related Information ═══   Include Files  #include ═══ 5.38. ═══ The include file defines the memory allocation functions that are heap-specific: _debug_ucalloc _debug_uheapmin _debug_umalloc _mheap _uaddmem _ucalloc _uclose _ucreate _udefault _udestroy _udump_allocated _udump_allocated_delta _uheapchk _uheap_check _uheapmin _uheapset _uheap_walk _umalloc _uopen also defines macros used by the heap-specific functions. Definitions for the non-heap-specific memory management functions are located in and in . Note: To use the debug versions of memory management functions, specify the debug memory (/Tm) compiler option. ═══ Related Information ═══    Memory Management in the Programming Guide  Include Files  #include ═══ 5.39. ═══ The include file declares the getsyntx function and for the struct variant type: struct variant { char *codeset; /* code set of the current locale */ char backslash; /* encoding of \ */ char right_bracket; /* encoding of ] */ char left_bracket; /* encoding of [ */ char right_brace; /* encoding of } */ char left_brace; /* encoding of { */ char circumflex; /* encoding of ^ */ char tilde; /* encoding of ~ */ char exclamation_mark; /* encoding of ! */ char number_sign; /* encoding of # */ char vertical_line; /* encoding of | */ char dollar_sign; /* encoding of $ */ char commercial_at; /* encoding of @ */ char grave_accent; /* encoding of ` */ } ═══ Related Information ═══   setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.40. ═══ The include file declares the supported subset of the ISO/C Multibyte Support extensions defined in ISO/IEC 9899:1990/Amendment 1:1993(E) extensions. The following functions are declared in : fgetwc fgetws fputwc fputws getwc getwchar mbrlen mbrtowc mbsrtowcs putwc putwchar swprintf swscanf ungetwc vswprintf wcrtomb wcscat wcschr wcscmp wcscoll wcscpy wcscspn wcsftime wcslen wcsncat wcsncmp wcsncpy wcspbrk wcsrchr wcsrtombs wcsspn wcsstr wcstod wcstok wcstol wcstoul wcswidth wcsxfrm wctob wcwidth You do not need to include and to use this include file. also defines the following types and constants: mbstate_t Conversion state information needed when converting between sequences of multibyte characters and wide characters. size_t typedef for the type of the value returned by sizeof. wchar_t typedef for a wide character constant. wint_t An integral type unchanged by integral promotions, that can hold any value corresponding to members of the extended character set, as well as WEOF (see below). FILE The FILE structure type is defined in . Stream 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 . va_list This type is also defined in . NULL A pointer that never points to a data object. WEOF Expands to a constant expression of type wint_t, whose value does not correspond to any member of the extended character set. It indicates EOF. You can perform wide character input/output on the streams described in the ISO/IEC 9899:1990 standard, subclause 7.9.2. This standard expands the definition of a stream to include an orientation for both text and binary streams. After you have associated a stream with an external file, but before you have performed any operations on it, the stream does not have any orientation. Once you apply a wide character input or output function to a stream that does not have orientation, the stream becomes wide-oriented. Similarly, once you apply a byte input or output function to a stream without orientation, the stream becomes byte-oriented. After you establish a stream's orientation, the only way to change it is to make a successful call to the freopen function, which removes a stream's orientation. ═══ Related Information ═══    setlocale - Set Locale  Introduction to Locale in the Programming Guide  Include Files  #include ═══ 5.41. ═══ 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 ═══  Include Files  #include ═══ 5.42. ═══ The file declares functions used to classify wide characters: iswalnum iswalpha iswblank iswcntrl iswctype iswctype iswdigit iswgraph iswlower iswprint iswpunct iswspace iswupper iswxdigit towlower towupper wctype wctype.h also defines the types wint_t and wctype_t, and the macro WEOF, which expands to a constant expression of type wint_t whose value does not correspond to any member of the extended character set and indicates EOF. ═══ Related Information ═══    Include Files  #include