Compaq_C____________________________________________ Run-Time Library Reference Manual for OpenVMS Systems Order Number: AA-PUNEH-TK February 2001 This manual describes the functions and macros in the Compaq C Run-Time Library for OpenVMS systems. Revision/Update Information: This revised manual supersedes the DEC C Run-Time Library Reference Manual for OpenVMS Systems (Order No. AA-PUNEG-TK). Software Version: Compaq C Version 6.4 for OpenVMS Systems Compaq Computer Corporation Houston, Texas ________________________________________________________________ First Printing, February 1991 Revised, November 1992 Revised, June 1993 Revised, May 1994 Revised, May 1995 Revised, November 1995 Revised, December 1998 Revised, November 1999 Revised, February 2001 © 2001 Compaq Computer Corporation. COMPAQ, the Compaq logo, VAX, Alpha, VMS, and OpenVMS are registered in the U.S. Patent and Trademark Office. Tru64 is a trademark of Compaq Information Technologies Group, L.P. in the United States and other countries. UNIX is a trademark of The Open Group in the United States and other countries. All other product names mentioned herein may be trademarks of their respective companies. Confidential computer software. Valid license from Compaq required for possession, use, or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. Compaq shall not be liable for technical or editorial errors or omissions contained herein. The information in this document is provided as is without warranty of any kind and is subject to change without notice. The warranties for Compaq products are set forth in the express limited warranty statements accompanying such products. Nothing herein should be construed as constituting an additional warranty. ZK5763 This document is available on CD-ROM. This document was prepared using VAX DOCUMENT Version 2.1. ________________________________________________________________ Portions of the Compaq C Run-Time Library have been implemented using source copyrighted by the University of California, Berkley and its contributors. Copyright (c) 1981 Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the University of California, Berkeley and its contributors. 4. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. _________________________________________________________________ Contents Preface................................................... xxiii 1 Introduction 1.1 Using the Compaq C Run-Time Library........... 1-3 1.2 RTL Linking Options on Alpha Systems (Alpha only).................................. 1-4 1.2.1 Linking with the Shareable Image.......... 1-4 1.2.2 Linking with the Object Libraries......... 1-6 1.2.3 Examples.................................. 1-7 1.3 RTL Linking Options on VAX Systems (VAX only).................................... 1-10 1.3.1 Linking with the Compaq C RTL............. 1-11 1.3.1.1 Linking with the Compaq C RTL Shareable Images.................................. 1-11 1.3.1.2 Linking with or Providing Your Own Shareable Images........................ 1-12 1.3.1.3 Linking with the Compaq C RTL Object Libraries............................... 1-13 1.3.1.4 Linking with the Compaq C RTL Object Libraries /NOSYSSHR..................... 1-14 1.3.2 Resolving Link-Time Conflicts with Multiple C RTLs........................... 1-15 1.3.2.1 Using VAXC$LCL.OPT...................... 1-16 1.3.2.2 Using VAXC$EMPTY.EXE.................... 1-17 1.3.2.3 Using DECC$EMPTY.EXE.................... 1-18 1.3.3 Linking Examples for Compaq C or Compaq C++ Code Only............................. 1-20 1.3.4 Linking Examples for VAX C and Compaq C Code Combined............................. 1-21 1.3.5 Linking with the VAX C RTL /NOSYSSHR...... 1-22 1.4 Compaq C RTL Function Prototypes and Syntax... 1-23 1.4.1 Function Prototypes....................... 1-23 v 1.4.2 Syntax Conventions for Function Prototypes................................ 1-24 1.4.3 UNIX Style File Specifications............ 1-25 1.5 Feature-Test Macros for Header-File Control... 1-29 1.5.1 Standards Macros.......................... 1-29 1.5.2 Selecting a Standard...................... 1-30 1.5.3 Interactions with the /STANDARD Qualifier................................. 1-32 1.5.4 Multiple-Version-Support Macro............ 1-35 1.5.5 Compatibility Modes....................... 1-35 1.5.6 Curses and Socket Compatibility Macros.... 1-37 1.6 Input and Output on OpenVMS Systems........... 1-38 1.6.1 RMS Record and File Formats............... 1-41 1.6.2 Access to RMS Files....................... 1-43 1.6.2.1 Accessing RMS Files in Stream Mode...... 1-44 1.6.2.2 Accessing RMS Record Files in Record Mode.................................... 1-45 1.6.2.2.1 Accessing Variable-Length or VFC Record Files in Record Mode................... 1-48 1.6.2.2.2 Accessing Fixed-Length Record Files in Record Mode............................ 1-49 1.6.2.3 Example-Difference Between Stream Mode and Record Mode......................... 1-50 1.7 Specific Portability Concerns................. 1-53 1.7.1 Reentrancy................................ 1-56 1.7.2 Multithread Restrictions.................. 1-59 1.8 64-bit Pointer Support (Alpha only)........... 1-60 1.8.1 Using the Compaq C Run-Time Library....... 1-61 1.8.2 Obtaining 64-bit Pointers to Memory....... 1-62 1.8.3 Compaq C Header Files..................... 1-62 1.8.4 Functions Affected........................ 1-64 1.8.4.1 No Pointer-Size Impact.................. 1-64 1.8.4.2 Functions Accepting Both Pointer Sizes................................... 1-65 1.8.4.3 Functions with Two Implementations...... 1-65 1.8.4.4 Functions Restricted to 32-Bit Pointers................................ 1-67 1.8.5 Reading Header Files...................... 1-68 vi 2 Understanding Input and Output 2.1 Using RMS from RTL Routines................... 2-6 2.2 UNIX I/O and Standard I/O..................... 2-7 2.3 Wide-Character Versus Byte I/O Functions...... 2-9 2.4 Conversion Specifications..................... 2-10 2.4.1 Converting Input Information.............. 2-11 2.4.2 Converting Output Information............. 2-24 2.5 Terminal I/O.................................. 2-38 2.6 Program Examples.............................. 2-39 3 Character, String, and Argument-List Functions 3.1 Character-Classification Functions............ 3-7 3.2 Character-Conversion Functions................ 3-14 3.3 String and Argument-List Functions............ 3-16 3.4 Program Examples.............................. 3-18 4 Error and Signal Handling 4.1 Error Handling................................ 4-3 4.2 Signal Handling............................... 4-7 4.2.1 OpenVMS Versus UNIX Terminology........... 4-8 4.2.2 UNIX Signals and the Compaq C RTL......... 4-8 4.2.3 Signal-Handling Concepts.................. 4-11 4.2.4 Signal Actions............................ 4-12 4.2.5 Signal Handling and OpenVMS Exception Handling.................................. 4-14 4.3 Program Example............................... 4-20 5 Subprocess Functions 5.1 Implementing Child Processes in Compaq C...... 5-2 5.2 The exec Functions............................ 5-4 5.2.1 Exec Processing........................... 5-5 5.2.2 Exec Error Conditions..................... 5-6 5.3 Synchronizing Processes....................... 5-7 5.4 Interprocess Communication.................... 5-7 5.5 Program Examples.............................. 5-7 vii 6 Curses Screen Management Functions and Macros 6.1 Using the BSD-Based Curses Package (Alpha only).................................. 6-2 6.2 Curses Overview............................... 6-2 6.3 Curses Terminology............................ 6-7 6.3.1 Predefined Windows (stdscr and curscr).... 6-8 6.3.2 User-Defined Windows...................... 6-9 6.4 Getting Started with Curses................... 6-11 6.5 Predefined Variables and Constants............ 6-15 6.6 Cursor Movement............................... 6-16 6.7 Program Example............................... 6-18 7 Math Functions 7.1 Math Function Variants-float, double, long double........................................ 7-3 7.2 Error Detection............................... 7-5 7.3 The Header File........................ 7-6 7.4 Example....................................... 7-7 8 Memory Allocation Functions 8.1 Program Example............................... 8-2 9 System Functions 10 Developing International Software 10.1 Internationalization Support.................. 10-1 10.1.1 Installation.............................. 10-1 10.1.2 Unicode Support........................... 10-2 10.2 Features of International Software............ 10-2 10.3 Developing International Software Using Compaq C...................................... 10-4 10.4 Locales....................................... 10-5 10.5 Using the setlocale Function to Set Up an International Environment..................... 10-6 10.6 Using Message Catalogs........................ 10-8 10.7 Handling Different Character Sets............. 10-8 10.7.1 Charmap File.............................. 10-9 10.7.2 Converter Functions....................... 10-9 10.7.3 Using Codeset Converter Files............. 10-9 viii 10.8 Handling Culture-Specific Information......... 10-11 10.8.1 Extracting Cultural Information From a Locale.................................... 10-12 10.8.2 Date and Time Formatting Functions........ 10-12 10.8.3 Monetary Formatting Function.............. 10-12 10.8.4 Numeric Formatting........................ 10-13 10.9 Functions for Handling Wide Characters........ 10-13 10.9.1 Character Classification Functions........ 10-13 10.9.2 Case Conversion Functions................. 10-14 10.9.3 Functions for Input and Output of Wide Characters................................ 10-14 10.9.4 Functions for Converting Multibyte and Wide Characters........................... 10-15 10.9.5 Functions for Manipulating Wide-Character Strings and Arrays........................ 10-16 10.10 Collating Functions........................... 10-16 11 Date/Time Functions 11.1 Date/Time Support Models...................... 11-2 11.2 Overview of Date/Time Functions............... 11-3 11.3 Compaq C RTL Date/Time Computations-UTC and Local Time.................................... 11-4 11.4 Time-Zone Conversion Rule Files............... 11-6 11.5 Sample Date/Time Scenario..................... 11-8 Reference Section abort............................................... REF-3 abs................................................. REF-4 access.............................................. REF-5 acos................................................ REF-7 [w]addch............................................ REF-8 [w]addstr........................................... REF-10 ix alarm............................................... REF-11 asctime, asctime_r.................................. REF-12 asin................................................ REF-14 assert.............................................. REF-15 atan................................................ REF-17 atan2............................................... REF-18 atexit.............................................. REF-19 atof................................................ REF-21 atoi, atol.......................................... REF-22 atoq, atoll (Alpha only)............................ REF-23 basename............................................ REF-24 bcmp................................................ REF-26 bcopy............................................... REF-27 box................................................. REF-28 brk................................................. REF-29 bsearch............................................. REF-31 btowc............................................... REF-34 bzero............................................... REF-35 cabs................................................ REF-36 calloc.............................................. REF-37 catclose............................................ REF-38 catgets ............................................ REF-39 catopen............................................. REF-43 ceil................................................ REF-47 cfree............................................... REF-48 chdir............................................... REF-49 chmod............................................... REF-51 chown............................................... REF-53 [w]clear............................................ REF-54 clearerr............................................ REF-55 x clearok............................................. REF-56 clock............................................... REF-57 close............................................... REF-58 closedir............................................ REF-60 [w]clrattr.......................................... REF-63 [w]clrtobot......................................... REF-64 [w]clrtoeol......................................... REF-65 confstr............................................. REF-66 cos................................................. REF-69 cosh................................................ REF-70 cot................................................. REF-71 creat............................................... REF-72 [no]crmode.......................................... REF-81 ctermid ............................................ REF-83 ctime, ctime_r...................................... REF-84 cuserid ............................................ REF-86 DECC$CRTL_INIT...................................... REF-87 decc$fix_time....................................... REF-88 decc$from_vms ...................................... REF-90 decc$match_wild .................................... REF-92 decc$record_read.................................... REF-94 decc$record_write................................... REF-95 decc$set_child_standard_streams..................... REF-96 decc$set_reentrancy.................................REF-102 decc$to_vms ........................................REF-104 decc$translate_vms .................................REF-107 decc$validate_wchar.................................REF-109 decc$write_eof_to_mbx...............................REF-111 [w]delch............................................REF-115 delete..............................................REF-116 xi [w]deleteln.........................................REF-118 delwin..............................................REF-119 difftime............................................REF-120 dirname ............................................REF-121 div.................................................REF-123 dlclose.............................................REF-124 dlerror.............................................REF-125 dlopen..............................................REF-126 dlsym...............................................REF-128 drand48.............................................REF-129 dup, dup2...........................................REF-131 [no]echo............................................REF-132 ecvt................................................REF-133 endwin..............................................REF-135 erand48.............................................REF-136 [w]erase............................................REF-138 execl...............................................REF-139 execle..............................................REF-141 execlp..............................................REF-143 execv...............................................REF-144 execve..............................................REF-145 execvp..............................................REF-147 exit, _exit.........................................REF-148 exp.................................................REF-150 fabs................................................REF-151 fchown..............................................REF-152 fclose..............................................REF-154 fcntl...............................................REF-155 fcvt................................................REF-159 fdopen..............................................REF-161 xii feof................................................REF-162 ferror..............................................REF-163 fflush..............................................REF-164 ffs.................................................REF-165 fgetc...............................................REF-166 fgetname ...........................................REF-167 fgetpos.............................................REF-169 fgets ..............................................REF-171 fgetwc..............................................REF-173 fgetws .............................................REF-175 fileno..............................................REF-178 floor...............................................REF-179 fmod................................................REF-180 fopen...............................................REF-181 fp_class, fp_classf, fp_classl (Alpha only).........REF-184 fpathconf...........................................REF-186 fprintf.............................................REF-189 fputc...............................................REF-192 fputs...............................................REF-193 fputwc..............................................REF-194 fputws..............................................REF-196 fread...............................................REF-197 free................................................REF-199 freopen.............................................REF-200 frexp...............................................REF-202 fscanf..............................................REF-204 fseek...............................................REF-207 fsetpos.............................................REF-209 fstat...............................................REF-210 fsync...............................................REF-214 xiii ftell...............................................REF-215 ftime...............................................REF-216 ftruncate...........................................REF-218 ftw.................................................REF-219 fwait...............................................REF-222 fwide...............................................REF-223 fwprintf............................................REF-225 fwrite..............................................REF-229 fwscanf.............................................REF-231 gcvt ...............................................REF-233 getc................................................REF-235 [w]getch............................................REF-236 getchar.............................................REF-237 getclock............................................REF-238 getcwd .............................................REF-240 getdtablesize.......................................REF-242 getegid.............................................REF-243 getenv..............................................REF-244 geteuid.............................................REF-246 getgid..............................................REF-248 getitimer...........................................REF-249 getlogin............................................REF-251 getname ............................................REF-252 getopt..............................................REF-254 getpagesize.........................................REF-259 getpid..............................................REF-260 getppid.............................................REF-261 getpwnam............................................REF-262 getpwuid............................................REF-264 gets ...............................................REF-266 xiv [w]getstr...........................................REF-268 gettimeofday........................................REF-269 getuid..............................................REF-270 getw................................................REF-272 getwc...............................................REF-273 getwchar............................................REF-274 getyx...............................................REF-275 gmtime, gmtime_r....................................REF-276 gsignal.............................................REF-278 hypot...............................................REF-280 iconv...............................................REF-281 iconv_close.........................................REF-283 iconv_open..........................................REF-284 [w]inch.............................................REF-288 index ..............................................REF-289 initscr.............................................REF-290 initstate...........................................REF-291 [w]insch............................................REF-293 [w]insertln.........................................REF-294 [w]insstr...........................................REF-295 isalnum.............................................REF-296 isalpha.............................................REF-297 isapipe.............................................REF-298 isascii.............................................REF-299 isatty..............................................REF-300 iscntrl.............................................REF-301 isdigit.............................................REF-302 isgraph.............................................REF-303 islower.............................................REF-304 isprint.............................................REF-305 xv ispunct.............................................REF-306 isspace.............................................REF-307 isupper.............................................REF-308 iswalnum............................................REF-309 iswalpha............................................REF-310 iswcntrl............................................REF-311 iswctype............................................REF-312 iswdigit............................................REF-315 iswgraph............................................REF-316 iswlower............................................REF-317 iswprint............................................REF-318 iswpunct............................................REF-319 iswspace............................................REF-320 iswupper............................................REF-321 iswxdigit...........................................REF-322 isxdigit............................................REF-323 jrand48.............................................REF-324 kill................................................REF-326 labs................................................REF-328 lcong48.............................................REF-329 ldexp...............................................REF-331 ldiv................................................REF-332 leaveok.............................................REF-333 link................................................REF-334 localeconv..........................................REF-336 localtime, localtime_r..............................REF-342 log, log10..........................................REF-345 longjmp.............................................REF-346 longname ...........................................REF-349 lrand48.............................................REF-350 xvi lseek...............................................REF-352 lwait...............................................REF-354 malloc .............................................REF-355 mblen...............................................REF-357 mbrlen..............................................REF-358 mbrtowc.............................................REF-360 mbstowcs............................................REF-362 mbtowc..............................................REF-364 mbsinit.............................................REF-366 mbsrtowcs ..........................................REF-367 memccpy ............................................REF-369 memchr .............................................REF-371 memcmp..............................................REF-372 memcpy .............................................REF-373 memmove ............................................REF-374 memset .............................................REF-376 mkdir...............................................REF-377 mkstemp.............................................REF-381 mktemp .............................................REF-382 mktime..............................................REF-383 mmap ...............................................REF-385 modf................................................REF-392 [w]move.............................................REF-393 mprotect............................................REF-394 mrand48.............................................REF-396 msync...............................................REF-398 munmap..............................................REF-401 mv[w]addch..........................................REF-403 mv[w]addstr.........................................REF-405 mvcur...............................................REF-407 xvii mv[w]delch..........................................REF-408 mv[w]getch..........................................REF-409 mv[w]getstr.........................................REF-410 mv[w]inch...........................................REF-411 mv[w]insch..........................................REF-412 mv[w]insstr.........................................REF-413 mvwin...............................................REF-414 newwin..............................................REF-415 nice................................................REF-416 [no]nl..............................................REF-417 nl_langinfo.........................................REF-418 nrand48.............................................REF-424 open................................................REF-426 opendir.............................................REF-430 overlay.............................................REF-432 overwrite...........................................REF-433 pathconf............................................REF-434 pause...............................................REF-437 pclose..............................................REF-438 perror..............................................REF-439 pipe................................................REF-441 popen...............................................REF-446 pow.................................................REF-448 printf..............................................REF-450 [w]printw...........................................REF-451 putc................................................REF-453 putchar.............................................REF-454 putenv..............................................REF-455 puts................................................REF-457 putw................................................REF-458 xviii putwc...............................................REF-459 putwchar............................................REF-460 qabs, llabs (Alpha only)............................REF-461 qdiv, lldiv (Alpha only)............................REF-462 qsort...............................................REF-463 raise...............................................REF-465 rand................................................REF-467 random..............................................REF-468 [no]raw.............................................REF-470 read................................................REF-472 readdir, readdir_r..................................REF-475 realloc ............................................REF-478 [w]refresh..........................................REF-480 remove..............................................REF-481 rename..............................................REF-482 rewind..............................................REF-484 rewinddir...........................................REF-485 rindex .............................................REF-486 rmdir...............................................REF-487 sbrk................................................REF-488 scanf...............................................REF-489 [w]scanw............................................REF-491 scroll..............................................REF-493 scrollok............................................REF-494 seed48..............................................REF-495 seekdir.............................................REF-497 [w]setattr..........................................REF-498 setbuf..............................................REF-499 setenv..............................................REF-501 setgid..............................................REF-502 xix setitimer...........................................REF-504 setjmp..............................................REF-506 setlocale...........................................REF-509 setstate............................................REF-514 setuid..............................................REF-516 setvbuf.............................................REF-518 sigaction...........................................REF-521 sigaddset...........................................REF-525 sigblock............................................REF-527 sigdelset...........................................REF-528 sigemptyset.........................................REF-529 sigfillset..........................................REF-531 sigismember.........................................REF-532 siglongjmp..........................................REF-533 sigmask.............................................REF-535 signal..............................................REF-536 sigpause............................................REF-538 sigpending..........................................REF-539 sigprocmask.........................................REF-540 sigsetjmp...........................................REF-543 sigsetmask..........................................REF-545 sigstack (VAX only).................................REF-546 sigsuspend..........................................REF-548 sigvec..............................................REF-550 sin.................................................REF-552 sinh................................................REF-553 sleep...............................................REF-554 sprintf.............................................REF-555 sqrt................................................REF-557 srand...............................................REF-558 xx srand48.............................................REF-559 srandom.............................................REF-560 sscanf..............................................REF-561 ssignal.............................................REF-563 [w]standend.........................................REF-565 [w]standout.........................................REF-566 stat................................................REF-567 strcasecmp..........................................REF-572 strcat .............................................REF-573 strchr .............................................REF-575 strcmp..............................................REF-577 strcoll.............................................REF-578 strcpy .............................................REF-579 strcspn.............................................REF-580 strdup .............................................REF-581 strerror............................................REF-582 strfmon.............................................REF-584 strftime............................................REF-590 strlen..............................................REF-599 strncasecmp.........................................REF-600 strncat ............................................REF-601 strncmp.............................................REF-602 strncpy ............................................REF-604 strnlen.............................................REF-606 strpbrk ............................................REF-607 strptime ...........................................REF-608 strrchr ............................................REF-616 strsep .............................................REF-617 strspn..............................................REF-619 strstr .............................................REF-620 xxi strtod .............................................REF-622 strtok .............................................REF-624 strtol .............................................REF-627 strtoq, strtoll (Alpha only)........................REF-629 strtoul ............................................REF-631 strtouq, strtoull (Alpha only)......................REF-633 strxfrm.............................................REF-635 subwin..............................................REF-640 swab................................................REF-642 swprintf............................................REF-643 swscanf.............................................REF-645 sysconf.............................................REF-647 system..............................................REF-658 tan.................................................REF-660 tanh................................................REF-661 telldir.............................................REF-662 tempnam.............................................REF-663 time................................................REF-665 times...............................................REF-666 tmpfile.............................................REF-668 tmpnam .............................................REF-669 toascii.............................................REF-670 tolower.............................................REF-671 _tolower............................................REF-672 touchwin............................................REF-673 toupper.............................................REF-674 _toupper............................................REF-675 towctrans...........................................REF-676 towlower............................................REF-677 towupper............................................REF-678 xxii truncate............................................REF-679 ttyname.............................................REF-680 tzset...............................................REF-681 ualarm..............................................REF-688 umask...............................................REF-690 uname...............................................REF-692 ungetc..............................................REF-693 ungetwc.............................................REF-694 utime...............................................REF-696 utimes..............................................REF-700 unsetenv............................................REF-704 usleep..............................................REF-705 VAXC$CRTL_INIT......................................REF-706 VAXC$ESTABLISH......................................REF-708 va_arg..............................................REF-710 va_count............................................REF-711 va_end..............................................REF-712 va_start_1, va_start................................REF-713 vfork...............................................REF-716 vfprintf............................................REF-718 vfwprintf...........................................REF-719 vprintf.............................................REF-723 vswprintf...........................................REF-724 vwprintf............................................REF-727 vsprintf............................................REF-729 wait................................................REF-730 wait3...............................................REF-732 wait4...............................................REF-737 waitpid.............................................REF-742 wcrtomb.............................................REF-747 xxiii wcscat .............................................REF-749 wcschr .............................................REF-752 wcscmp..............................................REF-754 wcscoll.............................................REF-756 wcscpy .............................................REF-757 wcscspn.............................................REF-758 wcsftime............................................REF-761 wcslen..............................................REF-771 wcsncat ............................................REF-772 wcsncmp.............................................REF-775 wcsncpy ............................................REF-777 wcspbrk ............................................REF-779 wcsrchr ............................................REF-781 wcsrtombs ..........................................REF-784 wcsspn..............................................REF-787 wcsstr .............................................REF-790 wcstod..............................................REF-791 wcstok .............................................REF-793 wcstol .............................................REF-797 wcstombs............................................REF-799 wcstoul ............................................REF-801 wcswcs .............................................REF-804 wcswidth............................................REF-807 wcsxfrm.............................................REF-808 wctob...............................................REF-813 wctomb..............................................REF-814 wctrans.............................................REF-815 wctype..............................................REF-817 wcwidth.............................................REF-822 wmemchr ............................................REF-823 xxiv wmemcmp.............................................REF-825 wmemcpy ............................................REF-826 wmemmove ...........................................REF-827 wmemset ............................................REF-829 wprintf.............................................REF-830 wrapok..............................................REF-833 write...............................................REF-834 writev..............................................REF-836 wscanf..............................................REF-838 A Compaq C Socket Routine Reference A.1 Porting Considerations........................ A-1 A.1.1 Calling an IPC Routine from an AST State..................................... A-1 A.1.2 Calling from KERNEL or EXEC Modes......... A-2 A.1.3 Event Flags............................... A-2 A.1.4 Suppressing Compaq C Compilation Warnings.................................. A-2 A.1.5 Header Files.............................. A-2 A.2 Compaq C Structures........................... A-3 A.3 Internet Protocols............................ A-3 A.3.1 Transmission Control Protocol............. A-4 A.3.2 User Datagram Protocol.................... A-5 A.4 errno Values.................................. A-5 A.5 h_errno Values................................ A-10 A.6 Relationship Between errno and h_errno........ A-11 A.7 TCP/IP Interface Enhancements................. A-13 A.8 Summary of Socket Routines.................... A-14 A.8.1 Basic Communication Routines.............. A-14 A.8.2 Auxiliary Communication Routines.......... A-15 A.8.3 h_errno Support Routines.................. A-15 A.8.4 Communication Support Routines............ A-16 accept.............................................. A-19 xxv bind................................................ A-22 close............................................... A-24 connect............................................. A-25 decc$get_sdc........................................ A-28 endhostent.......................................... A-29 endnetent........................................... A-30 endprotoent......................................... A-31 endservent.......................................... A-32 gethostaddr......................................... A-33 gethostbyaddr....................................... A-34 gethostbyname....................................... A-36 gethostent.......................................... A-38 gethostname......................................... A-39 getnetbyaddr........................................ A-40 getnetbyname........................................ A-41 getnetent........................................... A-43 getpeername......................................... A-44 getprotobyname...................................... A-46 getprotobynumber.................................... A-47 getprotoent......................................... A-48 getservbyname....................................... A-49 getservbyport....................................... A-51 getservent.......................................... A-52 getsockname......................................... A-53 getsockopt.......................................... A-55 herror.............................................. A-57 hstrerror........................................... A-58 hostalias........................................... A-59 htonl............................................... A-60 htons............................................... A-62 xxvi inet_addr........................................... A-64 inet_lnaof.......................................... A-66 inet_makeaddr....................................... A-67 inet_netof.......................................... A-68 inet_network........................................ A-69 inet_ntoa........................................... A-70 ioctl............................................... A-71 listen.............................................. A-73 ntohl............................................... A-75 ntohs............................................... A-77 read................................................ A-79 recv................................................ A-81 recvfrom............................................ A-84 recvmsg............................................. A-87 select.............................................. A-90 send................................................ A-94 sendmsg............................................. A-96 sendto.............................................. A-99 sethostent.......................................... A-102 setnetent........................................... A-103 setprotoent......................................... A-104 setservent.......................................... A-106 setsockopt.......................................... A-107 shutdown............................................ A-110 socket.............................................. A-112 decc$socket_fd...................................... A-115 vaxc$get_sdc........................................ A-116 write............................................... A-117 A.9 Programming Examples.......................... A-119 B Version-Dependency Tables B.1 Functions Available on all OpenVMS VAX and OpenVMS Alpha Versions........................ B-1 B.2 Functions Available on OpenVMS Version 6.2 and Higher........................................ B-4 B.3 Functions Available on OpenVMS Version 7.0 and Higher........................................ B-5 xxvii B.4 Functions Available on OpenVMS Alpha Version 7.0 and Higher................................ B-7 B.5 Functions Available on OpenVMS Version 7.2 and Higher........................................ B-9 B.6 Functions Available on OpenVMS Version 7.3 and Higher........................................ B-9 C Prototypes Duplicated to Non-Standard Headers Index Examples 1-1 Differences Between Stream Mode and Record Mode...................................... 1-50 2-1 Output of the Conversion Specifications... 2-39 2-2 Using the Standard I/O Functions.......... 2-42 2-3 Using Wide Character I/O Functions........ 2-43 2-4 I/O Using File Descriptors and Pointers... 2-45 3-1 Character-Classification Functions........ 3-13 3-2 Converting Double Values to an ASCII String.................................... 3-15 3-3 Changing Characters to and from Uppercase Letters................................... 3-16 3-4 Concatenating Two Strings................. 3-18 3-5 Four Arguments to the strcspn Function.... 3-18 3-6 Using the Functions and Definitions............................... 3-19 4-1 Suspending and Resuming Programs.......... 4-21 5-1 Creating the Child Process................ 5-7 5-2 Passing Arguments to the Child Process.... 5-10 5-3 Checking the Status of Child Processes.... 5-12 5-4 Communicating Through a Pipe.............. 5-13 6-1 A Curses Program.......................... 6-11 6-2 Manipulating Windows...................... 6-12 6-3 Refreshing the Terminal Screen............ 6-14 6-4 Curses Predefined Variables............... 6-15 6-5 The Cursor Movement Functions............. 6-17 xxviii 6-6 stdscr and Occluding Windows.............. 6-18 7-1 Calculating and Verifying a Tangent Value..................................... 7-7 8-1 Allocating and Deallocating Memory for Structures................................ 8-2 9-1 Accessing the User Name................... 9-5 9-2 Accessing Terminal Information............ 9-6 9-3 Manipulating the Default Directory........ 9-7 9-4 Printing the Date and Time................ 9-7 A-1 TCP/IP Server............................. A-119 A-2 TCP/IP Client............................. A-128 A-3 UDP/IP Server............................. A-136 A-4 UDP/IP Client............................. A-145 Figures 1-1 Linking with the Compaq C RTL on OpenVMS Alpha Systems............................. 1-10 1-2 I/O Interface from C Programs............. 1-39 1-3 Mapping Standard I/O and UNIX I/O to RMS....................................... 1-41 5-1 Communications Links Between Parent and Child Processes........................... 5-3 6-1 An Example of the stdscr Window........... 6-8 6-2 Displaying Windows and Subwindows......... 6-10 6-3 Updating the Terminal Screen.............. 6-11 6-4 An Example of the getch Macro............. 6-20 REF-1 Reading and Writing to a Pipe.............REF-445 Tables 1-1 Linking Conflicts......................... 1-16 1-2 UNIX and OpenVMS File Specification Delimiters................................ 1-26 1-3 Valid and Invalid UNIX and OpenVMS File Specifications............................ 1-26 1-4 Feature Test Macros - Standards........... 1-30 1-5 Functions with Dual Implementations....... 1-66 1-6 Functions restricted to 32-bit pointers... 1-67 xxix 1-7 Callbacks that Pass Only 32-Bit Pointers.................................. 1-68 2-1 I/O Functions and Macros.................. 2-1 2-2 Optional Characters Between % (or %n$) and the Input Conversion Specifier............ 2-12 2-3 Conversion Specifiers for Formatted Input..................................... 2-14 2-4 Optional Characters Between % (or %n$) and the Output Conversion Specifier........... 2-25 2-5 Conversion Specifiers for Formatted Output.................................... 2-31 3-1 Character, String, and Argument-List Functions ................................ 3-1 3-2 Character-Classification Functions........ 3-8 3-3 ASCII Characters and the Character-Classification Functions........ 3-8 4-1 Error- and Signal-Handling Functions...... 4-1 4-2 The Error Code Symbolic Values............ 4-4 4-3 Compaq C RTL Signals...................... 4-9 4-4 Compaq C RTL Signals and Corresponding OpenVMS VAX Exceptions (VAX only)......... 4-15 4-5 Compaq C RTL Signals and Corresponding OpenVMS Alpha Exceptions (Alpha only)..... 4-17 5-1 Subprocess Functions...................... 5-2 6-1 Curses Functions and Macros............... 6-3 6-2 Curses Predefined Variables and #define Constants................................. 6-15 7-1 Math Functions............................ 7-1 8-1 Memory Allocation Functions............... 8-1 9-1 System Functions.......................... 9-1 10-1 Locale Categories......................... 10-5 11-1 Date/Time Functions....................... 11-1 11-2 Time-zone Filename Acronyms............... 11-7 REF-1 Interpretation of the mode Argument....... REF-5 REF-2 File Protection Values and Their Meanings.................................. REF-51 REF-3 RMS Valid Keywords and Values............. REF-74 REF-4 tm Structure..............................REF-343 xxx REF-5 Optional Characters in strfmon Conversion Specifications............................REF-585 REF-6 strfmon Conversion Specifiers.............REF-587 REF-7 Optional Elements of strftime Conversion Specifications............................REF-591 REF-8 strftime Conversion Specifiers............REF-592 REF-9 strptime Conversion Specifications........REF-610 REF-10 SYSCONF Argument and Return Values........REF-648 REF-11 Time-Zone Initialization Rules............REF-682 REF-12 The vfork and fork Functions..............REF-716 REF-13 Optional Elements of wcsftime Conversion Specifications............................REF-762 REF-14 wcsftime Conversion Specifiers............REF-764 A-1 Structures Used by Socket Routines........ A-3 A-2 errno Values.............................. A-6 A-3 4.4BSD Entry Points....................... A-13 A-4 Basic Communication Routines.............. A-14 A-5 Auxiliary Communication Routines.......... A-15 A-6 Supported h_errno Routines................ A-16 A-7 Supported Communication Routines.......... A-16 B-1 Functions Available on All OpenVMS Systems................................... B-1 B-2 Functions Added in OpenVMS Version 6.2.... B-4 B-3 Functions Added in OpenVMS Version 7.0.... B-5 B-4 Functions Added in OpenVMS Alpha Version 7.0....................................... B-7 B-5 Functions Added in OpenVMS Version 7.2.... B-9 B-6 Functions Added in OpenVMS Version 7.3.... B-9 C-1 Duplicated Prototypes..................... C-1 xxxi _________________________________________________________________ Preface This manual describes the Compaq C Run-Time Library (RTL). It provides reference information about the RTL functions and macros that perform input/output (I/O) operations, character and string manipulation, mathematical operations, error detection, subprocess creation, system access, and screen management. It also notes portability concerns between operating systems, where applicable, and describes the Compaq C for OpenVMS socket routines used for writing Internet application programs for the TCP/IP Services for OpenVMS (formerly the VMS/ULTRIX Connection) product, or other implementations of the TCP/IP protocol. The Compaq C RTL contains XPG4-compliant internationalization support, providing functions to help you develop software that can run in different languages and cultures. You can send comments or suggestions regarding this manual or any Compaq C document by sending electronic mail to the following Internet address: c_docs@compaq.com Intended Audience This manual is intended for experienced and novice programmers who need reference information on the functions and macros found in the Compaq C RTL. xxiii Document Structure This manual has the following chapters, reference section, and appendixes: o Chapter 1 provides an overview of the Compaq C RTL. o Chapter 2 discusses the Standard I/O, Terminal I/O, and UNIX I/O functions. o Chapter 3 describes the character, string, and argument- list functions. o Chapter 4 describes the error-handling and signal- handling functions. o Chapter 5 explains the functions used to create subprocesses. o Chapter 6 describes the Curses Screen Management functions. o Chapter 7 discusses the math functions. o Chapter 8 explains the memory allocation functions. o Chapter 9 describes the functions used to interact with the operating system. o Chapter 10 gives an introduction to the facilities provided in the Compaq C environment on OpenVMS systems for developing international software. o Chapter 11 describes the date/time functions. o The Reference Section describes all the functions in the Compaq C RTL. o Appendix A describes the Compaq C for OpenVMS socket routines used for writing Internet application programs for the TCP/IP Services for OpenVMS (formerly the VMS /ULTRIX Connection) product. o Appendix B contains version-dependency tables that list the Compaq C RTL functions supported on different OpenVMS versions. o Appendix C lists the function prototypes that are duplicated in more than one header file. xxiv Associated Documents The following documents may be useful when programming in Compaq C for OpenVMS Systems: o Compaq C User's Guide for OpenVMS Systems-For C programmers who need information on using Compaq C for OpenVMS Systems. o Compaq C Language Reference Manual-Provides language reference information for Compaq C on Compaq systems. o VAX C to Compaq C Migration Guide-To help OpenVMS VAX application programmers migrate from VAX C to Compaq C. o Compaq C Installation Guide for OpenVMS VAX Systems- For OpenVMS system programmers who install the Compaq C software on VAX systems. o Compaq C Installation Guide for OpenVMS Alpha Systems- For OpenVMS system programmers who install the Compaq C software on Alpha systems. o OpenVMS Master Index-For programmers who need to work with the VAX and Alpha machine architectures or the OpenVMS system services. This index lists manuals that cover the individual topics concerning access to the OpenVMS operating system. o X/Open Portability Guide, Issue 3-Documents what is commonly know as the XPG3 specification. o X/Open CAE Specification System Interfaces and Headers, Issue 4-Documents what is commonly know as the XPG4 specification. o X/Open CAE Specification, System Interfaces and Headers, Issue 4, Version 2-Documents what is commonly known as XPG4 V2. o Standard for Information Technology - Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API)-Amendment 2: Threads Extension [C Language]-Documents what is also known as POSIX 1003.1c-1995. o ISO/IEC 9945-2:1993 - Information Technology - Portable Operating System Interface (POSIX) - Part 2: Shell and Utilities-Documents what is also known as ISO POSIX-2. xxv o ISO/IEC 9945-1:1990 - Information Technology - Portable Operating System Interface (POSIX) - Part 1: System Application Programming Interface (API) (C Language)- Documents what is also known as ISO POSIX-1. o ISO/IEC 9899:1990-1994 - Programming Languages - C, Amendment 1: Integrity-Documents what is also known as ISO C, Amendment 1. o ISO/IEC 9899:1990 - Programming Languages - C-Documents what is also known as ISO C. The normative part is the same as X3.159-1989, American National Standard for Information Systems - Programming Language C, also known as ANSI C. Conventions_Used_in_this_Document________________________________ Convention__________Meaning________________________________ The symbol represents a single stroke of the Return key on a terminal. Ctrl/X The symbol Ctrl/X, where letter X represents a terminal control character, is generated by holding down the Ctrl key while pressing the key of the specified terminal character. switch statement Monospace type identifies language int data type keywords and the names of Compaq C fprintf function functions and header files. Monospace header type is also used when referring to file a specific variable name used in an example. arg1 Italic type indicates a placeholder, such as an argument or parameter name, and the introduction of new terms. $ RUN CPROG Interactive examples show user input in boldface type. xxvi ___________________________________________________________ Convention__________Meaning________________________________ float x; A vertical ellipsis indicates that not all of the text of a program or program . output is illustrated. Only relevant . material is shown in the example. . x = 5; option, . . . A horizontal ellipsis indicates that additional parameters, options, or values can be entered. A comma that precedes the ellipsis indicates that successive items must be separated by commas. [output- Square brackets, in function synopses source, . . . ] and a few other contexts, indicate that a syntactic element is optional. Square brackets are not optional, however, when used to delimit a directory name in an OpenVMS file specification or when used to delimit the dimensions of a multidimensional array in Compaq C source code. sc-specifier ::= In syntax definitions, items appearing auto on separate lines are mutually static exclusive alternatives. extern register [a|b] Brackets surrounding two or more items separated by a vertical bar (|) indicate a choice; you must choose one of the two syntactic elements. A delta symbol is used in some contexts to indicate a single ASCII space ____________________character._____________________________ Platform Labels A platform is a combination of operating system and hardware that provides a distinct environment. This manual contains information applicable to the OpenVMS operating system on both the VAX and Alpha architectures. xxvii The information in this manual applies to both of these platforms, except when specifically labeled, as follows: ___________________________________________________________ Label____________Explanation_______________________________ (Alpha only) Specific to an Alpha processor (Alpha architecture) running the OpenVMS operating system. (VAX only) Specific to a VAX processor running the _________________OpenVMS_operating_system._________________ New and Changed Features The following C RTL enhancements are included in Compaq C Version 6.4 and OpenVMS Version 7.3: o The strptime function was made XPG5-compliant (The strptime function was made XPG5-compliant). o The limitation of eight nested directory levels was lifted (Alpha only) (The limitation of eight nested directory levels was lifted (Alpha only)). o Improved Support for Extended File Specifications (Alpha only) (Improved Support for Extended File Specifications (Alpha only)). - Case preservation in file names is supported (Alpha only) (The Compaq C RTL supports case preservation in file names (Alpha only)). - Most C RTL functions now accept long OpenVMS-style file names as arguments (Alpha only) (Most C RTL functions now accept long OpenVMS-style file names as arguments (Alpha only)). o Support is added for exact-case argv arguments (Alpha only) (The Compaq C RTL supports exact-case argv arguments (Alpha only)). o Files can be implicitly opened for shared access (The Compaq C RTL can implicitly open files for shared access). o There is an alternative way of translating UNIX file specifications (Alternative way of translating UNIX file specs). xxviii o New C RTL functions are added (New Functions). o Support is added for a new signal, SIGWINCH (Chapter 4). o The socket routine socket_fd is changed to decc$socket_ fd (decc$socket_fd). This change is in the header file. Programs using this function need to be amended to call decc$socket_fd instead of socket_fd. Otherwise they will get implicit function declaration. The strptime function was made XPG5-compliant The strptime function has been modified to be compliant with X/Open CAE Specification System Interfaces and Headers Issue 5 (commonly known as XPG5). The change for XPG5 is in how the strptime function processes the "%y" directive for a two-digit year within the century if no century is specified. When a century is not otherwise specified, XPG5 requires that values for the "%y" directive in the range 69-99 refer to years in the twentieth century (1969 to 1999 inclusive), while values in the range 00-68 refer to years in the twenty-first century (2000 to 2068 inclusive). Essentially, for the "%y" directive, strptime became a "pivoting" function, with 69 being a pivoting year. Before this change, the strptime function interpreted a two-digit year with no century as a year within twentieth century. With OpenVMS Version 7.3, XPG5-compliant strptime becomes a default strptime function in the Compaq C RTL. However, the previous non-pivoting XPG4-compliant strptime function is retained for compatibility. The pivoting is controlled by the DECC$XPG4_STRPTIME logical name. To use the non-pivoting version of strptime, either: o Define DECC$XPG4_STRPTIME to any value before invoking the application. OR o Call the non-pivoting strptime directly as the function decc$strptime_xpg4. xxix The limitation of eight nested directory levels was lifted (Alpha only) The Compaq C RTL I/O subsystem was enhanced to remove the restriction of eight nested directory levels for an ODS-5 device. This affects Compaq C RTL functions such as access, mkdir, opendir, rmdir, and stat. Improved Support for Extended File Specifications (Alpha only) The following sections describe improved Compaq C RTL support for extended file specifications. The Compaq C RTL supports case preservation in file names (Alpha only) Programs linked against the Compaq C Run-time library DECC$SHR can now preserve the case of file names on ODS level 5 disks. This applies when creating or reporting file names. By default, this feature is disabled. To enable this feature enter the following command: $ DEFINE DECC$EFS_CASE_PRESERVE ENABLE If file names are all in upper case, use the following command to convert the names into lower case when reporting the name in UNIX style: $ DEFINE DECC$EFS_CASE_SPECIAL ENABLE If file names are not all in upper case, the preceding command preserves case. The commands to disable the preceding logical-name settings are: $ DEFINE DECC$EFS_CASE_PRESERVE DISABLE $ DEFINE DECC$EFS_CASE_SPECIAL DISABLE The setting for the DECC$EFS_CASE_SPECIAL logical name, if not set to DISABLE, supersedes any setting for the DECC$EFS_CASE_PRESERVE logical name. The DECC$EFS_CASE_PRESERVE and DECC$EFS_CASE_SPECIAL logicals are checked only once per image activation, not on a file-by-file basis. xxx Most C RTL functions now accept long OpenVMS-style file names as arguments (Alpha only) For OpenVMS Alpha Version 7.2, some basic Compaq C RTL I/O functions (creat, stat, and the functions from the open family of functions) were enhanced to accept long OpenVMS-style file names for an ODS-5 device. For OpenVMS Alpha Version 7.3, all other Compaq C RTL functions, except chdir and the functions from the exec family of functions, were also enhanced to accept long OpenVMS-style file names for an ODS-5 device. All C RTL functions that accept or report full file specifications will process file specifications up to 4095 bytes long, subject to the rules defined for the media format. For file specifications in OpenVMS format, there are no special restrictions. In situations where a full file specification cannot be reported because the buffer is too short, the function attempts to report the abbreviated name. UNIX file names have the following restrictions: o Names containing special characters, such as multiple periods, caret, or multinational characters, may be rejected. o A function call may report failure if the output buffer is not large enough to receive the full name. For OpenVMS style names, the reported name would contain a FID-abbreviated name. There is no representation of FID-abbreviated names defined for UNIX. The Compaq C RTL supports exact-case argv arguments (Alpha only) Nonquoted command-line arguments passed to C and C++ programs (argv arguments) can now optionally have their case preserved, rather than being lowercased as in previous versions. By default, this feature is disabled. To enable this case preservation feature, define the logical name DECC$ARGV_PARSE_STYLE to "ENABLE" and set the process-level DCL parse style flag to "EXTENDED" in the process running the program: xxxi $ DEFINE DECC$ARGV_PARSE_STYLE ENABLE $ SET PROCESS/PARSE_STYLE=EXTENDED Enabling this feature also ensures that the image name returned in argv[0] is also case-preserved. To disable this feature, use any one of the following commands: $ SET PROCESS/PARSE_STYLE=TRADITIONAL or $ DEFINE/SYSTEM DECC$ARGV_PARSE_STYLE DISABLE or $ DEASSIGN DECC$ARGV_PARSE_STYLE The value of the DECC$ARGV_PARSE_STYLE logical is case- insensitive. The Compaq C RTL can implicitly open files for shared access The Compaq C RTL was enhanced to open all files for shared access as if the "shr=del,get,put,upd" option was specified in the open* or creat call. To enable this feature, define the logical name DECC$FILE_ SHARING to "ENABLE". The value is case-insensitive. DECC$FILE_SHARING is checked only once per image activation, not on a file-by-file basis. Alternative way of translating UNIX file specs The Compaq C RTL was enhanced to allow interpreting the leading part of a UNIX-style file spec as either a subdirectory name or a device name. As with previous releases, the default translation of foo /bar (UNIX-style name) is FOO:BAR (OpenVMS-style device name). To request translation of foo/bar (UNIX-style name) to [.FOO]BAR (OpenVMS-style subdirectory name), define the logical name DECC$DISABLE_TO_VMS_LOGNAME_TRANSLATION to any value. DECC$DISABLE_TO_VMS_LOGNAME_TRANSLATION is checked only once per image activation, not on a file-by-file basis. xxxii New Functions The Compaq C RTL has added the following functions in OpenVMS Version 7.3: fchown link utime utimes writev xxxiii 1 _________________________________________________________________ Introduction The ISO/ANSI C standard defines a library of functions, as well as related types and macros, to be provided with any implementation of ANSI C. The Compaq C Language Reference Manual describes the ANSI-conformant library features common to all Compaq C platforms. The Compaq C Run-Time Library Reference Manual for OpenVMS Systems provides a more detailed description of these routines and their use in the OpenVMS environment. It also documents additional header files, functions, types, and macros that are available on the OpenVMS system. All library functions are declared in a header file. To make the contents of a header file available to your program, include the header file with an #include preprocessor directive. For example: #include Each header file contains function prototypes for a set of related functions, and defines any types and macros needed for their use. To list the header files on OpenVMS Alpha systems, use the following commands: $ LIBRARY/LIST ALPHA$LIBRARY:SYS$STARLET_C.TLB (Alpha only) $ LIBRARY/LIST ALPHA$LIBRARY:DECC$RTLDEF.TLB (Alpha only) $ DIR SYS$COMMON:[DECC$LIB.REFERENCE.DECC$RTLDEF]*.H; (Alpha only) $ DIR ALPHA$LIBRARY:*.H; (Alpha only) The first command lists the text module form of the header files for the OpenVMS system interfaces. The second lists the text module form of the header files for the Compaq C language interface. The third lists *.h header files for the Compaq C language interfaces. The fourth lists *.h header files for layered products and other applications. Introduction 1-1 ________________________ Note ________________________ The SYS$COMMON:[DECC$LIB.REFERENCE.DECC$RTLDEF] directory is only a reference area for your viewing. The compiler still looks in the *.TLB files for #include file searches. ______________________________________________________ To list the header files on OpenVMS VAX systems, use one of the following command: $ DIR 'F$TRNLMN("DECC$LIBRARY_INCLUDE")'*.H; (VAX only) $ DIR DECC$LIBRARY_INCLUDE:*.H; (VAX only) On OpenVMS VAX systems, the following command might also find additional or duplicate header files: $ DIR SYS$LIBRARY:*.H; (VAX only) However, duplicate files (such as ) found in SYS$LIBRARY probably support the VAX C Version 3.2 environment and should not be used with Compaq C. Function definitions themselves are not included in the header files, but are contained in the Compaq C Run-Time Library (RTL) shipped with the OpenVMS operating system. Before using the Compaq C RTL, you must be familiar with the following topics: o The linking process o The macro substitution process o The difference between function definitions and function calls o The format of valid file specifications o The OpenVMS-specific methods of input and output (I/O) o The Compaq C for OpenVMS extensions and nonstandard features A knowledge of all these topics is necessary to effectively use the Compaq C RTL. This chapter shows the connections between these topics and the Compaq C RTL. Read this chapter before any of the other chapters in this manual. 1-2 Introduction The primary purpose of the Compaq C RTL is to provide a means for C programs to perform I/O operations; the C language itself has no facilities for reading and writing information. In addition to I/O support, the Compaq C RTL also provides a means to perform many other tasks. Chapters 2 through 11 describe the various tasks supported by the Compaq C RTL. The Reference Section alphabetically lists and describes all the functions and macros available to perform these tasks. 1.1 Using the Compaq C Run-Time Library When working with the Compaq C RTL, you must be aware of some implementation specifics. First, if you plan to use Compaq C RTL functions in your C programs, make sure that a function named main or a function that uses the main_program option exists in your program. For more information, see the Compaq C Language Reference Manual or the Compaq C User's Guide for OpenVMS Systems. Second, the Compaq C RTL functions are executed at run time, but references to these functions are resolved at link time. When you link your program, the OpenVMS Linker resolves all references to Compaq C RTL functions by searching any shareable code libraries or object code libraries specified on the LINK command line. You can use the Compaq C RTL as a shareable image or you can use the Compaq C RTL object libraries. When you use the Compaq C RTL as a shareable image, the code for the RTL resides in an image file in SYS$SHARE and is shared by all Compaq C programs. After execution, control returns to your program. This process has a number of advantages: o You reduce the size of a program's executable image. o The program's image takes up less disk space. o The program swaps in and out of memory faster due to decreased size. Introduction 1-3 o With Compaq C and Compaq C++, you no longer need to define an options file when linking your program against the shareable image. Linking against the RTL shareable image is now much simpler than it was with VAX C. In fact, it is the default method of linking to the Compaq C RTL. When linking to the Compaq C RTL, you do not need to define any LNK$LIBRARY logicals. In fact, you should deassign LNK$LIBRARY because linking with the shareable image is more convenient than linking with the Compaq C RTL object libraries. See your OpenVMS, Compaq C, or Compaq C++ release notes for any supplemental information about linking with the Compaq C RTL. 1.2 RTL Linking Options on Alpha Systems (Alpha only) The following sections describe several ways of linking Compaq C and Compaq C++ programs with the Compaq C RTL on OpenVMS Alpha systems. 1.2.1 Linking with the Shareable Image Most linking needs should be satisfied by using the Compaq C RTL shareable image DECC$SHR.EXE in the ALPHA$LIBRARY directory. The shareable images VAXCRTL.EXE and VAXCRTLG.EXE do not exist on OpenVMS Alpha systems. The only C RTL shareable image is ALPHA$LIBRARY:DECC$SHR.EXE, which the linker automatically finds through IMAGELIB.OLB. The fact that VAXCRTL*.EXE does not exist on Alpha systems has the following ramifications: o You must change any existing VAX C link procedures to eliminate any references to the VAXCRTL*.EXE images. An explicit reference to DECC$SHR.EXE is unnecessary because IMAGELIB.OLB is searched automatically by the linker (see the OpenVMS Linker Utility Manual). o Because DECC$SHR.EXE exports only prefixed universal symbols (ones that begin with DECC$), to successfully link against it make sure you cause prefixing to occur for all Compaq C RTL entry points that you use. 1-4 Introduction If you use only the Compaq C RTL functions defined in the ANSI C Standard, all entry points will be prefixed. If you use Compaq C RTL functions not defined in the ANSI C Standard, you must compile in one of two ways to ensure prefixing: - Compile with the /PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES qualifier. - Compile with the /STANDARD=VAXC or /STANDARD=COMMON qualifier; you get /PREFIX_LIBRARY_ ENTRIES=ALL_ENTRIES as the default. To link against the shareable image, use the LINK command. For example: $ LINK PROG1 The linker automatically searches IMAGELIB.OLB to find DECC$SHR.EXE, and resolves all C RTL references. ________________________ Note ________________________ In OpenVMS Alpha Version 7.0, the Compaq C Run- Time Library functions whose names are of the form decc$fmath_2, are defined in STARLET, but are not universal symbols in the DECC$SHR image. When these functions are referenced by an application, linking the image results in inclusion of the DECC$SHR image from IMAGELIB and the specific C math modules from STARLET. If neither the DPML$SHR image or the CMA$TIS_ SHR image were already brought in during the IMAGELIB phase, the object form is included from STARLET because references to these symbols appear in the STARLET phase. In OpenVMS Version 7.0, this resulted in the undefined symbols: CMA$TIS_ERRNO_SET_VALUE CMA$TIS_VMS_ERRNO_SET_VALUE In OpenVMS Alpha Version 7.1, the decc$fmath_2 symbols have been added to the DECC$SHR image so that both the DPML$SHR and CMA$TIS_SHR references are now resolved using shareable images found in IMAGELIB. ______________________________________________________ Introduction 1-5 1.2.2 Linking with the Object Libraries The Compaq C RTL object libraries are used solely for linking programs compiled without /PREFIX=ALL. On OpenVMS Alpha systems, the Compaq C RTL provides the following object libraries in the ALPHA$LIBRARY directory: o VAXCCURSE.OLB o VAXCRTLD.OLB o VAXCRTLT.OLB o VAXCRTL.OLB o VAXCRTLX.OLB o VAXCRTLDX.OLB o VAXCRTLTX.OLB The object library VAXCCURSE.OLB, which provides access to the curses functions, contains unprefixed entry points that vector to the appropriate prefixed entry points. The object libraries VAXCRTL.OLB, VAXCRTLD.OLB, VAXCRTLT.OLB, VAXCRTLX.OLB, VAXCRTLDX.OLB, and VAXCRTLTX.OLB also contain unprefixed entry points that vector to the appropriate prefixed entry points, depending on the floating-point type specified by the object library used: o VAXCRTL.OLB contains all Compaq C RTL routine name entry points as well as VAX G-floating double-precision, floating-point entry points. o VAXCRTLD.OLB contains a limited support of VAX D- floating double-precision, floating-point entry points. o VAXCRTLT.OLB contains IEEE T-floating double-precision, floating-point entry points. o VAXCRTLX.OLB contains G_floating support and support for the /L_DOUBLE_SIZE=128 compiler qualifier. o VAXCRTLDX.OLB contains D_floating support and support for the /L_DOUBLE_SIZE=128 compiler qualifier. o VAXCRTLTX.OLB contains IEEE T_floating support and support for the /L_DOUBLE_SIZE=128 compiler qualifier. 1-6 Introduction /L_DOUBLE_SIZE=128 is the default. On the LINK command, specify only one of the VAXCRTL*.OLB libraries and, if needed, the VAXCCURSE.OLB library. In the default mode of the compiler (/STANDARD=RELAXED_ ANSI89) and also in strict ANSI C mode, all calls to ANSI C standard library routines are automatically prefixed with DECC$. With the /[NO]PREFIX_LIBRARY_ENTRIES qualifier, you can change this to prefix all Compaq C RTL names with DECC$, or to not prefix any Compaq C RTL names. Other options are also available for this qualifer. See the /[NO]PREFIX_LIBRARY_ENTRIES qualifier in this chapter for more information. When linking with /NOSYSSHR, if calls to the Compaq C RTL routines are prefixed with DECC$, then the modules in STARLET.OLB are the only ones you need to link against. Since STARLET.OLB is automatically searched by the linker (unless the link qualifier /NOSYSLIB is used), all prefixed RTL external names are automatically resolved. If any calls to the Compaq C RTL routines are not prefixed, then you need to explicitly link against VAXCRTL.OLB, VAXCRTLD.OLB, VAXCRTLT.OLB (or VAXCRTLX.OLB, VAXCRTLDX.OLB, or VAXCRTLDX.OLB), or VAXCCURSE.OLB, depending on which floating-point types you need, or if you want curses functions. If you are linking with /NOSYSSHR, prefixed Compaq C RTL entry points are resolved in STARLET.OLB. If you are linking with /SYSSHR (the default), prefixed Compaq C RTL entry points are resolved in DECC$SHR.EXE. 1.2.3 Examples The following examples show several different ways you might want to link with the Compaq C RTL. See Figure 1-1 for a graphical summary of these examples. 1. Most of the time, you just want to link against the shareable image: $ CC/PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES PROG1 $ LINK PROG1 The linker automatically searches IMAGELIB.OLB to find DECC$SHR.EXE. Introduction 1-7 2. If you want to use just object libraries (to write privileged code or for ease of distribution, for example), use the /NOSYSSHR qualifier of the LINK command: $ CC/PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES PROG1 $ LINK/NOSYSSHR PROG1 Prefixed RTL symbol references in the user program are resolved in the Compaq C RTL object library contained in STARLET.OLB. ________________________ Notes ________________________ o When linking Compaq C programs against the Compaq C RTL object libraries using the /NOSYSSHR qualifier, applications that previously linked without undefined globals may result in undefined globals for the CMA$TIS symbols. To resolve these undefined globals, add the following line to your link options file: SYS$LIBRARY:STARLET.OLB/LIBRARY/INCLUDE=CMA$TIS o If a program linked with the /NOSYSSHR qualifier makes a call to a routine that resides in a dynamically activated image, and the routine returns a value indicating an unsuccessful status, errno is set to ENOSYS, and vaxc$errno is set to C$_NOSYSSHR. The error message corresponding to C$_NOSYSSHR is "Linking /NOSYSSHR disables dynamic image activation." An example of this situation is a program linked with /NOSYSSHR that makes a call to a socket routine. ______________________________________________________ 3. When compiling with prefixing disabled, in order to use object libraries that provide alternate implementations of C RTL functions, you need to use the VAXC*.OLB object libraries. In this case, compile and link as follows: $ CC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ LINK PROG1, MYLIB/LIBRARY, ALPHA$LIBRARY:VAXCRTLX.OLB/LIBRARY 1-8 Introduction Unprefixed Compaq C RTL symbol references in the user program are resolved in MYLIB and in VAXCRTL.OLB. Prefixed Compaq C RTL symbol references in VAXCRTLX.OLB are resolved in DECC$SHR.EXE through IMAGELIB.OLB. In this same example, to get IEEE T-floating double- precision floating-point support, you might use the following compile and link commands: $ CC/NOPREFIX_LIBRARY_ENTRIES/FLOAT=IEEE_FLOAT PROG1 $ LINK PROG1, MYLIB/LIBRARY, ALPHA$LIBRARY:VAXCRTLTX.OLB/LIBRARY 4. Combining examples 2 and 3, you might want to use just the object libraries (for writing privileged code or for ease of distribution) and use an object library that provides C RTL functions. In this case, compile and link as follows: $ CC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ LINK/NOSYSSHR PROG1, MYLIB/LIBRARY, ALPHA$LIBRARY:VAXCRTLX.OLB/LIBRARY Prefixed Compaq C RTL symbol references in VAXCRTL.OLB are resolved in STARLET.OLB. Introduction 1-9 Figure 1-1 Linking with the Compaq C RTL on OpenVMS Alpha Systems 1.3 RTL Linking Options on VAX Systems (VAX only) Both the VAX C RTL and the Compaq C RTL can coexist on your OpenVMS VAX system. The VAX C RTL supports existing VAX C applications. The Compaq C RTL supports ANSI-compliant Compaq C and Compaq C++, as well as other components of the OpenVMS environment. The Compaq C RTL also provides a mechanism for thread safety and performance improvements. 1-10 Introduction Applications developed with VAX C will continue to use the VAX C RTL. However, you can relink VAX C applications to use the Compaq C RTL instead. This lets you take advantage of the new features of the Compaq C RTL and solve potential interoperability problems in complex applications that incorporate both the VAX C RTL and the Compaq C RTL. Existing applications that are relinked to use the Compaq C RTL should be carefully tested for possible problems resulting from the differences in behavior between the VAX C RTL and the Compaq C RTL. See the applicable Compaq C release notes and OpenVMS release notes for more information. The following sections describe several ways of linking Compaq C programs with the Compaq C RTL and VAX C RTL on OpenVMS VAX systems. 1.3.1 Linking with the Compaq C RTL The Compaq C RTL provides a new set of files with different names from the VAX C RTL files. If you want to link with the Compaq C RTL, you need to change your link procedures to use the new file names. The following sections describe linking with the Compaq C RTL files. 1.3.1.1 Linking with the Compaq C RTL Shareable Images Most linking needs should be satisfied by using the Compaq C RTL shareable image DECC$SHR.EXE in the SYS$LIBRARY directory. Use this linking method for programs that are written entirely in Compaq C or Compaq C++ code; that is, with no VAX C object modules. Because DECC$SHR.EXE exports only prefixed universal symbols (ones that begin with DECC$), to successfully link against it make sure you cause prefixing to occur for all Compaq C RTL entry points. If you use only the Compaq C RTL functions defined in the ANSI C Standard, all entry points will be prefixed. If you use Compaq C RTL functions not defined in the ANSI C Standard, you must compile in one of two ways to ensure prefixing: o Compile with the /PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES qualifier. Introduction 1-11 o Compile with the /STANDARD=VAXC or /STANDARD=COMMON qualifier; you get /PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES as the default. Then link against the shareable image using the LINK command. For example: $ LINK PROG1 If you are using the VAX C compiler and you want to link with DECC$SHR.EXE, you must link to one of the following files: VAXC2DECC.EXE VAXCG2DECC.EXE You link with them as follows: $ LINK PROG1,TT:/OPTIONS SYS$LIBRARY:VAXC2DECC/SHARE Use the G-floating version, VAXCG2DECC.EXE, if you compiled with the /G_FLOAT or /FLOAT=G_FLOAT qualifier. 1.3.1.2 Linking with or Providing Your Own Shareable Images Most linking needs for an application using a shareable image are handled by a straight forward link command, regardless of whether the shared image uses Compaq C, VAX C or some other programming language. For example, assume that SHARE1.EXE is a shareable image linked with VAXCRTL.EXE. Also assume that your program, PROG1, is compiled with Compaq C and, therefore, references prefixed names for C RTL functions. You can then use the following commands: $ LINK PROG1, SYS$INPUT:/OPTIONS MYDISK:[TEXT]SHARE1.EXE/SHARE If PROG1 does not use prefixed names, the link could result in link conflicts. If this occurs, see Section 1.3.2. 1-12 Introduction 1.3.1.3 Linking with the Compaq C RTL Object Libraries The Compaq C RTL object libraries are used primarily for linking with the /NOSYSSHR qualifier. On OpenVMS VAX systems, the Compaq C RTL provides the following object libraries in the SYS$LIBRARY directory: o DECCCURSE.OLB o DECCRTLG.OLB o DECCRTL.OLB As with VAX C, if you specify more than one object library on the LINK command, you must do so in the order listed. You use these object libraries in the same way that you would use the VAX C RTL object libraries VAXCRTL.OLB, VAXCRTLG.OLB, and VAXCCURSE.OLB. For example: $ ! Link a D-float program $ LINK PROG1, SYS$LIBRARY:DECCRTL.OLB/LIBRARY $ ! $ ! Link a G-float program $ LINK PROG2, SYS$LIBRARY:DECCRTLG.OLB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY $ ! $ ! Link a D-float, curses program $ LINK PROG1, SYS$LIBRARY:DECCCURSE.OLB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY ________________________ Note ________________________ When linking to the Compaq C RTL object libraries, you do not need to define any LNK$LIBRARY logicals. In fact, you must deassign LNK$LIBRARY when linking with the .OLB libraries; otherwise, you might see "multiply defined symbols" errors. In general, you should deassign LNK$LIBRARY because pointing this logical to the Compaq C RTL object libraries interferes with VAX C development. ______________________________________________________ Introduction 1-13 1.3.1.4 Linking with the Compaq C RTL Object Libraries /NOSYSSHR If you want to link your program with the Compaq C RTL object libraries using the /NOSYSSHR qualifier, you must specify /INCLUDE=CMA$TIS for the object library. For OpenVMS VAX Version 7.3 and higher, you must specify /INCLUDE=(CMA$TIS,CMA$TIS_VEC). Otherwise, several symbols will be undefined and the resulting image will not execute. In order to add this qualifier, you cannot use the LNK$LIBRARY logicals to link with the Compaq C RTL. You must use a linker options file or list the Compaq C RTL object library on the command line. For example: $ LINK/NOSYSSHR PROG1, SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCLUDE=CMA$TIS $ LINK/NOSYSSHR PROG1, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCLUDE=(CMA$TIS,CMA$TIS_VEC) (OpenVMS V7.3 and higher) ________________________ Notes ________________________ o When linking Compaq C programs against the Compaq C RTL object libraries using the /NOSYSSHR qualifier, applications that previously linked without undefined globals may result in undefined globals for the CMA$TIS symbols. To resolve these undefined globals, add the following line to your link options file: SYS$LIBRARY:STARLET.OLB/LIBRARY/INCLUDE=CMA$TIS SYS$LIBRARY:STARLET.OLB/LIBRARY/INCLUDE=(CMA$TIS,CMA$TIS_VEC) (OpenVMS V7.3 and higher) o If a program linked with the /NOSYSSHR qualifier makes a call to a routine that resides in a dynamically activated image, and the routine returns a value indicating an unsuccessful status, errno is set to ENOSYS, and vaxc$errno is set to C$_NOSYSSHR. The error message corresponding to C$_NOSYSSHR is "Linking /NOSYSSHR disables dynamic image activation." An example of this situation is a program linked with /NOSYSSHR that makes a call to a socket routine. 1-14 Introduction ______________________________________________________ 1.3.2 Resolving Link-Time Conflicts with Multiple C RTLs This section describes the use of interoperability tools to resolve link-time conflicts when using multiple C RTLs. When migrating to the Compaq C RTL, multiple C RTLs will likely be needed to link an application. One C RTL might be explicitly linked against. A second C RTL might not be explicitly linked against, but brought into the link by means of a shareable image. For example, when developing a Motif program using Compaq C, the application must be linked against the Compaq C RTL and against the Motif images. Motif currently brings the VAX C RTL into the link. Problems encountered when linking with multiple C RTLs are a result of the OpenVMS linker resolving symbol references in the image being linked by searching the transitive closure of shareable images and libraries. That is, when linking with a shareable image, the linker searches that shareable image and all shareable images referenced in that shareable image. So when linking with VAXCRTL.EXE and with an image linked with VAXCRTLG.EXE, the linker will find two instances of all the C RTL symbols (one in VAXCRTL and one in VAXCRTLG), and report a conflict. The object libraries do not conflict with routine names, but do conflict with the global symbols. Because VAX C implements global symbols as global overlaid psects, the linker attempts to connect all the instances of a C-generated psect with the same name. For example, a reference to stdin in the user program is connected with the psect of the same name in VAXCRTL.OLB. However, a shareable image that was linked with VAXCRTL.OLB also has a psect of the same name; this results in an error because the linker cannot connect those two definitions of the psect stdin. Three interoperability tools are provided with the Compaq C compiler and in a separate Compaq C/C++ RTL Run-Time Components kit to resolve link-time conflicts: o VAXC$LCL.OPT o VAXC$EMPTY.EXE Introduction 1-15 o DECC$EMPTY.EXE These tools work by hiding the conflicting symbols from one of the C RTLs being linked. Which tool is required depends on what C RTLs are used by the main application and the shareable image. Table 1-1 shows typical C RTL conflicts and the interoperability tool required to resolve it. In the table, VAXCRTL.EXE refers to either VAXCRTL.EXE or VAXCRTLG.EXE. Table_1-1_Linking_Conflicts________________________________ Linker_Message_____Type_of_Conflict_________Tool_Needed____ LINK-E-MULSHRPSC VAXCRTL.OLB/VAXCRTL.EXE VAXC$LCL.OPT LINK-E-SHRPSCLNG VAXCRTL.OLB/DECCRTL.OLB VAXC$LCL.OPT LINK-E-MULSHRPSC, DECCRTL.OLB/VAXCRTL.EXE VAXC$LCL.OPT LINK-E-SHRPSCLNG None. DECCRTL.OLB DECC$EMPTY /DECC$SHR.EXE LINK-W-MULDEF VAXCRTL.EXE VAXC$EMPTY /VAXCRTLG.EXE LINK-W-MULDEF VAXC2DECC.EXE VAXC$EMPTY ___________________/VAXCRTL.EXE____________________________ 1.3.2.1 Using VAXC$LCL.OPT VAXC$LCL.OPT is required when building any shareable image linked with the VAX C RTL object library or Compaq C RTL object library. If the shareable image is built without using VAXC$LCL.OPT, the C RTL global symbols are visible in the shareable image and cause linker conflicts when users of the image link against it. For example: %LINK-E-MULSHRPSC, psect C$$TRNS_VALUES defined in shareable image IMAGE1.EXE; is multiply defined in shareable image SYS$LIBRARY:VAXCRTL.EXE;1 -LINK-E-NOIMGFIL, image file not created 1-16 Introduction In this example, the shareable image IMAGE1 uses VAXCRTL.OLB, and the image being linked uses VAXCRTL.EXE. For a successful link, relink the shareable image using VAXC$LCL.OPT: $ LINK/SHARE IMAGE1.OBJ, IMAGE1.OPT/OPTIONS, SYS$LIBRARY:VAXCRTL/LIBRARY, - _$ SYS$LIBRARY:VAXC$LCL.OPT/OPTIONS The following message also indicates a conflict involving the VAX C RTL object library: %LINK-E-SHRPSCLNG, Psect STDIN has length of 8 in module C$EXTERNDATA file SYS$LIBRARY:DECCRTL.OLB;2 which exceeds length of 4 in shareable image IMAGE1.EXE; -LINK-E-NOIMGFIL, image file not created In this example, the shareable image IMAGE1 uses VAXCRTL.OLB, and the image being linked uses DECCRTL.OLB. For a successful link, relink the shareable image using VAXC$LCL.OPT. If the shareable image cannot be relinked (as in the case of a third-party shareable image), then the interoperability tool can be applied to the main image. If the main image is being linked against DECCRTL.OLB, then apply VAXC$LCL.OPT to the link of the main image. If the main image is being linked against VAXCRTL.EXE, the only solution is to get the shareable image fixed, because applying any of the interoperability tools to the link of the main image will result in an unsuccessful link. 1.3.2.2 Using VAXC$EMPTY.EXE Use VAXC$EMPTY.EXE to link a main application with both VAXC2DECC.EXE (or VAXCG2DECC.EXE) and a shareable image linked with VAXCRTL.EXE (or VAXCRTLG.EXE). Using VAXC$EMPTY.EXE hides all the global symbols in the VAXCRTL*.EXE shareable image to prevent conflicts with VAXC2DECC.EXE or VAXCG2DECC.EXE. Also use VAXC$EMPTY.EXE to link an application with both VAXCRTL.EXE and a shareable image linked with VAXCRTLG.EXE (or vice versa). Introduction 1-17 When there is a conflict between C RTL shareable images, the linker produces large numbers of messages similar to the following: %LINK-W-MULDEF, symbol ACOS multiply defined in module VAXCRTL file SYS$COMMON:[SYSLIB]VAXCRTL.EXE;18 In this example, the shareable image is linked with VAXCRTL.EXE, and the main program is linked with VAXC2DECC.EXE. The solution is to define the VAXCRTL logical to point to VAXC$EMPTY.EXE before linking the main program: $ DEFINE/USER VAXCRTL SYS$LIBRARY:VAXC$EMPTY.EXE $ LINK/EXEC=MAIN_IMAGE MAIN_PROG,OBJ1,OBJ2,...,SYS$INPUT:/OPTIONS IMAGE1/SHARE VAXCRTL/SHARE Note the following about this solution: o Your linker options file cannot reference SYS$LIBRARY:VAXCRTL; it must reference only VAXCRTL. o Do not link explicitly against VAXC$EMPTY.EXE, or your application will neither link nor run correctly. o Do not leave the VAXCRTL pointing to VAXC$EMPTY.EXE, or your application will not run correctly. o The DEFINE/USER command is used to ensure that the logical definition is removed after execution of the LINK command. Make sure that no commands intervene between the DEFINE/USER command and the LINK command. Follow the same process when linking against VAXCRTLG.EXE by defining the VAXCRTLG logical to point to VAXC$EMPTY.EXE. 1.3.2.3 Using DECC$EMPTY.EXE The DECC$EMPTY.EXE interoperability tool allows a program to use the Compaq C object library even when the program links with a shareable image that was linked with DECC$SHR.EXE. 1-18 Introduction If DECC$EMPTY.EXE is not used during the link, all Compaq C RTL references from the main program will be resolved in DECC$SHR.EXE, not in the object library. There is no linker message that indicates this fact. For example, if IMAGE1 is linked against DECC$SHR, and the following link is performed, then the main image will not contain any Compaq C RTL object modules. All C RTL references from the main progam are resolved in DECC$SHR: $ LINK/EXEC=MAIN_IMAGE MAIN_PROG,OBJ1,...,SYS$INPUT:/OPTIONS IMAGE1/SHARE SYS$LIBRARY:DECCRTL/LIBRARY By defining the DECC$SHR logical to point to DECC$EMPTY.EXE immediately before the link, all references to C RTL symbols from the main program are resolved in the Compaq C RTL object library. For example: $ DEFINE/USER DECC$SHR SYS$LIBRARY:DECC$EMPTY.EXE $ LINK/EXEC=MAIN_IMAGE MAIN_PROG,OBJ1,...,SYS$INPUT:/OPTIONS IMAGE1/SHARE SYS$LIBRARY:DECCRTL/LIBRARY Note the following about this solution: o Do not link explicitly against DECC$EMPTY.EXE, or your application will neither link correctly nor run correctly. o Do not leave the DECC$SHR logical pointing to DECC$EMPTY.EXE, or your application will not run correctly. o The DEFINE/USER command is used to ensure that the logical definition is removed after execution of the LINK command. Make sure that no commands intervene between the DEFINE/USER command and the LINK command. Introduction 1-19 1.3.3 Linking Examples for Compaq C or Compaq C++ Code Only The following examples show the different ways you might want to link Compaq C only or Compaq C++ only programs with the Compaq C RTL on OpenVMS VAX systems: 1. Most of the time, you just want to link against the shareable image: $ CC/DECC/PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES PROG1 $ LINK PROG1 The linker automatically searches IMAGELIB.OLB to find DECC$SHR.EXE. 2. If you want to use just object libraries (to write privileged code or for ease of distribution, for example), use the /NOSYSSHR qualifier of the LINK command: $ CC/DECC/PREFIX_LIBRARY_ENTRIES=ALL_ENTRIES PROG1 $ LINK/NOSYSSHR PROG1, SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCL=CMA$TIS $ LINK/NOSYSSHR PROG1, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCL=(CMA$TIS,CMA$TIS_VEC) (OpenVMS V7.3 and higher) Prefixed Compaq C RTL symbol references in the user program are resolved in STARLET.OLB. 3. When compiling with prefixing disabled, in order to use object libraries that provide alternate implementations of C RTL functions, you need to use the DECC*.OLB object libraries. In this case, compile and link as follows: $ CC/DECC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ LINK PROG1, MYLIB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY Unprefixed Compaq C RTL symbol references in the user program are resolved in MYLIB and DECCRTL.OLB. The unprefixed names refrence prefixed names resolved in DECC$SHR.EXE. You can link with any valid combination of DECCRTL.OLB, DECCRTLG.OLB, and DECCCURSE.OLB. In this same example, to get G-floating double-precision, floating-point support, you might use the following compile and LINK commands: 1-20 Introduction $ CC/DECC/NOPREFIX_LIBRARY_ENTRIES/FLOAT=G_FLOAT PROG1 $ LINK PROG1, MYLIB/LIBRARY, SYS$LIBRARY:DECCRTLG.OLB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY 4. Combining examples 2 and 3, you might want to use just the object libraries (for writing privileged code or for ease of distribution) and use an object library that provides C RTL functions. In this case, compile and link as follows: $ CC/DECC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ LINK/NOSYSSHR PROG1, MYLIB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY 1.3.4 Linking Examples for VAX C and Compaq C Code Combined You might have programs that combine VAX C and Compaq C (or Compaq C++) code. The following examples show different ways to link such programs with the Compaq C RTL on OpenVMS VAX systems. These examples correspond to the examples in Section 1.3.3. 1. To link against the shareable image, specify the VAXC2DECC.EXE shareable image: $ CC/DECC PROG1 $ CC/VAXC PROG2 $ LINK PROG1, PROG2, TT:/OPTIONS SYS$LIBRARY:VAXC2DECC.EXE/SHARE Prefixed C RTL calls from PROG1 are resolved in DECC$SHR. Unprefixed C RTL calls from PROG2 are resolved in VAXC2DECC.EXE, which transfers them to DECC$SHR. 2. If you want to use just object libraries (to write privileged code or for ease of distribution, for example), use the /NOSYSSHR qualifier of the LINK command: $ CC/DECC PROG1 $ CC/VAXC PROG2 $ LINK/NOSYSSHR PROG1, PROG2, SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCL=CMA$TIS All C RTL calls from both PROG1 and PROG2 are resolved in DECCRTL.OLB. Introduction 1-21 3. When compiling with prefixing disabled, in order to use object libraries that provide alternate implementations of C RTL functions, you need to use the DECC*.OLB object libraries. In this case, compile and link as follows: $ CC/DECC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ CC/VAXC PROG2 $ LINK PROG1, PROG2, MYLIB/LIBRARY, - _$SYS$LIBRARY:DECCRTL.OLB/LIBRARY/INCL=CMA$TIS Unprefixed Compaq C RTL symbol references in the user program are resolved in MYLIB and DECCRTL.OLB. 4. Combining examples 2 and 3, you might want to use just the object libraries (for writing privileged code or for ease of distribution) and use an object library that provides C RTL functions. In this case, compile and link as follows: $ CC/DECC/NOPREFIX_LIBRARY_ENTRIES PROG1 $ CC/VAXC PROG2 $ LINK/NOSYSSHR PROG1, PROG2, MYLIB/LIBRARY, - _$ SYS$LIBRARY:DECCRTL.OLB/LIBRARY /INCL=CMA$TIS 1.3.5 Linking with the VAX C RTL /NOSYSSHR This section applies to programs running on OpenVMS VAX Version 6.0 or higher. For programs that currently link with the VAX C RTL object libraries using the /NOSYSSHR qualifier, you must specify /INCLUDE=CMA$TIS for the object library. Otherwise, several symbols will be undefined and the resulting image will not execute. In order to add this qualifier, you cannot use the LNK$LIBRARY logicals to link with the VAX C RTL object libraries. You must use a linker options file or list the VAX C RTL object libraries on the command line. For example: $ LINK/NOSYSSHR PROG1, SYS$LIBRARY:VAXCRTL.OLB/LIBRARY/INCLUDE=CMA$TIS 1-22 Introduction 1.4 Compaq C RTL Function Prototypes and Syntax After learning how to link object modules and include header files, you must learn how to reference Compaq C functions in your program. The remaining chapters in this manual provide detailed descriptions of the Compaq C RTL functions. 1.4.1 Function Prototypes In all chapters, the syntax describing each function follows the standard convention for defining a function. This syntax is called a function prototype (or just prototype). The prototype is a compact representation of the order of a function's arguments (if any), the types of the arguments, and the type of the value returned by a function. The use of prototypes is recommended. If the return value of the function cannot be easily represented by a C data-type keyword, look for a description of the return values in the explanatory text. The prototype descriptions provide insight into the functionality of the function. These descriptions may not describe how to call the function in your source code. For example, consider the prototype for the feof function: #include int feof(FILE *file_ptr); This syntax shows the following information: o The feof prototype resides in the header file. To use feof, you must include this header file. (Declaring Compaq C RTL functions yourself is not recommended.) o The feof function returns a value of data type int. This prototype indicates the arguments and the return value of feof. o There is one argument, file_ptr, that is of type "pointer to FILE". FILE is defined in the header file. Introduction 1-23 To use feof in a program, include anywhere before the function call to feof, as in the following example: #include /* Include Standard I/O */ main() { FILE *infile; /* Define a file pointer */ . . . /* Call the function feof */ while ( ! feof(infile) ) /* Until EOF reached */ { /* Perform file operations */ . . . } } 1.4.2 Syntax Conventions for Function Prototypes Since some library functions take a varying number of parameters, syntax descriptions for function prototypes adhere to the following conventions: o Ellipses ( . . . ) are used to indicate a varying number of parameters. o In cases where the type of a parameter may vary, its type is not shown in the syntax. Consider the printf syntax description: #include int printf(const char *format_specification, . . . ); The syntax description for printf shows that you can specify one or more optional parameters. The remaining information about printf parameters is in the description of the function. 1-24 Introduction 1.4.3 UNIX Style File Specifications The Compaq C RTL functions and macros often manipulate files. One of the major portability problems is the different file specifications used on various systems. Since many C applications are ported to and from UNIX systems, it is convenient for all compilers to be able to read and understand UNIX system file specifications. The following file specification conversion functions are included in the Compaq C RTL to assist in porting C programs from UNIX systems to OpenVMS systems: - decc$match_wild - decc$translate_vms - decc$fix_time - decc$to_vms - decc$from_vms ________________________ Note ________________________ These DECC$ routine names replace the SHELL$ routine names previously available with the VAX C RTL. ______________________________________________________ The advantage of including these file specification conversion functions in the Compaq C RTL is that you do not have to rewrite C programs containing UNIX system file specifications. Compaq C can translate most valid UNIX system file specifications to OpenVMS file specifications. ________________________ Note ________________________ The Compaq C RTL cannot translate UNIX file specifications with more than one period character (.). If the UNIX file specification contains a period, all slash characters (/) must precede that period. ______________________________________________________ Introduction 1-25 Please note the differences between the UNIX system and OpenVMS file specifications, as well as the method used by the RTL to access files. For example, the RTL accepts a valid OpenVMS specification and most valid UNIX file specifications, but the RTL cannot accept a combination of both. Table 1-2 shows the differences between UNIX system and OpenVMS system file specification delimiters. Table_1-2_UNIX_and_OpenVMS_File_Specification_Delimiters___ OpenVMS Description______System______UNIX_System___________________ Node delimiter :: !/ Device : / delimiter Directory path [ ] / delimiter Subdirectory [ . ] / delimiter File extension . . delimiter File version ; Not applicable delimiter__________________________________________________ For example, Table 1-3 shows the formats of two valid specifications and one invalid specification. Table 1-3 Valid and Invalid UNIX and OpenVMS File __________Specifications___________________________________ System____File_Specification__________Valid/Invalid________ OpenVMS BEATLE::DBA0:[MCCARTNEY]SONGValid UNIX beatle!/usr1/mccartney Valid /songs.lis (continued on next page) 1-26 Introduction Table 1-3 (Cont.) Valid and Invalid UNIX and OpenVMS File __________________Specifications___________________________ System____File_Specification__________Valid/Invalid________ - BEATLE::DBA0:[MCCARTNEY.C] Invalid __________/songs.lis_______________________________________ When Compaq C translates file specifications, it looks for both OpenVMS and UNIX system file specifications. Consequently, there may be differences between how Compaq C translates UNIX system file specifications and how UNIX systems translate the same UNIX file specification. For example, if the two methods of file specification are combined, as in Table 1-3, Compaq C RTL can interpret [MCCARTNEY.C]/songs.lis as either [MCCARTNEY]songs.lis or [C]songs.lis. Therefore, when Compaq C encounters a mixed file specification, an error occurs. UNIX systems use the same delimiter for the device name, the directory names, and the file name. Due to the ambiguity of UNIX file specifications, Compaq C may not translate a valid UNIX system file specification according to your expectations. For instance, the OpenVMS system equivalent of /bin/today can be either [BIN]TODAY or [BIN.TODAY]. Compaq C can make the correct interpretation only from the files present. If a file specification conforms to UNIX system file name syntax for a single file or directory, it is converted to the equivalent OpenVMS file name if one of the following conditions is true: o If the specification corresponds to an existing OpenVMS directory, it is converted to that directory name. For example, /dev/dir/sub is converted to DEV:[DIR.SUB] if DEV:[DIR.SUB] exists. o If the specification corresponds to an existing OpenVMS file name, it is converted to that file name. For example, /dev/dir/file is converted to DEV:[DIR]FILE if DEV:[DIR]FILE exists. Introduction 1-27 o If the specification corresponds to a nonexistent OpenVMS file name, but the given device and directory exist, it is converted to a file name. For example, /dev/dir/file is converted to DEV:[DIR]FILE if DEV:[DIR] exists. ________________________ Note ________________________ Beginning with OpenVMS Version 7.3, you can instruct the Compaq C RTL to interpret the leading part of a UNIX-style file spec as either a subdirectory name or a device name. As with previous releases, the default translation of foo/bar (UNIX-style name) is FOO:BAR (OpenVMS-style device name). To request translation of foo/bar (UNIX-style name) to [.FOO]BAR (OpenVMS-style subdirectory name), define the logical name DECC$DISABLE_TO_VMS_LOGNAME_ TRANSLATION to any value. DECC$DISABLE_TO_VMS_LOGNAME_ TRANSLATION is checked only once per image activation, not on a file-by-file basis. Defining this logical affects not only the decc$to_vms function, but all Compaq C RTL functions that accept both UNIX-style and OpenVMS-style file names as an argument. ______________________________________________________ In the UNIX system environment, you reference files with a numeric file descriptor. Some file descriptors reference Standard I/O devices; some descriptors reference actual files. If the file descriptor belongs to an unopened file, the Compaq C RTL opens the file. Compaq C equates file descriptors with the following OpenVMS logical names: ___________________________________________________________ File OpenVMS Descriptor_____Logical________Meaning______________________ 0 SYS$INPUT Standard input 1 SYS$OUTPUT Standard output 2______________SYS$ERROR______Standard_error_______________ 1-28 Introduction 1.5 Feature-Test Macros for Header-File Control Feature-test macros provide a means for writing portable programs. They ensure that the Compaq C RTL symbolic names used by a program do not clash with the symbolic names supplied by the implementation. The Compaq C Run-time Library header files are coded to support the use of a number of feature-test macros. When an application defines a feature-test macro, the Compaq C RTL header files supply the symbols and prototypes defined by that feature-test macro and nothing else. If a program does not define such a macro, the Compaq C RTL header files define symbols without restriction. The feature-test macros supported by the Compaq C Run-time Library fall into three broad categories for controlling the visibility of symbols in header files according to the following: o Standards o Multiple-version support o Compatibility 1.5.1 Standards Macros The Compaq C Run-time Library implements parts of the following standards: o X/Open CAE Specification, System Interfaces and Headers, Issue 4, Version 2, also known as XPG4 V2. o X/Open CAE Specification, System Interfaces and Headers, Issue 4, also known as XPG4. o Standard for Information Technology - Portable Operating System Interface (POSIX) - Part 1: System Application Program Interface (API)-Amendment 2: Threads Extension [C Language], also known as POSIX 1003.1c-1995 or IEEE 1003.1c-1995. o ISO/IEC 9945-2:1993 - Information Technology - Portable Operating System Interface (POSIX) - Part 2: Shell and Utilities, also known as ISO POSIX-2. Introduction 1-29 o ISO/IEC 9945-1:1990 - Information Technology - Portable Operating System Interface (POSIX) - Part 1: System Application Programming Interface (API) (C Language), also known as ISO POSIX-1. o ISO/IEC 9899:1990-1994 - Programming Languages - C, Amendment 1: Integrity, also known as ISO C, Amendment 1. o ISO/IEC 9899:1990 - Programming Languages - C, also known as ISO C. The normative part is the same as X3.159-1989, American National Standard for Information Systems - Programming Language C, also known as ANSI C. 1.5.2 Selecting a Standard You can define a feature-test macro to select each standard. You can do this either with a #define preprocessor directive in your C source before the inclusion of any header file, or with the /DEFINE qualifier on the CC command line. Table 1-4 lists and describes the Compaq C RTL feature-test macros that control standards support. macro) Table_1-4_Feature_Test_Macros_-_Standards________________________ Other Standard Standards Macro_Name___________Selected__Implied____Description____________ _XOPEN_SOURCE_ XPG4 V2 XPG4, Makes visible XPG4- EXTENDED ISO POSIX-2extended features, ISO POSIX-1including traditional ANSI C UNIX-based interfaces not previously adopted by X/Open. (continued on next page) 1-30 Introduction Table_1-4_(Cont.)_Feature_Test_Macros_-_Standards________________ Other Standard Standards Macro_Name___________Selected__Implied____Description____________ _XOPEN_SOURCE XPG4 ISO POSIX-2Makes visible XPG4 ISO POSIX-1standard symbols and ANSI C causes _POSIX_C_SOURCE to be set to 2 if it is not already defined with a value greater than 2.[1], [2] _POSIX_C_ IEEE ISO POSIX-2Header files defined SOURCE==199506 1003.1c-19ISO POSIX-1by ANSI C make visible ANSI C those symbols required by IEEE 1003.1c-1995. _POSIX_C_SOURCE == ISO ISO POSIX-1Header files defined 2 POSIX-2 ANSI C by ANSI C make visible those symbols required by ISO POSIX-2 plus those required by ISO POSIX-1. _POSIX_C_SOURCE == ISO ANSI C Header files defined 1 POSIX-1 by ANSI C make visible those symbols required by ISO POSIX-1. __STDC_VERSION__==199ISO C ANSI C Makes ISO C amendment 1 amdt 1 symbols visible. _ANSI_C_SOURCE ANSI C - Makes ANSI C standard symbols visible. [1]Where_the_ISO_C_Amendment_1_includes_symbols_not_specified____ by XPG4, defining __STDC_VERSION__ == 199409 and _XOPEN_SOURCE (or _XOPEN_SOURCE_EXTENDED) selects both ISO C and XPG4 APIs. Conflicts that arise when compiling with both XPG4 and ISO C Amendment 1 resolve in favor of ISO C Amendment 1. [2]Where XPG4 extends the ISO C Amendment 1, defining _XOPEN_ SOURCE or _XOPEN_SOURCE_EXTENDED selects ISO C APIs as well as the XPG4 extensions available in the header file. This mode of compilation makes XPG4 extensions visible. _________________________________________________________________ Introduction 1-31 Features not defined by one of the previously named standards are considered Compaq C extensions and are selected by not defining any standards-related, feature- test macros. If you do not explicitly define feature test macros to control header file definitions, you implicitly include all defined symbols as well as Compaq C extensions. 1.5.3 Interactions with the /STANDARD Qualifier The /STANDARD qualifier selects the dialect of the C language supported. With the exception of /STANDARD=ANSI89 and /STANDARD=ISOC94, the selection of C dialect and the selection of Compaq C RTL APIs to use are independent choices. All other values for /STANDARD cause the entire set of APIs to be available, including extensions. Specifying /STANDARD=ANSI89 restricts the default API set to the ANSI C set. In this case, to select a broader set of APIs, you must also specify the appropriate feature- test macro. To select the ANSI C dialect and all APIs, including extensions, undefine __HIDE_FORBIDDEN_NAMES before including any header file. Compiling with /STANDARD=ISOC94 sets __STDC_VERSION__ to 199409. Conflicts that arise when compiling with both XPG4 and ISO C Amendment 1 resolve in favor of ISO C Amendment 1. XPG4 extensions to ISO C Amendment 1 are selected by defining _XOPEN_SOURCE. The following examples help clarify these rules: o The fdopen function is an ISO POSIX-1 extension to . Therefore, defines fdopen only if one or more of the following is true: - The program including it is not compiled in strict ANSI C mode (/STANDARD=ANSI89). - _POSIX_C_SOURCE is defined as 1 or greater. - _XOPEN_SOURCE is defined. - _XOPEN_SOURCE_EXTENDED is defined. 1-32 Introduction o The popen function is an ISO POSIX-2 extension to . Therefore, defines popen only if one or more of the following is true: - The program including it is not compiled in strict ANSI C mode (/STANDARD=ANSI89). - _POSIX_C_SOURCE is defined as 2 or greater. - _XOPEN_SOURCE is defined. - _XOPEN_SOURCE_EXTENDED is defined. o The getw function is an X/Open extension to . Therefore, defines getw only if one or more of the following is true: - The program is not compiled in strict ANSI C mode (/STANDARD=ANSI89). - _XOPEN_SOURCE is defined. - _XOPEN_SOURCE_EXTENDED is defined. o The X/Open Extended symbolic constants _SC_PAGESIZE, _SC_PAGE_SIZE, _SC_ATEXIT_MAX, and _SC_IOV_MAX were added to to support the sysconf function. However, these constants are not defined by _POSIX_C_SOURCE. The header file defines these constants only if a program does not define _POSIX_C_SOURCE and does define _XOPEN_SOURCE_EXTENDED. If _POSIX_C_SOURCE is defined, these constants are not visible in . Note that _POSIX_C_SOURCE is defined only for programs compiled in strict ANSI C mode. o The fgetname function is a Compaq C RTL extension to . Therefore, defines fgetname only if the program is not compiled in strict ANSI C mode (/STANDARD=ANSI89). o The macro _PTHREAD_KEYS_MAX is defined by POSIX 1003.1c-1995. This macro is made visible in when compiling for this standard with _POSIX_C_SOURCE == 199506 defined, or by default when compiling without any standards-defining, feature-test macros. Introduction 1-33 o The macro WCHAR_MAX defined in is required by ISO C Amendment 1 but not by XPG4. Therefore: - Compiling for ISO C Amendment 1 makes this symbol visible, but compiling for XPG4 compliance does not. - Compiling for both ISO C Amendment 1 and XPG4 makes this symbol visible. Similarly, the functions wcsftime and wcstok in are defined slightly differently by the ISO C Amendment 1 and XPG4: - Compiling for ISO C Amendment 1 makes the ISO C Amendment 1 prototypes visible. - Compiling for XPG4 compliance makes the XPG4 prototypes visible. - Compiling for both ISO C Amendment 1 and XPG4 selects the ISO C prototypes because conflicts resulting from this mode of compilation resolve in favor of ISO C. - Compiling without any standard selecting feature test macros makes ISO C Amendment 1 features visible. So in this example, compiling with no standard-selecting feature-test macros makes WCHAR_MAX and the ISO C Amendment 1 prototypes for wcsftime and wcstok visible. o The wcswidth and wcwidth functions are XPG4 extensions to ISO C Amendment 1. Their prototypes are in . These symbols are visible if: - Compiling for XPG4 compliance by defining _XOPEN_ SOURCE or _XOPEN_SOURCE_EXTENDED. - Compiling for DEC C Version 4.0 compatibility or on pre-OpenVMS Version 7.0 systems. - Compiling with no standard selecting feature test macros. - Compiling for both ISO C Amendment 1 and XPG4 compilance because these symbols are XPG4 extensions to ISO C Amendment 1. Compiling for strict ISO C Amendment 1 does not make them visible. 1-34 Introduction 1.5.4 Multiple-Version-Support Macro By default, the header files enable APIs in the Compaq C RTL provided by the version of the operating system on which the compilation occurs. This is accomplished by the predefined setting of the __VMS_VER macro, as described in the Compaq C User's Guide for OpenVMS Systems. For example, compiling on OpenVMS Version 6.2 causes only Compaq C RTL APIs from Version 6.2 and earlier to be made available. Another example of the use of the __VMS_VER macro is support for the 64-bit versions of Compaq C RTL functions available with OpenVMS Alpha Version 7.0 and higher. In all header files, functions that provide 64-bit support are conditionalized so that they are visible only if __VMS_ VER indicates a version of OpenVMS that is greater than or equal to 7.0. To target an older version of the operating system, do the following: 1. Define a logical DECC$SHR to point to the old version of DECC$SHR. The compiler uses a table from DECC$SHR to perform routine name prefixing. 2. Define __VMS_VER appropriately, either with the /DEFINE qualifier or with a combination of the #undef and #define preprocessor directives. With /DEFINE, you may need to disable the warning regarding redefinition of a predefined macro. Targeting a newer version of the operating system might not always be possible. For some versions, you can expect that the new DECC$SHR.EXE will require new features of the operating system that are not present. For such versions, the defining if the logical DECC$SHR in Step 1 would cause the compilation to fail. 1.5.5 Compatibility Modes The following predefined macros are used to select header- file compatibility with previous versions of DEC C) or the OpenVMS operating system: o _DECC_V4_SOURCE o _VMS_V6_SOURCE Introduction 1-35 There are two types of incompatibilities that can be controlled in the header files: o To conform to standards, some changes are source-code incompatible but binary compatible. To select DEC C Version 4.0 source compatibility, use the _DECC_V4_ SOURCE macro. o Other changes to conform to standards introduce a binary or run-time incompatibility. In general, programs that recompile get new behaviors. In these cases, use the _VMS_V6_SOURCE feature test macro to retain previous behaviors. However, for the exit, kill, and wait functions, the OpenVMS Version 7.0 changes to make these routines ISO POSIX-1 compliant were considered too incompatible to become the default. Therefore, in these cases the default behavior is the same as on pre-OpenVMS Version 7.0 systems. To access the versions of these routines that comply with ISO POSIX-1, use the _POSIX_EXIT feature test macro. The following examples help clarify the use of these macros: o To conform to the ISO POSIX-1 standard, typedefs for the following have been added to : dev_t gid_t ino_t mode_t nlink_t off_t pid_t size_t ssize_t uid_t Previous development environments using a version of DEC C earlier than Version 5.2 may have compensated for the lack of these typedefs in by adding them to another module. If this is the case on your system, then compiling with the provided with DEC C Version 5.2 might cause compilation errors. 1-36 Introduction To maintain your current environment and include the DEC C Version 5.2 , then compile with _DECC_V4_ SOURCE defined. This will omit incompatible references from the DEC C Version 5.2 headers. In , for example, the previously listed typedefs will not be visible. o As of OpenVMS Version 7.0, the Compaq C RTL getuid and geteuid functions are defined to return an OpenVMS UIC (user identification code) that contains both the group and member portions of the UIC. In previous versions of the DEC C RTL, these functions returned only the member number from the UIC code. Note that the prototypes for getuid and geteuid in (as required by the ISO POSIX-1 standard) and in (for Compaq C RTL compatibility) have not changed. By default, newly compiled programs that call getuid and geteuid get the new definitions. That is, these functions will return an OpenVMS UIC. To let programs retain the pre-OpenVMS Version 7.0 behavior of getuid and geteuid, compile with the _VMS_ V6_SOURCE feature-test macro defined. o As of OpenVMS Version 7.0, the Compaq C RTL exit function is defined with ISO POSIX-1 semantics. As a result, the input status argument to exit takes a number between 0 and 255. (Prior to this, exit could take an OpenVMS condition code in its status parameter.) By default, the behavior for exit on OpenVMS systems is the same as before - exit accepts an OpenVMS condition code. To enable the ISO POSIX-1 compatible exit function, compile with the _POSIX_EXIT feature-test macro defined. 1.5.6 Curses and Socket Compatibility Macros The following feature-test macros are used to control the curses and socket subsets of the Compaq C RTL library: o _BSD44_CURSES This macro selects the curses package from the 4.4BSD Berkeley Software Distribution. Introduction 1-37 o _VMS_CURSES This macro selects a curses package based on the VAX C compiler. This is the default curses package. o _SOCKADDR_LEN This macro is used to select 4.4BSD-compatible and XPG4 V2-compatible socket interfaces. These interfaces require support in your underlying TCP/IP software. Contact your TCP/IP vendor to inquire if the version of TCP/IP software you run supports 4.4BSD sockets. Strict XPG4 V2 compliance requires the 4.4BSD-compatible socket interface. Therefore, if _XOPEN_SOURCE_EXTENDED is defined on OpenVMS Version 7.0 or higher, _SOCKADDR_LEN is defined to be 1. The following examples help clarify the use of these macros: o Symbolic constants like AE, AL, AS, AM, BC, which represent pointers to termcap fields used by the BSD curses package, are only visible in if _ BSD44_CURSES is defined. o The header file defines a 4.4BSD sockaddr structure only if _SOCKADDR_LEN or _XOPEN_SOURCE_ EXTENDED is defined. Otherwise, defines a pre-4.4BSD sockaddr structure. If _SOCKADDR_LEN is defined and _XOPEN_SOURCE_EXTENDED is not defined, The header file also defines an osockaddr structure, which is a 4.3BSD sockaddr structure to be used for compatibility purposes. Since XPG4 V2 does not define an osockaddr structure, it is not visible in _ XOPEN_SOURCE_EXTENDED mode. 1.6 Input and Output on OpenVMS Systems After you learn how to link with the Compaq C RTL and call Compaq C functions and macros, you can use the Compaq C RTL for its primary purpose: input/output (I/O). Since every system has different methods of I/O, familiarize yourself with the OpenVMS-specific methods of file access. In this way, you will be equipped to predict 1-38 Introduction functional differences when porting your source program from one operating system to another. Figure 1-2 shows the I/O methods available with the Compaq C RTL. The OpenVMS system services communicate directly with the OpenVMS operating system, so they are closest to the operating system. The OpenVMS Record Management Services (RMS) functions use the system services, which manipulate the operating system. The Compaq C Standard I/O and UNIX I/O functions and macros use the RMS functions. Since the Compaq C RTL Standard I/O and UNIX I/O functions and macros must go through several layers of function calls before the system is manipulated, they are furthest from the operating system. Figure 1-2 I/O Interface from C Programs The C programming language was developed on the UNIX operating system, and the Standard I/O functions were designed to provide a convenient method of I/O that would be powerful enough to be efficient for most applications, and also be portable so that the functions could be used on any system running C language compilers. The Compaq C RTL adds functionality to this original specification. Since, as implemented in the Compaq C RTL, the Standard I/O functions recognize line terminators, the Compaq C RTL Standard I/O functions are particularly useful for text manipulation. The Compaq C RTL also implements some of the Standard I/O functions as preprocessor defined macros. Introduction 1-39 In a similar manner, the UNIX I/O functions originally were designed to provide a more direct access to the UNIX operating systems. These functions were meant to use a numeric file descriptor to represent a file. A UNIX system represents all peripheral devices as files to provide a uniform method of access. The Compaq C RTL adds functionality to the original specification. The UNIX I/O functions, as implemented in Compaq C, are particularly useful for manipulating binary data. The Compaq C RTL also implements some of the UNIX I/O functions as preprocessor defined macros. The Compaq C RTL includes the Standard I/O functions that should exist on all C compilers, and also the UNIX I/O functions to maintain compatibility with as many other implementations of C as possible. However, both Standard I/O and UNIX I/O use RMS to access files. To understand how the Standard I/O and UNIX I/O functions manipulate RMS formatted files, learn the fundamentals of RMS. See Section 1.6.1 for more information about Standard I/O and UNIX I/O in relationship to RMS files. For an introduction to RMS, see the Guide to OpenVMS File Applications. Before deciding which method is appropriate for you, first ask this question: Are you concerned with UNIX compatibility or with developing code that will run solely under the OpenVMS operating system? o If UNIX compatibility is important, you probably want to use the highest levels of I/O-Standard I/O and UNIX I/O-because that level is largely independent of the operating system. Also, the highest level is easier to learn quickly, an important consideration if you are a new programmer. o If UNIX compatibility is not important to you or if you require the sophisticated file processing that the Standard I/O and UNIX I/O methods do not provide, you might find RMS desirable. If you are writing system-level software, you may need to access the OpenVMS operating system directly through calls to system services. For example, you may need to access a user-written device driver directly through the Queue I/O Request System Service ($QIO). To do this, use the 1-40 Introduction OpenVMS level of I/O; this level is recommended if you are an experienced OpenVMS programmer. For examples of programs that call OpenVMS system services, see the Compaq C User's Guide for OpenVMS Systems. You may never use the RMS or the OpenVMS system services. The Standard I/O and UNIX I/O functions are efficient enough for a large number of applications. Figure 1-3 shows the dependency of the Standard I/O and the UNIX I/O functions on RMS, and the various methods of I/O available to you. Figure 1-3 Mapping Standard I/O and UNIX I/O to RMS 1.6.1 RMS Record and File Formats To understand the capabilities and the restrictions of the Standard I/O and UNIX I/O functions and macros, you need to understand VAX Record Management Services (RMS). Introduction 1-41 RMS supports the following file organizations: o Sequential o Relative o Indexed Sequential files have consecutive records with no empty records in between; relative files have fixed-length cells that may or may not contain a record; and indexed files have records that contain data, carriage-control information, and keys that permit various orders of access. The Compaq C RTL functions can access only sequential files. If you wish to use the other file organizations, you must use the RMS functions. For more information about the RMS functions, see the Compaq C User's Guide for OpenVMS Systems. RMS is not concerned with the contents of records, but it is concerned about the record format, which is the way a record physically appears on the recording surface of the storage medium. RMS supports the following record formats: o Fixed length o Variable length o Variable with fixed-length control (VFC) o Stream You can specify a fixed-length record format at the time of file creation. This means that all records occupy the same amount of space in the file. You cannot change the record format once you create the file. The length of records in variable length, VFC, and stream file formats can vary up to a maximum size that must be specified when you create the file. With variable-length record or VFC format files, the size of the record is held in a header section at the beginning of the data record. With stream files, RMS terminates the records when it encounters a specific character, such as a carriage-control or line-feed character. Stream files are useful for storing text. 1-42 Introduction RMS allows you to specify carriage-control attributes for records in a file. Such attributes include the implied carriage-return or the FORTRAN formatted records. RMS interprets these carriage controls when the file is output to a terminal, a line printer, or other device. The carriage-control information is not stored in the data records. By default, files inherit the RMS record format, maximum record size and record attributes, from the previous version of the file, if one exists; to an OpenVMS system programmer, the inherited attributes are known as fab$b_ rfm, fab$w_mrs and fab$b_rat. If no previous versions exist, the newly created file defaults to stream format with line-feed record separator and implied carriage-return attributes. (This manual refers to this type of file as a stream file.) You can manipulate stream files using the Standard I/O and the UNIX I/O functions of the Compaq C RTL. When using these files and fixed-record files with no carriage control, there is no restriction on the ability to seek to any random byte of the file using the fseek or the lseek functions. However, if the file has one of the other RMS record formats, such as variable-length record format, then these functions, due to RMS restrictions, can seek only to record boundaries. Use the default VAX stream format unless you need to create or access files to be used with other VAX languages or utilities. 1.6.2 Access to RMS Files RMS sequential files can be opened in record mode or stream mode. By default, STREAM_LF files are opened in stream mode; all other file types are opened in record mode. When opening a file, you can override these defaults by specifying the optional argument "ctx=rec" to force record mode, or "ctx=stm" to force stream mode. RMS relative and indexed files are always opened in record mode. The access mode determines the behavior of various I/O functions in the Compaq C RTL. One of the file types defined by RMS is an "RMS-11 stream" format file, corresponding to a value of FAB$C_STM for the record format. The definition of this format is such that the RMS record operation SYS$GET removes leading null bytes from each record. Because this file type is processed in Introduction 1-43 record mode by the Compaq C RTL, it is unsuitable as a file format for binary data unless it is explicitly opened with "ctx=stm", in which case the raw bytes of data from the file are returned. ________________________ Note ________________________ In OpenVMS Version 7.0 the default LRL value on stream files was changed from 0 to 32767. This change caused significant performance degradation on certain file operations such as sort. This is no longer a problem. The Compaq C Run-Time Library now lets you define the logical DECC$DEFAULT_ LRL to change the default record-length value on stream files. The Compaq C Run-Time Library first looks for this logical. If it is found and it translates to a numeric value between 0 and 32767, that value is used for the default LRL. To restore the behavior prior to OpenVMS Version 7.0, enter the following command: $ DEFINE DECC$DEFAULT_LRL 0 ______________________________________________________ 1.6.2.1 Accessing RMS Files in Stream Mode Stream access to RMS files is done with the block I/O facilities of RMS. Stream input is performed from RMS files by passing each byte of the on-disk representation of the file to your program. Stream output to RMS files is done by passing each byte from your program to the file. The Compaq C RTL performs no special processing on the data. When opening a file in stream mode, the Compaq C RTL allocates a large internal buffer area. Data is read from the file using a single read into the buffer area and then passing the data to your program as needed. Data is written to the file when the internal buffer is full or when the fflush function is called. 1-44 Introduction 1.6.2.2 Accessing RMS Record Files in Record Mode Record access to record files is done with the record I/O facilities of RMS. The Compaq C RTL emulates a byte stream by translating carriage-control characters during the process of reading and writing records. Random access is allowed to all record files, but positioning (with fseek and lseek) must be on a record boundary for VFC files, variable record files, or files with non-null carriage control. Positioning a record file causes all buffered input to be discarded and buffered output to be written to the file. Record input from RMS record files is emulated by the Compaq C RTL in two steps: 1. The Compaq C RTL reads a logical record from the file. If the record format is variable length with fixed control (RFM = VFC), and the record attributes are not print carriage control (RAT is not PRN), then the Compaq C RTL concatenates the fixed-control area to the beginning of the record. 2. The Compaq C RTL expands the record to simulate a stream of bytes by translating the record's carriage-control information (if any). In RMS terms, the Compaq C RTL translates the record's carriage-control information using one of the following methods: o If the record attribute is implied carriage control (RAT = CR), then the Compaq C RTL appends a new-line character to the record. This new-line character is considered an integral part of the record, which means for example, that it can be obtained by the fgetc function and is considered a line terminator by the fgets function. Since fgets reads the file up to the new-line character, for RAT=CR files this function cannot retrieve a string that crosses the record boundaries. o If the record attributes are print carriage control (RAT = PRN), then the Compaq C RTL expands and concatenates the prefix and postfix carriage controls before and after the record. Introduction 1-45 This translation is done according to rules specified by RMS, with one exception: if the prefix character is x01 and the postfix character is x8D, then nothing is attached to the beginning of the record and a single new-line character is attached to the end of it. This is done because this prefix/postfix combination is normally used to represent a line. o If the record attributes are FORTRAN carriage control (RAT = FTN), then the Compaq C RTL removes the initial control byte and attaches the appropriate carriage- control characters before and after the data as defined by RMS, with the exception of the space and default carriage-control characters. In these cases, which are used to represent a line, the Compaq C RTL appends a single new-line character to the data. The mapping of Fortran cariage-control can be disabled by using "ctx=nocvt". o If the record attributes are null (RAT = NONE) and the input is coming from a terminal, then the Compaq C RTL appends the terminating character to the record. If the terminator is a carriage return or Ctrl/Z, then Compaq C translates the character to a new-line character (\n). If the input is coming from a nonterminal file, then the Compaq C RTL passes the record unchanged to your program with no additional prefix or postfix characters. As you read from the file, the Compaq C RTL delivers a stream of bytes resulting from the translations. Information that is not read from an expanded record by one function call is delivered on the next input function call. The Compaq C RTL performs record output to RMS record files in two steps. The first part of the record output emulation is the formation of a logical record. As you write bytes to a record file, the emulator examines the information being written for record boundaries. The handling of information in the byte stream depends on the attributes of the destination file or device, as follows: 1-46 Introduction o For all files, if the number of output bytes is greater than the internal buffer allocated by the Compaq C RTL, a record is output. o For files with fixed record length (RFM = FIX) or for files opened with "ctx=bin" or "ctx=xplct", a record is output only when the internal buffer is filled or when the flush function is called. o For files with STREAM_CR record format (RFM = STMCR), the Compaq C RTL outputs a record when it encounters a carriage-return character (\r). o For files with STREAM record format (RFM = STM) the Compaq C RTL outputs a record when it encounters a new-line (\n), form feed (\f), or vertical tab (\v) character. o For all other file types, the Compaq C RTL outputs a record when it encounters a new-line (\n) character. The second part of record output emulation is to write the logical record formed during the first step. The Compaq C RTL forms the output record as follows: o If the record attribute is carriage control (R AT = CR), and if the logical record ends with a new-line character (\n), the Compaq C RTL drops the new-line character and writes the logical record with implied carriage control. o If the record attribute is print carriage control (RAT = PRN), then the Compaq C RTL writes the record with print carriage control according to the rules specified by RMS. If the logical record ends with a single new- line character (\n), the Compaq C RTL maps the new-line character to an x01 prefix and x8D postfix character. This is the reverse of the translation for record input files with print carriage-control attributes. o If the record attributes are Fortran carriage control (RAT = FTN), then the Compaq C RTL removes any prefix and/or postfix carriage control characters and concatenates a single carriage control byte to the beginning of the record as defined by RMS, with one exception: If the output record ends in a new-line character (\n), the Compaq C RTL will remove the new- line and use the space carriage control byte. This is Introduction 1-47 the reverse of the translation for record input files with Fortran carriage-control attributes. The mapping of Fortran cariage-control can be disabled by using "ctx=nocvt". o If the logical record is to be written to a terminal device and the last character of the record is a new- line character (\n) the Compaq C RTL replaces the new- line character with a carriage-return (\r), and attaches a line-feed character (\n) to the front of the record. The Compaq C RTL then writes out the record with no carriage control. o If the output file record format is variable length with fixed control (RFM = VFC), and the record attributes do not include print carriage control (RAT is not PRN), then the Compaq C RTL takes the beginning of the logical record to be the fixed-control header, and reduces the number of bytes written out by the length of the header. These bytes are then used to construct the fixed-control header. If there are too few bytes in the logical record, an error is signaled. 1.6.2.2.1 Accessing Variable-Length or VFC Record Files in Record Mode When you access a variable-length or VFC record file in record mode, many I/O functions behave differently than they would if they were being used with stream mode. This section describes these differences. In general, the new-line character (\n) is the record separator for all record modes. On output, when a new- line character is encountered, a record is generated unless you specify an optional argument (such as "ctx=bin" or "ctx=xplct") that affects the interpretation of new lines. The read and decc$record_read functions always read at most one record. The write and decc$record_write functions always generate at least one record. decc$record_read and decc$record_write are equivalent, respectively, to read and write, except that they work with file pointers rather than file descriptors. 1-48 Introduction Unlike the read function which reads at most one record, the fread function can span records. Rather than read number_items records (where number_items is the third parameter to fread), fread tries to read the number of bytes equal to number_items x size_of_item (where size_of_ item is the second parameter to fread). The value returned by fread is equal to the number of bytes read divided by size_of_item. However, the fwrite function always generates at least number_items records. The fgets and gets functions read to either a new-line character or a record boundary. The fflush function always generates a record if there is unwritten data in the buffer. The same is true of close, fclose, fseek, lseek, rewind, and fsetpos, all of which perform implicit fflush functions. A record is also generated whenever an attempt is made to write more characters than allowed by the maximum record size. For more information on these functions, see the Reference Section. 1.6.2.2.2 Accessing Fixed-Length Record Files in Record Mode When accessing a fixed-length record file in record mode, the I/O functions generally behave as described in Section 1.6.2.2.1. The write, fwrite, and decc$record_write functions will fail if given a record size that is not an integral multiple of the maximum record size, unless the file was opened with the "ctx=xplct" optional argument specified. All other output functions will generate records at every nth byte, where n is the maximum record size. If a new record is forced by fflush, the data in the buffer is padded to the maximum record size with null characters. ________________________ Note ________________________ This padding can cause problems for programs that seek to the end-of-file. For example, if a program were to append data to a file, then seek backwards in the file (causing an fflush to occur), and then seek to the Introduction 1-49 end-of-file again, a zero-filled "hole" will have been created between the previous end-of-file and the new end-of-file if the previous end-of-file was not on a record boundary. ______________________________________________________ 1.6.2.3 Example-Difference Between Stream Mode and Record Mode Example 1-1 demonstrates the difference between stream mode and record mode access. Example 1-1 Differences Between Stream Mode and Record Mode /* CHAP_1_STREAM_RECORD.C */ /* This program demonstrates the difference between */ /* record mode and stream mode Input/Output. */ #include #include #include void process_records(const char *fspec, FILE * fp); main() { FILE *fp; fp = fopen("example-fixed.dat", "w", "rfm=fix", "mrs=40", "rat=none"); if (fp == NULL) { perror("example-fixed"); exit(EXIT_FAILURE); } printf("Record mode\n"); process_records("example-fixed.dat", fp); fclose(fp); (continued on next page) 1-50 Introduction Example 1-1 (Cont.) Differences Between Stream Mode and Record Mode printf("\nStream mode\n"); fp = fopen("example-streamlf.dat", "w"); if (fp == NULL) { perror("example-streamlf"); exit(EXIT_FAILURE); } process_records("example-streamlf.dat", fp); fclose(fp); } void process_records(const char *fspec, FILE * fp) { int i, sts; char buffer[40]; /* Write records of all 1's, all 2's and all 3's */ for (i = 0; i < 3; i++) { memset(buffer, '1' + i, 40); sts = fwrite(buffer, 40, 1, fp); if (sts != 1) { perror("fwrite"); exit(EXIT_FAILURE); } } (continued on next page) Introduction 1-51 Example 1-1 (Cont.) Differences Between Stream Mode and Record Mode /* Rewind the file and write 10 characters of A's, then 10 B's, */ /* then 10 C's. */ /* */ /* For stream mode, each fwrite call outputs 10 characters */ /* and advances the file position 10 characters */ /* characters. */ /* */ /* For record mode, each fwrite merges the 10 characters into */ /* the existing 40-character record, updates the record and */ /* advances the file position 40 characters to the next record. */ rewind(fp); for (i = 0; i < 3; i++) { memset(buffer, 'A' + i, 10); sts = fwrite(buffer, 10, 1, fp); if (sts != 1) { perror("fwrite2"); exit(EXIT_FAILURE); } } /* Now reopen the file and output the records. */ fclose(fp); fp = fopen(fspec, "r"); for (i = 0; i < 3; i++) { sts = fread(buffer, 40, 1, fp); if (sts != 1) perror("fread"); printf("%.40s\n", buffer); } return; } 1-52 Introduction Running this program produces the following output: Record Mode AAAAAAAAAA111111111111111111111111111111 BBBBBBBBBB222222222222222222222222222222 CCCCCCCCCC333333333333333333333333333333 Stream mode AAAAAAAAAABBBBBBBBBBCCCCCCCCCC1111111111 2222222222222222222222222222222222222222 3333333333333333333333333333333333333333 1.7 Specific Portability Concerns One of the last tasks in preparing to use the Compaq C RTL, if you are going to port your source programs across systems, is to be aware of specific differences between the Compaq C RTL and the run-time libraries of other implementations of the C language. This section describes some of the problems that you might encounter when porting programs to and from an OpenVMS system. Although portability is closely tied to the implementation of the Compaq C RTL, this section also contains information on the portability of other Compaq C for OpenVMS constructs. The Compaq C RTL provides ANSI C defined library functions as well as many commonly available APIs and a few OpenVMS extensions. See Section 1.5 for specific standards, portions of which are implemented by the Compaq C RTL. Attempts have been made to maintain complete portability in functionality whenever possible. Many of the Standard I/O and UNIX I/O functions and macros contained in the Compaq C RTL are functionally equivalent to those of other implementations. The RTL function and macro descriptions elaborate on issues presented in this section and describe concerns not documented here. The following list documents issues of concern if you wish to port C programs to the OpenVMS environment: o Compaq C for OpenVMS Systems does not implement the global symbols end, edata, and etext. Introduction 1-53 o There are differences in how OpenVMS and UNIX systems lay out virtual memory. In some UNIX systems, the address space between 0 and the break address is accessible to your program. In OpenVMS systems, the first page of memory is not accessible. For example, if a program tries to reference location 0 on an OpenVMS system, a hardware error (ACCVIO) is returned and the program terminates abnormally. OpenVMS systems reserve the first page of address space to catch incorrect pointer references, such as a reference to a location pointed to by a null pointer. For this reason, some existing programs that run on some UNIX systems may fail and you should modify them, as necessary. (Tru64 UNIX and OpenVMS, however, are compatible in this regard.) o Some C programmers code all external declarations in #include files. Then, specific declarations that require initialization are redeclared in the relevant module. This practice causes the Compaq C compiler to issue a warning message about multiply declared variables in the same compilation. One way to avoid this warning is to make the redeclared symbols extern variables in the #include files. o Compaq C does not support asm calls on OpenVMS VAX systems. They are supported on OpenVMS Alpha systems. See the Compaq C User's Guide for OpenVMS Systems for more information on intrinsic functions. o Some C programs call the counted string functions strcmpn and strcpyn. These names are not used by Compaq C for OpenVMS Systems. Instead, you can define macros that expand the strcmpn and strcpyn names into the equivalent, ANSI-compliant names strncmp and strncpy. o The Compaq C for OpenVMS compiler does not support the following initialization form: int foo 123; Programs using this form of initialization must be changed. 1-54 Introduction o Compaq C for OpenVMS Systems predefines several compile- time macros such as __vax, __alpha, __32BITS, __vms, __vaxc, __VMS_VER, __DECC_VER, __D_FLOAT, __G_FLOAT, __IEEE_FLOAT, __X_FLOAT, and others. These predefined macros are useful for programs that must be compatible on other machines and operating systems. For more information, see the predefined macro chapter of the Compaq C User's Guide for OpenVMS Systems. o The ANSI C language does not guarantee any memory order for the variables in a declaration. For example: int a, b, c; o Depending on the type of external linkage requested, extern variables in a program may be treated differently using Compaq C on OpenVMS systems than they would on UNIX systems. See the Compaq C User's Guide for OpenVMS Systems for more information. o The dollar sign ($) is a legal character in Compaq C for OpenVMS identifiers, and can be used as the first character. o The ANSI C language does not define any order for evaluating expressions in function parameter lists or for many kinds of expressions. The way in which different C compilers evaluate an expression is only important when the expression has side effects. Consider the following examples: a[i] = i++; x = func_y() + func_z(); f(p++, p++) Neither Compaq C nor any other C compiler can guarantee that such expressions evaluate in the same order on all C compilers. o The size of a Compaq C variable of type int is 32 bits on OpenVMS systems. You will have to modify programs that are written for other machines and that assume a different size for a variable of type int. A variable of type long is the same size (32 bits) as a variable of type int. Introduction 1-55 o The C language defines structure alignment to be dependent on the machine for which the compiler is designed. On OpenVMS VAX systems, Compaq C aligns structure members on byte boundaries, unless #pragma member_alignment is specified. On OpenVMS Alpha systems, Compaq C aligns structure members on natural boundaries, unless #pragma nomember_alignment is specified. Other implementations may align structure members differently. o References to structure members in Compaq C cannot be vague. For more information, see the Compaq C Language Reference Manual. o Registers are allocated based upon how often a variable is used, but the register keyword gives the compiler a strong hint that you want to place a particular variable into a register. Whenever possible, the variable is placed into a register. Any scalar variable with the storage class auto or register can be allocated to a register as long as the variable's address is not taken with the ampersand operator (&) and it is not a member of a structure or union. 1.7.1 Reentrancy The Compaq C RTL supports an improved and enhanced reentrancy. The following types of reentrancy are supported: o AST reentrancy uses the _BBSSI built-in function to perform simple locking around critical sections of RTL code, but it may also disable asynchronous system traps (AST)s in locked regions of code. This type of locking should be used when AST code contains calls to Compaq C RTL I/O routines. Failure to specify AST reentrancy might cause I/O routines to fail, setting errno to EALREADY. o MULTITHREAD reentrancy is designed to be used in threaded programs such as those that use the DECthreads library. It performs DECthreads locking and never disables ASTs. DECthreads must be available on your system to use this form of reentrancy. 1-56 Introduction o TOLERANT reentrancy uses the _BBSSI built-in function to perform simple locking around critical sections of RTL code, but ASTs are not disabled. This type of locking should be used when ASTs are used and must be delivered immediately. o NONE gives optimal performance in the Compaq C RTL, but does absolutely no locking around critical sections of RTL code. It should only be used in a single-threaded environment when there is no chance that the thread of execution will be interrupted by an AST that would call the Compaq C RTL. The default reentrancy type is TOLERANT. You can set the reentrancy type by compiling with the /REENTRANCY command-line qualifier or by calling the decc$set_reentrancy function. This function must be called exclusively from non-AST level. When programming an application using multiple threads or ASTs, you should consider three classes of functions: o Functions with no internal data o Functions with thread-local internal data o Functions with process-wide internal data Most functions have no internal data at all. For these functions, synchronization is necessary only if the parameter is used by the application in multiple threads or in both AST and non-AST context. For example, although the strcat function is ordinarily safe, the following is an example of unsafe usage: extern char buffer[100]; void routine1(char *data) { strcat( buffer, data ); } If routine1 executed concurrently in multiple threads, or if routine1 is interrupted by an AST routine that calls it, the results of the strcat call are unpredictable. Introduction 1-57 The second class of functions are those that have thread- local static data. Typically, these are routines in the library that return a string where the application is not permitted to free the storage for the string. These routines are thread-safe but not AST-reentrant. This means they can safely be called concurrently, and each thread will have its own copy of the data. They cannot be called from AST routines if it is possible that the same routine was executing in non-AST context. The routines in this class are: asctime stat ctermid strerror ctime strtok cuserid VAXC$ESTABLISH gmtime the errno variable localtime wcstok perror All the socket functions are also included in this list if the TCP/IP product in use is thread-safe. The third class of functions are those that affect process- wide data. These functions are neither thread-safe nor AST-reentrant. For example, sigsetmask establishes the process-wide signal mask. Consider a routine like the following: void update_data base() { int old_mask; old_mask = sigsetmask( 1 << (SIGINT - 1)); /* Do work here that should not be aborted. */ sigsetmask( old_mask ); } If update_database was called concurrently in multiple threads, thread 1 might unblock SIGINT while thread 2 was still performing work that should not be aborted. The routines in this class are: o All the signal routines o All the exec routines 1-58 Introduction o The exit, _exit, nice, system, wait, getitimer, setitimer, and setlocale routines. ________________________ Note ________________________ Generally speaking, UTC-based time functions can affect in-memory time-zone information, which is process-wide data. However, if the system time zone remains the same during the execution of the application (which is the common case) and the cache of timezone files is enabled (which is the default), then the _r variant of the time functions asctime_r, ctime_r, gmtime_r and localtime_r is both thread-safe and AST-reentrant. If, however, the system time zone can change during the execution of the application or the cache of timezone files is not enabled, then both variants of the UTC-based time functions belong to the third class of functions, which are neither thread-safe nor AST-reentrant. ______________________________________________________ 1.7.2 Multithread Restrictions Mixing the multithread programming model and the OpenVMS AST programming model in the same application is not recommended. The application has no mechanism to control which thread gets interrupted by an AST. This can result in a resource deadlock if the thread holds a resource that is also needed by the AST routine. The following routines use mutexes. To avoid a potential resource deadlock, do not call them from AST routines in a multithreaded application. o All the I/O routines o All the socket routines o All the signal routines o vfork, exec, wait, system o catgets o set_new_handler (C++ only) o getenv o rand and srand Introduction 1-59 o exit and _exit o clock o nice o times o ctime, localtime, asctime, mktime 1.8 64-bit Pointer Support (Alpha only) This section is for application developers who need to use 64-bit virtual memory addressing on OpenVMS Alpha Version 7.0 or higher. OpenVMS Alpha 64-bit virtual addressing support makes the 64-bit virtual address space defined by the Alpha architecture available to both the OpenVMS operating system and its users. It also allows per-process virtual addressing for accessing dynamically mapped data beyond traditional 32-bit limits. The Compaq C Run-Time Library on OpenVMS Alpha Version 7.0 systems and higher includes the following features in support of 64-bit pointers: o Guaranteed binary and source compatibility of existing programs o No impact on applications that are not modified to exploit 64-bit support o Enhanced memory allocation routines that allocate 64-bit memory o Widened function parameters to accommodate 64-bit pointers o Dual implementations of functions that need to know the pointer size used by the caller o New information available to the DEC C Version 5.2 compiler or higher to seamlessly call the correct implementation o Ability to explicitly call either the 32-bit or 64-bit form of functions for applications that mix pointer sizes 1-60 Introduction o A single shareable image for use by 32-bit and 64-bit applications 1.8.1 Using the Compaq C Run-Time Library The Compaq C Run-Time library on OpenVMS Alpha Version 7.0 systems and higher can generate and accept 64-bit pointers. Functions that require a second interface to be used with 64-bit pointers reside in the same object libraries and shareable images as their 32-bit counterparts. No new object libraries or shareable images are introduced. Using 64-bit pointers does not require changes to your link command or link options files. The Compaq C 64-bit environment allows an application to use both 32-bit and 64-bit addresses. For more information about how to manipulate pointer sizes, see the /POINTER_ SIZE qualifier and #pragma pointer_size and #pragma required_pointer_size preprocessor directives in the Compaq C User's Guide for OpenVMS Systems. The /POINTER_SIZE qualifier requires you to specify a value of 32 or 64. This value is used as the default pointer size within the compilation unit. As an application programmer, you can compile one set of modules by using 32-bit pointers and another set by using 64-bit pointers. Care must be taken when these two separate groups of modules call each other. Use of the /POINTER_SIZE qualifier also influences the processing of Compaq C RTL header files. For those functions that have a 32-bit and 64-bit implementation, specifying /POINTER_SIZE enables function prototypes to access both functions, regardless of the actual value supplied to the qualifier. In addition, the value specified to the qualifier determines the default implementation to call during that compilation unit. The #pragma pointer_size and #pragma required_pointer_size preprocessor directives can be used to change the pointer size in effect within a compilation unit. You can default pointers to 32-bit pointers and then declare specific pointers within the module as 64-bit pointers. You would also need to specifically call the _malloc64 form of malloc to obtain memory from the 64-bit memory area. Introduction 1-61 1.8.2 Obtaining 64-bit Pointers to Memory The Compaq C RTL has many functions that return pointers to newly allocated memory. In each of these functions, the application owns the memory pointed to and is responsible for freeing that memory. Functions that allocate memory are: malloc calloc realloc strdup Each of these functions have a 32-bit and a 64-bit implementation. When the /POINTER_SIZE qualifier is used, the following functions can also be called: _malloc32, _malloc64 _calloc32, _calloc64 _realloc32, _realloc64 _strdup32, _strdup64 When /POINTER_SIZE=32 is specified, all malloc calls default to _malloc32. When /POINTER_SIZE=64 is specified, all malloc calls default to _malloc64. Regardless of whether the application calls a 32-bit or 64-bit memory allocation routine, there is still a single free function. This function accepts either pointer size. Be aware that the memory allocation functions are the only ones that return pointers to 64-bit memory. All Compaq C RTL structure pointers returned to the calling application (such as a FILE, WINDOW, or DIR) are always 32-bit pointers. This allows both 32-bit and 64-bit callers to pass these structure pointers within the application. 1.8.3 Compaq C Header Files The header files distributed with DEC C Version 5.2 and higher support 64-bit pointers. Each function prototype whose signature contains a pointer is constructed to indicate the size of the pointer accepted. 1-62 Introduction A 32-bit pointer can be passed as an argument to functions that accept either a 32-bit or 64-bit pointer for that argument. A 64-bit pointer, however, cannot be passed as an argument to a function that accepts a 32-bit pointer. Attempts to do this are diagnosed by the compiler with a MAYLOSEDATA message. The diagnostic message IMPLICITFUNC means the compiler can do no additional pointer-size validation for calls to that function. If this function is a Compaq C RTL function, refer to the reference section of this manual for the name of the header file that defines that function. You might find the following pointer-size compiler diagnostics useful: o %CC-IMPLICITFUNC A function prototype was not found before using the specified function. The compiler and run-time system rely on prototype definitions to detect incorrect pointer-size usage. Failure to include the proper header files can lead to incorrect results and/or pointer truncation. o %CC-MAYLOSEDATA A truncation is necessary to do this operation. The operation could be passing a 64-bit pointer to a function that does not support a 64-bit pointer in the given context. It could also be a function returning a 64-bit pointer to a calling application that is trying to store that return value in a 32-bit pointer. o %CC-MAYHIDELOSS This message (when enabled) helps expose real MAYLOSEDATA messages that are being suppressed because of a cast operation. To enable this warning, compile with the qualifier /WARNINGS=ENABLE=MAYHIDELOSS. Introduction 1-63 1.8.4 Functions Affected The Compaq C RTL shipped with OpenVMS Alpha Version 7.0 accommodates applications that use only 32-bit pointers, only 64-bit pointers, or combinations of both. To use 64- bit memory, you must, at a minimum, recompile and relink an application. The amount of source code change required depends on the application itself, calls to other runtime libraries, and the combinations of pointer sizes used. With respect to 64-bit pointer support, the functions in the Compaq C RTL fall into four categories: o Functions not impacted by choice of pointer size o Functions enhanced to accept either pointer size o Functions having a 32-bit and 64-bit implementation o Functions that accept only 32-bit pointers From an application developer's perspective, the first two types of functions are the easiest to use in either a single or mixed-pointer mode. The third type requires no modifications when used in a single-pointer compilation, but might require source code changes when used in a mixed-pointer mode. The fourth type requires careful attention whenever 64-bit pointers are used. 1.8.4.1 No Pointer-Size Impact The choice of pointer-size has no impact on a function if its prototype contains no pointer-related parameters or return values. The mathematical functions are good examples of this. Even some functions in this category that do have pointers in their prototype are not impacted by pointer size. For example, strerror has the prototype: char * strerror (int error_number); This function returns a pointer to a character string, but this string is allocated by the Compaq C RTL. As a result, to support both 32-bit and 64-bit applications, these types of pointers are guaranteed to fit in a 32-bit pointer. 1-64 Introduction 1.8.4.2 Functions Accepting Both Pointer Sizes The Alpha architecture supports 64-bit pointers. The OpenVMS Alpha calling standard specifies that all arguments are actually passed as 64-bit values. Before OpenVMS Alpha Version 7.0, all 32-bit addresses passed to procedures were sign-extended into this 64-bit parameter. The called function declared the parameters as 32-bit addresses, which caused the compiler to generate 32-bit instructions (such as LDL) to manipulate these parameters. Many functions in the Compaq C RTL are enhanced to receive the full 64-bit address. For example, consider strlen: size_t strlen (const char *string); The only pointer in this function is the character-string pointer. If the caller passes a 32-bit pointer, the function works with the sign-extended 64-bit address. If the caller passes a 64-bit address, the function works with that address directly. The Compaq C RTL continues to have only a single entry point for functions in this category. There are no source- code changes required to add any of the four pointer- size options for functions of this type. The OpenVMS documentation refers to these functions as 64-bit friendly. 1.8.4.3 Functions with Two Implementations There are many reasons why a function might need one implementation for 32-bit pointers, and another for 64-bit pointers. Some of these reasons include: o The pointer size of the return value is the same size as the pointer size of one of the arguments. If the argument is 32-bits, the return value is 32-bits. If the argument is 64-bits, the return value is 64-bits. o One of the arguments is a pointer to an object whose size is pointer-size sensitive. To know how many bytes are being pointed to, the function must know if the code was compiled in 32-bit or 64-bit pointer-size mode. o The function returns the address of dynamically allocated memory. The memory is allocated in 32- bit space when compiled for 32-bit pointers, and is allocated in 64-bit space when compiled for 64-bit pointers. Introduction 1-65 From the application developer's point of view, there are three function prototypes for each of these functions. The header file contains many functions whose return value is dependent upon the pointer size used as the first argument to the function call. For example, consider the memset function. The header file defines three entry points for this function: void * memset (void *memory_pointer, int character, size_t size); void *_memset32 (void *memory_pointer, int character, size_t size); void *_memset64 (void *memory_pointer, int character, size_t size); The first prototype is the function that your application would currently call if using this function. The compiler changes a call to memset into a call to either _memset32 when compiled /POINTER_SIZE=32, or _memset64 when compiled /POINTER_SIZE=64. You can override this default behavior by directly calling either the 32-bit or the 64-bit form of the function. This accommodates applications using mixed pointer sizes, regardless of the default pointer size specified with the /POINTER_SIZE qualifier. If the application is compiled without specifying the /POINTER_SIZE qualifier, neither the 32-bit specific nor the 64-bit specific function prototypes are defined. In this case, the compiler automatically calls the 32-bit interface for all interfaces having dual implementations. Table 1-5 shows the Compaq C RTL functions that have dual implementations in support of 64-bit pointer size. When compiling with the /POINTER_SIZE qualifier, calls to the unmodified function names are changed to calls to the function interface that matches the pointer size specified on the qualifier. Table_1-5_Functions_with_Dual_Implementations______________ basename malloc strpbrk wcsncat bsearch mbsrtowcs strptime wcsncpy calloc memccpy strrchr wcspbrk (continued on next page) 1-66 Introduction Table_1-5_(Cont.)_Functions_with_Dual_Implementations______ catgets memchr strsep wcsrchr ctermid memcpy strstr wcsrtombs cuserid memmove strtod wcsstr dirname memset strtok wcstok fgetname mktemp strtol wcstol fgets mmap strtoll wcstoul fgetws qsort strtoq wcswcs fullname realloc strtoul wmemchr gcvt rindex strtoull wmemcpy getcap strcat strtouq wmemmove getcwd strchr tgetstr wmemset getname strcpy tmpnam gets strdup wcscat index strncat wcschr longname____strncpy_____wcscpy_____________________________ 1.8.4.4 Functions Restricted to 32-Bit Pointers A few functions in the Compaq C RTL do not support 64-bit pointers. If you try to pass a 64-bit pointer to one of these functions, the compiler generates a %CC-W-MAYLOSEDATA warning. Applications compiled with /POINTER_SIZE=64 might need to be modified to avoid passing 64-bit pointers to these functions. Table 1-6 shows the functions restricted to using 32-bit pointers. The Compaq C RTL offers no 64-bit support for these functions. You must ensure that only 32-bit pointers are used with these functions. Table_1-6_Functions_restricted_to_32-bit_pointers__________ atexit frexp ioctl sendmsg execv getopt modf setbuf execve iconv putenv setstate execvp______initstate___recvmsg_____setvbuf________________ Introduction 1-67 Table 1-7 shows functions that make callbacks to user- supplied functions as part of processing that function call. The callback procedures are not passed 64-bit pointers. Table_1-7_Callbacks_that_Pass_Only_32-Bit_Pointers_________ decc$from_ decc$to_vms vms ftw_________tputs__________________________________________ 1.8.5 Reading Header Files This section introduces the pointer-size manipulations used in the Compaq C RTL header files. Use the following examples to become more proficient in reading these header files and to help modify your own header files. 1-68 Introduction Examples 1.: #if __INITIAL_POINTER_SIZE 1 # if (__VMS_VER < 70000000) || !defined __ALPHA 2 # error " Pointer size usage not permitted before OpenVMS Alpha V7.0" # endif # pragma __pointer_size __save 3 # pragma __pointer_size 32 4 #endif : : #if __INITIAL_POINTER_SIZE 5 # pragma __pointer_size 64 #endif : : #if __INITIAL_POINTER_SIZE 6 # pragma __pointer_size __restore #endif : All Compaq C compilers that support the /POINTER_SIZE qualifier predefine the macro __INITIAL_POINTER_SIZE. The Compaq C RTL header files take advantage of the ANSI rule that if a macro is not defined, it has an implicit value of 0. The macro is defined as 32 or 64 when the /POINTER_SIZE qualifier is used. It is defined as 0 if the qualifier is not used. The statement at 1 can be read as "if the user has specified either /POINTER_SIZE=32 or /POINTER_ SIZE=64 on the command line". DEC C Version 5.2 and higher is supported on many OpenVMS platforms. The lines at 2 generate an error message if the target of the compilation is one that does not support 64-bit pointers. A header file cannot assume anything about the actual pointer-size context in effect at the time the header file is included. Furthermore, the Compaq C compiler offers only the __INITIAL_POINTER_SIZE macro and a Introduction 1-69 mechanism to change the pointer size, but not a way to determine the current pointer size. All header files that have a dependency on pointer sizes are responsible for saving 3, initializing 4, altering 5, and restoring 6 the pointer-size context. 1-70 Introduction 2.: #ifndef __CHAR_PTR32 1 # define __CHAR_PTR32 1 typedef char * __char_ptr32; typedef const char * __const_char_ptr32; #endif : : #if __INITIAL_POINTER_SIZE # pragma __pointer_size 64 #endif : : #ifndef __CHAR_PTR64 2 # define __CHAR_PTR64 1 typedef char * __char_ptr64; typedef const char * __const_char_ptr64; #endif : Some function prototypes need to refer to a 32-bit pointer when in a 64-bit pointer-size context. Other function prototypes need to refer to a 64-bit pointer when in a 32-bit pointer-size context. Compaq C binds the pointer size used in a typedef at the time the typedef is made. The typedef declaration of __char_ptr32 1 is made in a 32-bit context. The typedef declaration of __char_ptr64 2 is made in a 64-bit context. Introduction 1-71 3. : #if __INITIAL_POINTER_SIZE # if (__VMS_VER < 70000000) || !defined __ALPHA # error " Pointer size usage not permitted before OpenVMS Alpha V7.0" # endif # pragma __pointer_size __save # pragma __pointer_size 32 #endif : 1 : #if __INITIAL_POINTER_SIZE 2 # pragma __pointer_size 64 #endif : 3 : int abs (int __j); 4 : __char_ptr32 strerror (int __errnum); 5 : Before declaring function prototypes that support 64-bit pointers, the pointer context is changed 2 from 32-bit pointers to 64-bit pointers. Functions restricted to 32-bit pointers are placed in the 32-bit pointer context section 1 of the header file. All other functions are placed in the 64-bit context section 3 of the header file. Functions that have no pointer-size impact (4 and 5) are located in the 64-bit section. Functions that have no pointer-size impact except for a 32-bit address return value 5 are also in the 64-bit section, and use the 32-bit specific typedefs previously discussed. 1-72 Introduction 4.: #if __INITIAL_POINTER_SIZE # pragma __pointer_size 64 #endif : : #if __INITIAL_POINTER_SIZE == 32 1 # pragma __pointer_size 32 #endif : char *strcat (char *__s1, __const_char_ptr64 __s2); 2 : #if __INITIAL_POINTER_SIZE # pragma __pointer_size 32 : char *_strcat32 (char *__s1, __const_char_ptr64 __s2); 3 : # pragma __pointer_size 64 : char *_strcat64 (char *__s1, const char *__s2); 4 : #endif : This example shows declarations of functions that have both a 32-bit and 64-bit implementation. These declarations are located in the 64-bit section of the header file. The normal interface to the function 2 is declared using the pointer size specified on the /POINTER_ SIZE qualifier. Because the header file is in 64-bit pointer context and because of the statements at 1, the declaration at 2 is made using the same pointer-size context as the /POINTER_SIZE qualifier. The 32-bit specific interface 3 and the 64-bit specific interface 4 are declared in 32-bit and 64-bit pointer- size context, respectively. Introduction 1-73 2 _________________________________________________________________ Understanding Input and Output There are three types of input and output (I/O) in the Compaq C Run-Time Library (RTL): UNIX, Standard, and Terminal. Table 2-1 lists all the I/O functions and macros found in the Compaq C RTL. For more detailed information on each function and macro, see the Reference Section. Table_2-1_I/O_Functions_and_Macros_________________________ Function or Macro____________Description_______________________________ UNIX_I/O-Opening_and_Closing_Files_________________________ close Closes the file associated with a file descriptor. creat Creates a new file. dup, dup2 Allocates a new descriptor that refers to a file specified by a file descriptor returned by open, creat, or pipe. open Opens a file and positions it at its beginning. ___________________________________________________________ UNIX_I/O-Reading_from_Files________________________________ read Reads bytes from a file and places them in a buffer. ___________________________________________________________ UNIX_I/O-Writing_to_Files__________________________________ write Writes a specified number of bytes from a buffer to a file. (continued on next page) Understanding Input and Output 2-1 Table_2-1_(Cont.)_I/O_Functions_and_Macros_________________ Function or Macro____________Description_______________________________ UNIX_I/O-Maneuvering_in_Files______________________________ lseek Positions a stream file to an arbitrary byte position and returns the new position as an int. ___________________________________________________________ UNIX_I/O-Additional_Standard_I/O_Functions_and_Macros______ fstat, stat Accesses information about the file descriptor or the file specification. fsync Writes to disk any buffered information for the specified file. getname Returns the file specification associated with a file descriptor. isapipe Returns 1 if the file descriptor is associated with a pipe and 0 if it is not. isatty Returns 1 if the specified file descriptor is associated with a terminal and 0 if it is not. lwait Waits for completion of pending asynchronous I/O. ttyname Returns a pointer to the null-terminated name of the terminal device associated with file descriptor 0, the default input device. (continued on next page) 2-2 Understanding Input and Output Table_2-1_(Cont.)_I/O_Functions_and_Macros_________________ Function or ___________________________________________________________ Standard_I/O-Opening_and_Closing_Files_____________________ fclose Closes a function by flushing any buffers associated with the file control block, and freeing the file control block and buffers previously associated with the file pointer. fdopen Associates a file pointer with a file descriptor returned by an open, creat, dup, dup2, or pipe function. fopen Opens a file by returning the address of a FILE structure. freopen Substitutes the file, named by a file specification, for the open file addressed by a file pointer. ___________________________________________________________ Standard_I/O-Reading_from_Files____________________________ fgetc, getc, Returns characters from a specified file. fgetwc, getw, getwc fgets, fgetws Reads a line from a specified file and stores the string in an argument. fread Reads a specified number of items from a file. fscanf, fwscanf Performs formatted input from a specified file. sscanf, swscanf Performs formatted input from a character string in memory. ungetc, ungetwc Pushes back a character into the input stream and leaves the stream positioned before the character. (continued on next page) Understanding Input and Output 2-3 Table_2-1_(Cont.)_I/O_Functions_and_Macros_________________ Function or Macro____________Description_______________________________ Standard_I/O-Writing_to_Files______________________________ fprintf, Performs formatted output to a specified fwprintf, file. vfprintf, vfwprintf fputc, putc, Writes characters to a specified file. putw, putwc, fputwc fputs, fputws Writes a character string to a file without copying the string's null terminator. fwrite Writes a specified number of items to a file. sprintf, Performs formatted output to a string in swprintf, memory. vsprintf, vswprintf ___________________________________________________________ Standard_I/O-Maneuvering_in_Files__________________________ fflush Sends any buffered information for the specified file to RMS. fgetpos Stores the current value of the file position indicator for the stream. fsetpos Sets the file position indicator for the stream according to the value of the object pointed to. fseek Positions the file to the specified byte offset in the file. ftell Returns the current byte offset to the specified stream file. rewind Sets the file to its beginning. (continued on next page) 2-4 Understanding Input and Output Table_2-1_(Cont.)_I/O_Functions_and_Macros_________________ Function or Macro____________Description_______________________________ Standard_I/O-Additional_Standard_I/O_Functions_and_Macros__ access Checks a file to see whether a specified access mode is allowed. clearerr Resets the error and end-of-file indications for a file. feof Tests a file to see if the end-of-file has been reached. ferror Returns a nonzero integer if an error has occurred while reading or writing a file. fgetname Returns the file specification associated with a file pointer. fileno Returns an integer file descriptor that identifies the specified file. ftruncate Truncates a file at the specified position. fwait Waits for completion of pending asynchcronous I/O. fwide Sets the orientation a stream. mktemp Creates a unique file name from a template. remove, delete Deletes a file. rename Gives a new name to an existing file. setbuf, setvbuf Associates a buffer with an input or output file. tmpfile Creates a temporary file that is opened for update. tmpnam Creates a character string that can be used in place of the file-name argument in other function calls. (continued on next page) Understanding Input and Output 2-5 Table_2-1_(Cont.)_I/O_Functions_and_Macros_________________ Function or Macro____________Description_______________________________ Terminal_I/O-Reading_from_Files____________________________ getchar, Reads a single character from the standard getwchar input (stdin). gets Reads a line from the standard input (stdin). scanf, wscanf Performs formatted input from the standard input. ___________________________________________________________ Terminal_I/O-Writing_to_Files______________________________ printf, Performs formatted output to the standard wprintf, output (stdout). vprintf, vwprintf putchar, Writes a single character to the standard putwchar output and returns the character. puts Writes a character string to the standard _________________output_followed_by_a_new-line_character.__ 2.1 Using RMS from RTL Routines When you create a file using the Compaq C RTL I/O functions and macros, you can supply values for many RMS file attributes, including: o Allocation quantity o Block size o Default file extension o Default file name o File access context options o File-processing options o File-sharing options o Multiblock count o Multibuffer count 2-6 Understanding Input and Output o Maximum record size o Record attributes o Record format o Record-processing options See the description of the creat function in the Reference Section for information on these values. Other functions that allow you to set these values include open, fopen, and freopen. For more information about RMS, see the Compaq C User's Guide for OpenVMS Systems. 2.2 UNIX I/O and Standard I/O UNIX I/O functions are UNIX system services, now standardized by ISO POSIX-1 (the ISO Portable Operating System Interface). UNIX I/O functions use file descriptors to access files. A file descriptor is an integer that identifies the file. A file descriptor is declared in the following way, where file_desc is the name of the file descriptor: int file_desc; UNIX I/O functions, such as creat, associate the file descriptor with a file. Consider the following example: file_desc1 = creat("INFILE.DAT", 0, "rat=cr", "rfm=var"); This statement creates the file, INFILE.DAT, with file access mode 0, carriage-return control, variable-length records, and it associates the variable file_desc1 with the file. When the file is accessed for other operations, such as reading or writing, the file descriptor is used to refer to the file. For example: write(file_desc1, buffer, sizeof(buffer)); This statement writes the contents of the buffer to INFILE.DAT. Understanding Input and Output 2-7 There may be circumstances when you should use UNIX I/O functions and macros instead of the Standard I/O functions and macros. For a detailed discussion of both forms of I/O and how they manipulate the RMS file formats, see Chapter 1. Standard I/O functions are specified by the ANSI C Standard. Standard I/O functions add buffering to the features of UNIX I/O and use file pointers to access files. A file pointer is an object of type FILE *, which is a typedef defined in the header file as follows: typedef struct _iobuf *FILE; The _iobuf identifier is also defined in . To declare a file pointer, use the following: FILE *file_ptr; You use the Standard I/O fopen function to create or open an existing file. For example: #include main() { FILE *outfile; outfile = fopen("DISKFILE.DAT", "w+"); . . . } Here, the file DISKFILE.DAT is opened for write-update access. The Compaq C RTL provides the following functions for converting between file descriptors and file pointers: o fileno-returns the file descriptor associated with the specified file pointer. o fdopen-associates a file pointer with a file descriptor returned by an open, creat, dup, dup2, or pipe function. 2-8 Understanding Input and Output 2.3 Wide-Character Versus Byte I/O Functions The wide-character I/O functions provide operations analogous to most of the byte I/O functions, except that the fundamental units internal to the wide-character functions are wide characters. However, the external representation (in files) is a sequence of multibyte characters, not wide characters. For the wide-character formatted input and output functions: o The wide-character formatted input functions (such as fwscanf) always read a sequence of multibyte characters from files, regardless of the specified directive and, before any further processing, convert this sequence to a sequence of wide characters. o The wide-character formatted output functions (such as fwprintf) write wide characters to output files by first converting wide-character argument types to a sequence of multibyte characters, then calling the underlying operating system output primitives. Byte I/O functions cannot handle state-dependent encodings. Wide-character I/O functions can. They accomplish this by associating each wide-character stream with a conversion- state object of type mbstate_t. The wide-character I/O functions are: fgetwc fputwc fwscanf fwprintf ungetwc fgetws fputws wscanf wprintf getwc putwc vfwprintf getwchar putwchar vwprintf The byte I/O functions are: fgetc fputc fscanf fprintf ungetc fgets fputs scanf printf fread getc putc vfprinf fwrite gets puts vprintf getchar putchar The wide-character input functions read multibyte characters from the stream and convert them to wide characters as if they were read by successive calls to the fgetwc function. Each conversion occurs as a call were made Understanding Input and Output 2-9 to the mbrtowc function with the conversion state described by the stream's own mbstate_t object. The wide-character output functions convert wide characters to multibyte characters and write them to the stream as if they were written by successive calls to the fputwc function. Each conversion occurs as if a call were made to the wcrtomb function, with the conversion state described by the I/O stream's own mbstate_t object. If a wide-character I/O function encounters an invalid multibyte character, the function sets errno to the value EILSEQ. 2.4 Conversion Specifications Several of the Standard I/O functions (including the Terminal I/O functions) use conversion specifications to specify data formats for I/O. These functions are the formatted-input and formatted-output functions. Consider the following example: int x = 5.0; FILE *outfile; . . . fprintf(outfile, "The answer is %d.\n", x); The decimal value of the variable x replaces the conversion specification %d in the string to be written to the file associated with the identifier outfile. Each conversion specification begins with a percent sign (%) and ends with a conversion specifier, which is a character that specifies the type of conversion to be performed. Optional characters can appear between the percent sign and the conversion specifier. For the wide-character formatted I/O functions, the conversion specification is a string of wide characters. For the byte I/O equivalent functions, it is a string of bytes. Sections 2.4.1 and 2.4.2 describe these optional characters and conversion specifiers. 2-10 Understanding Input and Output 2.4.1 Converting Input Information The format specification string for the input of information can include three kinds of items: o White-space characters (spaces, tabs, and new-line characters), which match optional white-space characters in the input field. o Ordinary characters (not %), which must match the next nonwhite-space character in the input. o Conversion specifications, which govern the conversion of the characters in an input field and their assignment to an object indicated by a corresponding input pointer. Each input pointer is an address expression indicating an object whose type matches that of a corresponding conversion specification. Conversion specifications form part of the format string. The indicated object is the target that receives the input value. There must be as many input pointers as there are conversion specifications, and the addressed objects must match the types of the conversion specifications. A conversion specification consists of the following characters, in the order listed: o A percent character (%) or the sequence %n$ (where n is an integer), The sequence %n$ denotes that the conversion is applied to the nth input pointer listed, where n is a decimal integer between [1, NL_ARGMAX] (see the header file). For example, a conversion specification beginning %5$ means that the conversion will be applied to the 5th input pointer listed after the format specification. The sequence %$ is invalid. If the conversion specification does not begin with the sequence %n$, the conversion specification is matched to its input pointer in left-to-right order. You should only use one type of conversion specification (% or %n$) in a format specification. o One or more optional characters (described in Table 2-2). o A conversion specifier (described in Table 2-3). Understanding Input and Output 2-11 Table 2-2 shows the characters you can use between the percent sign (%) (or the sequence %n$), and the conversion specifier. These characters are optional but, if specified, must occur in the order shown in Table 2-2. Table 2-2 Optional Characters Between % (or %n$) and the __________Input_Conversion_Specifier_______________________ Character___Meaning________________________________________ * An assignment-suppressing character. field A nonzero decimal integer that specifies the width maximum field width. For the wide-character input functions, the field width is measured in wide characters. For the byte input functions, the field width is measured in bytes, unless the directive is one of the following: %lc, %ls, %C, %S, %[ In these cases, the field width is measured in multibyte character units. (continued on next page) 2-12 Understanding Input and Output Table 2-2 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Input_Conversion_Specifier_______ Character___Meaning________________________________________ h, l, or L Precede a conversion specifier of d, i, or n (or ll) with an h if the corresponding argument is a pointer to short int rather than a pointer to int; with an l (lowercase ell) if it is a pointer to long int; or, for OpenVMS Alpha systems only, with an L or ll (two lowercase ells) if it is a pointer to __int64. Precede a conversion specifier of o, u, or x with an h if the corresponding argument is a pointer to unsigned short int rather than a pointer to unsigned int; with an l if it is a pointer to unsigned long int; or, for OpenVMS Alpha systems only, with an L or ll if it is a pointer to unsigned __int64. Precede a conversion specifier of c, s, or [ with an l (lower ell) if the corresponding argument is a pointer to a wchar_t. Finally, precede a conversion specifier of e, f, or g with an l (lowercase ell) if the corresponding argument is a pointer to double rather than a pointer to float, or with an L if it is a pointer to long double. If an h, l, L, or ll appears with any other conversion specifier, the behavior is ____________undefined._____________________________________ Table 2-3 describes the conversion specifiers for formatted input. Understanding Input and Output 2-13 Table_2-3_Conversion_Specifiers_for_Formatted_Input________ Input SpecifieType[1]______Description___________________________ d Expects a decimal integer in the input whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument must be a pointer to int. i Expects an integer whose type is determined by the leading input characters. A leading 0 is equated to octal, a leading 0X or 0x is equated to hexadecimal, and all other forms are equated to decimal. The corresponding argument must be a pointer to int. o Expects an octal integer in the input (with or without a leading 0). The corresponding argument must be a pointer to int. u Expects a decimal integer in the input whose format is the same as expected for the subject sequence of the strtoul function with the value 10 for the base argument. x Expects a hexadecimal integer in the input (with or without a leading 0x). The corresponding argument must be a pointer to unsigned int. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-14 Understanding Input and Output Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ c Byte Expects a single byte in the input. The corresponding argument must be a pointer to char. If a field width precedes the c conversion specifier, the number of characters specified by the field width is read. In this case, the corresponding argument must be a pointer to an array of char. If the optional character l (lowercase ell) precedes this conversion specifier, then the specifier expects a multibyte character in the input which is converted into a wide- character code. The corresponding argument must be a pointer to type wchar_t. If a field width also precedes the c conversion specifier, the number of characters specified by the field width is read. In this case, the corresponding argument must be a pointer to an array _____________________of_wchar_t.___________________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-15 Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ Wide- Expects a sequence of the number character of characters specified in the optional field width; this is 1 if not specified. If no l (lowercase ell) precedes the c specifier, then the corresponding argument must be a pointer to an array of char. If an l (lowercase ell) precedes the c specifier, the corresponding argument must be a pointer to an array of wchar_t. C Byte The specifier expects a multibyte character in the input, which is converted into a wide-character code. The corresponding argument must be a pointer to type wchar_t. If a field width also precedes the C conversion specifier, the number of characters specified by the field width is read. In this case, the corresponding argument must be a pointer to an array of wchar_t. Wide- Expects a sequence of the number character of characters specified in the optional field width; this is 1 if not specified. The corresponding argument must be a pointer to an array of wchar_t. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-16 Understanding Input and Output Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ s Byte Expects a sequences of bytes in the input. The corresponding argument must be a pointer to an array of characters that is large enough to contain the sequence and a terminating null character (\0) that is automatically added. The input field is terminated by a space, tab, or new-line character. If the optional character l (ell) precedes this conversion specifier, the specifier expects a sequence of multibyte characters in the input, which are converted to wide- character codes. The corresponding argument must be a pointer to an array of wide characters (type wchar_ t) that is large enough to contain the sequence plus the terminating null wide-character code that is automatically added. The input field is terminated by a space, tab, or _____________________new-line_character.___________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-17 Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ Wide- Expects (conceptually) a sequence character of nonwhite-space characters in the input. If no l (lowercase ell) precedes the s specifier, then the corresponding argument must be a pointer to an array of char large enough to contain the sequence plus the terminating null byte that is automatically added. If an l (lowercase ell) precedes the s specifier, then the corresponding argument must be a pointer to an array of wchar_t large enough to contain the sequence plus the terminating null wide character that is automatically added. S Byte The specifier expects a sequence of multibyte characters in the input, which are converted to wide-character codes. The corresponding argument must be a pointer to an array of wide characters (type wchar_t) that is large enough to contain the sequence plus a terminating null wide-character code which is added automatically. The input field is terminated by a space, tab, or new-line character. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-18 Understanding Input and Output Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ Wide- Expects a sequence of nonwhite- character space characters in the input. The corresponding argument must be a pointer to an array of wchar_t large enough to contain the sequence plus the terminating null wide character that is automatically added. e, f, Expects a floating-point number in g the input. The corresponding argument must be a pointer to float. The input format for floating-point numbers is: []nnn[radix][ddd][{E|e}[]nn]. The n's and d's are decimal digits (as many as indicated by the field width minus the signs and the letter E). The radix character is defined in the current locale. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-19 Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ [ . . . Expects a nonempty sequence of ] characters that is not delimited by a white-space character. The brackets enclose a set of characters (the scanset) expected in the input sequence. Any character in the input sequence that does not match a character in the scanset terminates the character sequence. All characters between the brackets comprise the scanset, unless the first character after the left bracket is a circumflex (^). In this case, the scanset contains all characters other than those that appear between the circumflex and the right bracket. Any character that does appear between the circumflex and the right bracket will terminate the input character sequence. If the conversion specifier begins with [] or [^], the right bracket character is in the scanset and the next right bracket character is the matching right bracket that ends the specification; otherwise, the first right bracket character ends the _____________________specification.________________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) 2-20 Understanding Input and Output Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ Byte If an l (lowercase ell) does not precede the [ specifier, then the characters in the scanset must be single-byte characters only. In this case, the corresponding argument must be a pointer to an array of char large enough to accept the sequence and the terminating null byte which is automatically added. If an l (lowercase ell) does precede the [ specifier, the characters in the input sequence are considered to be multibyte characters, which are then converted to a wide-character sequence for further processing. If character ranges are specified in the scanset, then the processing is done according to the LC_COLLATE category of the current program's locale. In this case, the corresponding argument must be a pointer to an array of wchar_t large enough to accept the sequence and the terminating null wide character which is automatically _____________________added.________________________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-21 Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ Wide- If no l (lowercase ell) precedes the [ character conversion specifier, then processing is the same as described for the Byte-input type of the %l[ specifier, except that the corresponding argument must be an array of char large enough to accept the multibyte sequence plus the terminating null byte that is automatically added. If an l (lowercase ell) precedes the [ conversion specifier, then processing is the same as the preceding paragraph except that the corresponding argument must be an array of wchar_t large enough to accept the wide-character sequence plus the terminating null wide character that is automatically added. p Requires an argument that is a pointer to void. The input value is interpreted as a hexadecimal value. n No input is consumed. The corresponding argument is a pointer to an integer. The integer is assigned the number of characters read from the input stream so far by this call to the formatted input function. Execution of a %n directive does not increment the assignment count returned when the formatted input function completes execution. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-22 Understanding Input and Output Table_2-3_(Cont.)_Conversion_Specifiers_for_Formatted_Input Input SpecifieType[1]______Description___________________________ % Matches a single percent symbol. No conversion or assignment takes place. The complete conversion specification [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. ___________________________________________________________ Remarks o You can change the delimiters of the input field with the bracket ([ ]) conversion specification. Otherwise, an input field is defined as a string of nonwhite-space characters. It extends either to the next white-space character or until the field width, if specified, is exhausted. The function reads across line and record boundaries, since the new-line character is a white- space character. o A call to one of the input conversion functions resumes searching immediately after the last character processed by a previous call. o If the assignment-suppression character (*) appears in the format specification, no assignment is made. The corresponding input field is interpreted and then skipped. o The arguments must be pointers or other address-valued expressions, since Compaq C permits only calls by value. To read a number in decimal format and assign its value to n, you must use the following form: scanf("%d", &n) You cannot use the following form: scanf("%d", n) Understanding Input and Output 2-23 o White space in a format specification matches optional white space in the input field. Consider the following format specification: field = %x This format specification matches the following forms: field = 5218 field=5218 field= 5218 field =5218 These forms do not match the following example: fiel d=5218 2.4.2 Converting Output Information The format specification string for the output of information can contain: o Ordinary characters, which are copied to the output. o Conversion specifications, each of which causes the conversion of a corresponding output source to a character string in a particular format Conversion specifications are matched to output sources in left- to-right order. A conversion specification consists of the following, in the order listed: o A percent character (%) or the sequence %n$. The sequence %n$ denotes that the conversion is applied to the nth output source listed, where n is a decimal integer between [1, NL_ARGMAX] (see the header file). For example, a conversion specification beginning %5$ means that the conversion will be applied to the 5th output source listed after the format specification. If the conversion specification does not begin with the sequence %n$, the conversion specification is matched to its output source in left-to-right order. You should only use one type of conversion specification (% or %n$) in a format specification. 2-24 Understanding Input and Output o One or more optional characters (described in Table 2-4). o A conversion specifier (described in Table 2-5) concludes the conversion specification. For examples of conversion specifications, see the sample programs in Section 2.6. Table 2-4 shows the characters you can use between the percent sign (%) (or the sequence %n$) and the conversion specifier. These characters are optional, but if specified, they must occur in the order shown in Table 2-4. Table 2-4 Optional Characters Between % (or %n$) and the __________Output_Conversion_Specifier______________________ Character__Meaning_________________________________________ (continued on next page) Understanding Input and Output 2-25 Table 2-4 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Output_Conversion_Specifier______ Character__Meaning_________________________________________ flags You can use the following flag characters, alone or in any combined order, to modify the conversion specification: ' Requests that a numeric conversion is (single formatted with the thousands separator quote) character. Only the numbers to the left of the radix character are formatted with the separator character. The character used as a separator and the positioning of the separators are defined in the program's current locale. - (hy- Left-justifies the converted output phen) source in its field. + Requests that an explicit sign be present on a signed conversion. If this flag is not specified, the result of a signed conversion begins with a sign only when a negative value is converted. space Prefixes a space to the result of a signed conversion, if the first character of the conversion is not a sign, or if the conversion results in no characters. If you specify both the space and the + flag, the space flag is ignored. (continued on next page) 2-26 Understanding Input and Output Table 2-4 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Output_Conversion_Specifier______ Character__Meaning_________________________________________ # Requests an alternate conversion format. Depending on the conversion specified, different actions will occur. For the o (octal) conversion, the precision is increased to force the first digit to be a zero. For the x (or X) conversion, a nonzero result is prefixed with 0x (or 0X). For e, E, f, g, and G conversions, the result contains a decimal point even at the end of an integer value. For g and G conversions, trailing zeros are not trimmed. For other conversions, the effect of # is undefined. 0 Uses zeros rather than spaces to pad the field width for d, i, o, u, x, X, e, E, f, g, and G conversions. If both the 0 and the - flags are specified, then the 0 flag is ignored. For d, i, o, u, x, and X conversions, if a precision is specified, the 0 flag is ignored. For other conversions, the behavior of the 0 flag is undefined. (continued on next page) Understanding Input and Output 2-27 Table 2-4 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Output_Conversion_Specifier______ Character__Meaning_________________________________________ field The minimum field width can be designated by width a decimal integer constant, or by an output source. To specify an output source, use an asterisk (*) or the sequence *n$, where n refers to the nth output source listed after the format specification. The minimum field width is considered after the conversion is done according to the all other components of the format directive. This component affects padding the result of the conversion as follows: If the result of the conversion is wider than the minimum field, write it out. If the result of the conversion is narrower than the minimum width, pad it to make up the field width. Pad with spaces by default. Pad with zeros if the 0 flag is specified; this does not mean that the width is an octal number. Padding is on the left by default, and on the right if a minus sign is specified. For the wide-character output functions, the field width is measured in wide characters; for the byte output functions, it is measured in bytes. . Separates the field width from the precision. (period) (continued on next page) 2-28 Understanding Input and Output Table 2-4 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Output_Conversion_Specifier______ Character__Meaning_________________________________________ precision The precision defines any of the following: o Minimum number of digits to appear for d, i, o, u, x, and X conversions o Number of digits to appear after the decimal- point character for e, E, and f conversions o Maximum number of significant digits for g and G conversions o Maximum number of characters to be written from a string in an s or S conversion If a precision appears with any other conversion specifier, the behavior is undefined. Precision can be designated by a decimal integer constant, or by an output source. To specify an output source, use an asterisk (*) or the sequence *n$, where n refers to the nth output source listed after the format specification. If only the period is specified, the precision is taken as 0. (continued on next page) Understanding Input and Output 2-29 Table 2-4 (Cont.) Optional Characters Between % (or %n$) __________________and_the_Output_Conversion_Specifier______ Character__Meaning_________________________________________ h, l, or An h specifies that a following d, i, o, u, x, L (or ll) or X conversion specifier applies to a short int or unsigned short int argument; an h can also specify that a following n conversion specifier applies to a pointer to a short int argument. An l (lowercase ell) specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; an l can also specify that a following n conversion specifier applies to a pointer to a long int argument. On OpenVMS Alpha systems, an L or ll (two lowercase ells) specifies that a following d, i, o, u, x, or X conversion specifier applies to an __int64 or unsigned __int64 argument. (Alpha only) An L specifies that a following e, E, f, g, or G conversion specifier applies to a long double argument. An l specifies that a following c or s conversion specifier applies to a wchar_t argument. If an h, l, or L appears with any other conversion specifier, the behavior is undefined. On OpenVMS VAX and OpenVMS Alpha systems, Compaq C int values are equivalent to long ___________values._________________________________________ Table 2-5 decribes the conversion specifiers for formatted output. 2-30 Understanding Input and Output Table_2-5_Conversion_Specifiers_for_Formatted_Output_______ Output SpecifType[1]_____Description______________________________ d, i Converts an int argument to signed decimal format. o Converts an unsigned int argument to unsigned octal format. u Converts an unsigned int argument to unsigned decimal format (giving a number in the range 0 to 4,294,967,295). x, X Converts an unsigned int argument to unsigned hexadecimal format (with or without a leading 0x). The letters abcdef are used for x conversion, and the letters ABCDEF are used for X conversion. f Converts a float or double argument to the format [-]mmm.nnnnnn. The number of n's is equal to the precision specification: o If no precision is specified, the default is 6. o If the precision is 0 and the # flag is specified, the decimal point appears but no n's appear. o If the precision is 0 and the # flag is not specified, the decimal point also does not appear. o If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-31 Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ e, E Converts a float or double argument to the format [-]m.nnnnnnExx. The number of n's is specified by the precision. If no precision is specified, the default is 6. If the precision is explicitly 0 and the # flag is specified, the decimal point appears but no n's appear. If the precision is explicitly 0 and the # flag is not specified, the decimal point also does not appear. An 'e' is printed for e conversion; an 'E' is printed for E conversion. The exponent always contains at least two digits. If the value is 0, the exponent is 0. g, G Converts a float or double argument to format f or e (or E if the G conversion specifier is used), with the precision specifying the number of significant digits. If the precision is 0, it is taken as 1. The format used depends on the value of the argument: format e (or E) is used only if the exponent resulting from such a conversion is less than -4, or is greater than or equal to the precision; otherwise, format f is used. Trailing zeros are suppressed in the fractional portion of the result. A decimal point appears only if it is followed by a digit. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-32 Understanding Input and Output Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ c Byte Converts an int argument to an unsigned char, and writes the resulting byte. If the optional character l (lowercase ell) precedes this conversion specifier, then the specifier converts a wchar_ t argument to an array of bytes representing the character, and writes the resulting character. If the field width is specified and the resulting character occupies fewer bytes than the field width, it will be padded to the given width with space characters. If the precision is specified, the behavior is undefined. Wide- If an l (lowercase ell) does not precede character the c specifier, then the int argument is converted to a wide character as if by calling btowc, and the resulting character is written. If an l (lowercase ell) precedes the c specifier, then the specifier converts a wchar_t argument to an array of bytes representing the character, and writes the resulting character. If the field width is specified and the resulting character occupies fewer characters than the field width, it will be padded to the given width with space characters. If the precision is specified, the behavior is undefined. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-33 Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ C Byte Converts a wchar_t argument to an array of bytes representing the character, and writes the resulting character. If the field width is specified and the resulting character occupies fewer bytes than the field width, it will be padded to the given width with space characters. If the precision is specified, the behavior is undefined. Wide- Converts a wchar_t argument to an array character of bytes representing the character, and writes the resulting character. If the field width is specified and the resulting character occupies fewer wide characters than the field width, it will be padded to the given width with space characters. If the precision is specified, the behavior is undefined. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) 2-34 Understanding Input and Output Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ s Byte Requires an argument that is a pointer to an array of characters of type char. The argument is used to write characters until a null character is encountered or until the number of characters indicated by the precision specification is exhausted. If the precision specification is 0 or omitted, all characters up to a null are output. If the optional character l (lowercase ell) precedes this conversion specifier, then the specifier converts an array of wide-character codes to multibyte characters, and writes the multibyte characters. Requires an argument that is a pointer to an array of wide characters of type wchar_t. Characters are written until a null wide character is encountered or until the number of bytes indicated by the precision specification is exhausted. If the precision specification is omitted or is greater than the size of the array of converted bytes, the array of wide characters must be terminated by a null __________________wide_character.__________________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-35 Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ Wide- If an l (lowercase ell) does not character precede the s specifier, then the specifier converts an array of multibyte characters, as if by calling mbrtowc for each multibyte character, and writes the resulting characters until a null wide character is encountered or the number of wide characters indicated by the precision specification is exhausted. If the precision specification is omitted or is greater than the size of the array of converted characters, the converted array must be terminated by a null wide character. If an l precedes this conversion specifier, then the argument is a pointer to an array of wchar_t. Characters from this array are written until a null wide character is encountered or the number of wide characters indicated by the precision specification is exhausted. If the precision specification is omitted or is greater than the size of the array, the array must be terminated by a null __________________wide_character.__________________________ [1]Either Byte or Wide-character. Where neither is shown for a given specifier, the specifier description applies to both. (continued on next page) 2-36 Understanding Input and Output Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ S Byte Converts an array of wide-character codes to multibyte characters, and writes the multibyte characters. Requires an argument that is a pointer to an array of wide characters of type wchar_t. Characters are written until a null wide character is encountered or until the number of bytes indicated by the precision specification is exhausted. If the precision specification is omitted or is greater than the size of the array of converted bytes, the array of wide characters must be terminated by a null wide character. Wide- The argument is a pointer to an array character of wchar_t. Characters from this array are written until a null wide character is encountered or the number of wide characters indicated by the precision specification is exhausted. If the precision specification is omitted or is greater than the size of the array, the array must be terminated by a null wide character. p Requires an argument that is a pointer to void. The value of the pointer is output as a hexadecimal number. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. (continued on next page) Understanding Input and Output 2-37 Table 2-5 (Cont.) Conversion Specifiers for Formatted __________________Output___________________________________ Output SpecifType[1]_____Description______________________________ n Requires an argument that is a pointer to an integer. The integer is assigned the number of characters written to the output stream so far by this call to the formatted output function. No argument is converted. % Writes out the percent symbol. No conversion is performed. The complete conversion specification would be %%. [1]Either_Byte_or_Wide-character._Where_neither_is_shown___ for a given specifier, the specifier description applies to both. ___________________________________________________________ 2.5 Terminal I/O Compaq C defines three file pointers that allow you to perform I/O to and from the logical devices usually associated with your terminal (for interactive jobs) or a batch stream (for batch jobs). In the OpenVMS environment, the three permanent process files SYS$INPUT, SYS$OUTPUT, and SYS$ERROR perform the same functions for both interactive and batch jobs. Terminal I/O refers to both terminal and batch stream I/O. The file pointers stdin, stdout, and stderr are defined when you include the header file using the #include preprocessor directive. The stdin file pointer is associated with the terminal to perform input. This file is equivalent to SYS$INPUT. The stdout file pointer is associated with the terminal to perform output. This file is equivalent to SYS$OUTPUT. The stderr file pointer is associated with the terminal to report run-time errors. This file is equivalent to SYS$ERROR. 2-38 Understanding Input and Output There are three file descriptors that refer to the terminal. The file descriptor 0 is equivalent to SYS$INPUT, 1 is equivalent to SYS$OUTPUT, and 2 is equivalent to SYS$ERROR. When performing I/O at the terminal, you can use Standard I/O functions and macros (specifying the pointers stdin, stdout, or stderr as arguments), you can use UNIX I/O functions (giving the corresponding file descriptor as an argument), or you can use the Terminal I/O functions and macros. There is no functional advantage to using one type of I/O over another; the Terminal I/O functions might save keystrokes since there are no arguments. 2.6 Program Examples This section gives some program examples that show how the I/O functions can be used in applications. Example 2-1 shows the printf function. Example 2-1 Output of the Conversion Specifications /* CHAP_2_OUT_CONV.C */ /* This program uses the printf function to print the */ /* various conversion specifications and their affect */ /* on the output. */ /* Include the proper header files in case printf has */ /* to return EOF. */ #include #include #include #define WIDE_STR_SIZE 20 (continued on next page) Understanding Input and Output 2-39 Example 2-1 (Cont.) Output of the Conversion Specifications main() { double val = 123345.5; char c = 'C'; int i = -1500000000; char *s = "thomasina"; wchar_t wc; wchar_t ws[WIDE_STR_SIZE]; /* Produce a wide character and a wide character string */ if (mbtowc(&wc, "W", 1) == -1) { perror("mbtowc"); exit(EXIT_FAILURE); } if (mbstowcs(ws, "THOMASINA", WIDE_STR_SIZE) == -1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Print the specification code, a colon, two tabs, and the */ /* formatted output value delimited by the angle bracket */ /* characters (<>). */ printf("%%9.4f:\t\t<%9.4f>\n", val); printf("%%9f:\t\t<%9f>\n", val); printf("%%9.0f:\t\t<%9.0f>\n", val); printf("%%-9.0f:\t\t<%-9.0f>\n\n", val); printf("%%11.6e:\t\t<%11.6e>\n", val); printf("%%11e:\t\t<%11e>\n", val); printf("%%11.0e:\t\t<%11.0e>\n", val); printf("%%-11.0e:\t\t<%-11.0e>\n\n", val); printf("%%11g:\t\t<%11g>\n", val); printf("%%9g:\t\t<%9g>\n\n", val); printf("%%d:\t\t<%d>\n", c); printf("%%c:\t\t<%c>\n", c); printf("%%o:\t\t<%o>\n", c); printf("%%x:\t\t<%x>\n\n", c); (continued on next page) 2-40 Understanding Input and Output Example 2-1 (Cont.) Output of the Conversion Specifications printf("%%d:\t\t<%d>\n", i); printf("%%u:\t\t<%u>\n", i); printf("%%x:\t\t<%x>\n\n", i); printf("%%s:\t\t<%s>\n", s); printf("%%-9.6s:\t\t<%-9.6s>\n", s); printf("%%-*.*s:\t\t<%-*.*s>\n", 9, 5, s); printf("%%6.0s:\t\t<%6.0s>\n\n", s); printf("%%C:\t\t<%C>\n", wc); printf("%%S:\t\t<%S>\n", ws); printf("%%-9.6S:\t\t<%-9.6S>\n", ws); printf("%%-*.*S:\t\t<%-*.*S>\n", 9, 5, ws); printf("%%6.0S:\t\t<%6.0S>\n\n", ws); } Running Example 2-1 produces the following output: $ RUN EXAMPLE %9.4f: <123345.5000> %9f: <123345.500000> %9.0f: < 123346> %-9.0f: <123346 > %11.6e: <1.233455e+05> %11e: <1.233455e+05> %11.0e: < 1e+05> %-11.0e: <1e+05 > %11g: < 123346> %9g: < 123346> %d: <67> %c: %o: <103> %x: <43> %d: <-1500000000> %u: <2794967296> %x: %s: %-9.6s: %-*.*s: %6.0s: < > Understanding Input and Output 2-41 %C: %S: %-9.6S: %-*.*S: %6.0S: < > $ Example 2-2 shows the use of the fopen, ftell, sprintf, fputs, fseek, fgets, and fclose functions. Example 2-2 Using the Standard I/O Functions /* CHAP_2_STDIO.C */ /* This program establishes a file pointer, writes lines from */ /* a buffer to the file, moves the file pointer to the second */ /* record, copies the record to the buffer, and then prints */ /* the buffer to the screen. */ #include #include main() { char buffer[32]; int i, pos; FILE *fptr; /* Set file pointer. */ fptr = fopen("data.dat", "w+"); if (fptr == NULL) { perror("fopen"); exit(EXIT_FAILURE); } for (i = 1; i < 5; i++) { if (i == 2) /* Get position of record 2. */ pos = ftell(fptr); /* Print a line to the buffer. */ sprintf(buffer, "test data line %d\n", i); /* Print buffer to the record. */ fputs(buffer, fptr); } (continued on next page) 2-42 Understanding Input and Output Example 2-2 (Cont.) Using the Standard I/O Functions /* Go to record number 2. */ if (fseek(fptr, pos, 0) < 0) { perror("fseek"); /* Exit on fseek error. */ exit(EXIT_FAILURE); } /* Read record 2 in the buffer. */ if (fgets(buffer, 32, fptr) == NULL) { perror("fgets"); /* Exit on fgets error. */ exit(EXIT_FAILURE); } /* Print the buffer. */ printf("Data in record 2 is: %s", buffer); fclose(fptr); /* Close the file. */ } Running Example 2-2 produces the following result: $ RUN EXAMPLE Data in record 2 is: test data line 2 The output to DATA.DAT from Example 2-2 is: test data line 1 test data line 2 test data line 3 test data line 4 Example 2-3 Using Wide Character I/O Functions /* CHAP_2_WC_IO.C */ /* This program establishes a file pointer, writes lines from */ /* a buffer to the file using wide-character codes, moves the */ /* file pointer to the second record, copies the record to the */ /* wide-character buffer, and then prints the buffer to the */ /* screen. */ #include #include #include (continued on next page) Understanding Input and Output 2-43 Example 2-3 (Cont.) Using Wide Character I/O Functions main() { char flat_buffer[32]; wchar_t wide_buffer[32]; wchar_t format[32]; int i, pos; FILE *fptr; /* Set file pointer. */ fptr = fopen("data.dat", "w+"); if (fptr == NULL) { perror("fopen"); exit(EXIT_FAILURE); } for (i = 1; i < 5; i++) { if (i == 2) /* Get position of record 2. */ pos = ftell(fptr); /* Print a line to the buffer. */ sprintf(flat_buffer, "test data line %d\n", i); if (mbstowcs(wide_buffer, flat_buffer, 32) == -1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Print buffer to the record. */ fputws(wide_buffer, fptr); } /* Go to record number 2. */ if (fseek(fptr, pos, 0) < 0) { perror("fseek"); /* Exit on fseek error. */ exit(EXIT_FAILURE); } (continued on next page) 2-44 Understanding Input and Output Example 2-3 (Cont.) Using Wide Character I/O Functions /* Put record 2 in the buffer. */ if (fgetws(wide_buffer, 32, fptr) == NULL) { perror("fgetws"); /* Exit on fgets error. */ exit(EXIT_FAILURE); } /* Print the buffer. */ printf("Data in record 2 is: %S", wide_buffer); fclose(fptr); /* Close the file. */ } Running Example 2-3 produces the following result: $ RUN EXAMPLE Data in record 2 is: test data line 2 The output to DATA.DAT from Example 2-3 is: test data line 1 test data line 2 test data line 3 test data line 4 Example 2-4 shows the use of both a file pointer and a file descriptor to access a single file. Example 2-4 I/O Using File Descriptors and Pointers /* CHAP_2_FILE_DIS_AND_POINTER.C */ /* The following example creates a file with variable-length */ /* records (rfm=var) and the carriage-return attribute (rat=cr).*/ /* */ /* The program uses creat to create and open the file, and */ /* fdopen to associate the file descriptor with a file pointer. */ /* After using the fdopen function, the file must be referenced */ /* using the Standard I/O functions. */ (continued on next page) Understanding Input and Output 2-45 Example 2-4 (Cont.) I/O Using File Descriptors and Pointers #include #include #include #include #define ERROR 0 #define ERROR1 -1 #define BUFFSIZE 132 main() { char buffer[BUFFSIZE]; int fildes; FILE *fp; if ((fildes = creat("data.dat", 0, "rat=cr", "rfm=var")) == ERROR1) { perror("DATA.DAT: creat() failed\n"); exit(EXIT_FAILURE); } if ((fp = fdopen(fildes, "w")) == NULL) { perror("DATA.DAT: fdopen() failed\n"); exit(EXIT_FAILURE); } while (fgets(buffer, BUFFSIZE, stdin) != NULL) if (fwrite(buffer, strlen(buffer), 1, fp) == ERROR) { perror("DATA.DAT: fwrite() failed\n"); exit(EXIT_FAILURE); } if (fclose(fp) == EOF) { perror("DATA.DAT: fclose() failed\n"); exit(EXIT_FAILURE); } } 2-46 Understanding Input and Output 3 _________________________________________________________________ Character, String, and Argument-List Functions Table 3-1 describes the character, string, and argument- list functions in the Compaq C Run-Time Library (RTL). Although further discussion follows, see the Reference Section for more detailed information on each function. Table_3-1_Character,_String,_and_Argument-List_Functions___ Function_________Description_______________________________ Character_Classification___________________________________ isalnum, Returns a nonzero integer if its argument iswalnum is one of the alphanumeric characters in the current locale. isalpha, Returns a nonzero integer if its argument iswalpha is one of the alphabetic characters in the current locale. isascii Returns a nonzero integer if its argument is any ASCII character. iscntrl, Returns a nonzero integer if its argument iswcntrl is a control character in the current locale. isdigit, Returns a nonzero integer if its argument iswdigit is a digit character in the current locale. isgraph, Returns a nonzero integer if its argument iswgraph is a graphic character in the current locale. (continued on next page) Character, String, and Argument-List Functions 3-1 Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ Function_________Description_______________________________ Character_Classification___________________________________ islower, Returns a nonzero integer if its argument iswlower is a lowercase character in the current locale. isprint, Returns a nonzero integer if its argument iswprint is a printing character in the current locale. ispunct, Returns a nonzero integer if its argument iswpunct is a punctuation character in the current locale. isspace, Returns a nonzero integer if its argument iswspace is a white space character in the current locale. isupper, Returns a nonzero integer if its argument iswupper is an uppercase character in the current locale. isxdigit, Returns a nonzero integer if its argument iswxdigit is a hexadecimal digit (0 to 9, A to F, or a to f). (continued on next page) 3-2 Character, String, and Argument-List Functions Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ ___________________________________________________________ Character_Conversion_______________________________________ btowc Converts a one-byte multibyte character to a wide character in the initial shift state. ecvt, fcvt, Converts an argument to a null-terminated gcvt string of ASCII digits and return the address of the string. index, rindex Searches for a character in a string. mblen, mbrlen Determines the number of bytes in a multibyte character. mbsinit Determines whether an mbstate_t object decribes an initial conversion state. mbstowcs Converts a sequence of multibyte characters into a sequence of corresponding codes. toascii Converts its argument, an 8-bit ASCII character, to a 7-bit ASCII character. tolower, _ Converts its argument, an uppercase tolower, character, to lowercase. towlower toupper, _ Converts its argument, a lowercase toupper, character, to uppercase. towupper towctrans Maps one wide character to another according to a specified mapping descriptor. (continued on next page) Character, String, and Argument-List Functions 3-3 Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ Function_________Description_______________________________ Character_Conversion_______________________________________ wctob Determines if a wide character corresponds to a single-byte multibyte character and returns its multibyte character representation. wcstombs Converts a sequence of wide-character codes corresponding to multibyte characters to a sequence of multibyte characters. wctomb Converts a wide character to its multibyte character representation. wctrans Returns the description of a mapping, corresponding to specified property, that can be later used in a call to towctrans. ___________________________________________________________ String_Manipulation________________________________________ atof Converts a given string to a double- precision number. atoi, atol Converts a given string of ASCII characters to the appropriate numeric values. atoll, atoq Converts a given string of ASCII (Alpha only) characters to an __int64. basename Returns the last component of a path name. dirname Reports the parent directory name of a file path name. strcat, Appends one string to the end of another strncat, string. wcscat, wcsncat strchr, Returns the address of the first or last strrchr, occurrence of a given character in a null- wcschr, wcsrchr terminated string. (continued on next page) 3-4 Character, String, and Argument-List Functions Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ Function_________Description_______________________________ String_Manipulation________________________________________ strcmp, Compares two character strings and strncmp, return a negative, zero, or positive strcoll, integer indicating that the values of wcscmp, the individual characters in the first wcsncmp, string are less than, equal to, or greater wcscoll than the values in the second string. strcpy, Copies all or part of one string into strncpy, another. wcscpy, wcsncpy strxfrm, Transforms a multibyte string to another wcsxfrm string ready for comparisons using the strcmp or wcscmp function. strcspn, Searches a string for a character that is wcscspn in a specified set of characters. strlen, wcslen Returns the length of a string of characters. The returned length does not include the terminating null character (\0). strpbrk, Searches a string for the occurrence of wcspbrk one of a specified set of characters. strspn, wcsspn Searches a string for the occurrence of a character that is not in a specified set of characters. strstr, wcswcs Searches a string for the first occurrence of a specified set of characters. strtod, wcstod Converts a given string to a double- precision number. strtok, wcstok Locates text tokens in a given string. (continued on next page) Character, String, and Argument-List Functions 3-5 Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ Function_________Description_______________________________ String_Manipulation________________________________________ strtol, wcstol Converts the initial portion of a string to a signed long integer. strtoll, strtoq Converts the initial portion of a string (Alpha only) to signed __int64. strtoul, Converts the initial portion of `a string wcstoul to an unsigned long integer. strtoull, Converts the initial portion of the string strtouq pointed to by the pointer to the character (Alpha only) string to an unsigned __int64. ___________________________________________________________ String_Handling-Accessing_Binary_Data______________________ bcmp Compares byte strings. bcopy Copies byte strings. bzero Copies nulls into byte strings. memchr, wmemchr Locates the first occurrence of the specified byte within the initial length of the object to be searched. memcmp, wmemcmp Compares two objects byte by byte. memcpy, Copies a specified number of bytes from memmove, one object to another. wmemcpy, wmemmove memset, wmemset Sets a specified number of bytes in a given object to a given value. (continued on next page) 3-6 Character, String, and Argument-List Functions Table 3-1 (Cont.) Character, String, and Argument-List __________________Functions________________________________ ___________________________________________________________ Argument-List Handling-Accessing a Variable-Length Argument List_______________________________________________________ va_arg Returns the next item in the argument list. va_count Returns the number of longwords (VAX only) or quadwords (VAX only) in the argument list. va_end Finishes the va_start session. va_start, va_ Initializes a variable to the beginning of start_1 the argument list. vfprintf, Prints formatted output based on an vprintf, argument list. vsprintf___________________________________________________ 3.1 Character-Classification Functions The character-classification functions take a single argument on which they perform a logical operation. The argument can have any value; it does not have to be an ASCII character. The isascii function determines if the argument is an ASCII character (0 through 177 octal). The other functions determine whether the argument is a particular type of ASCII character, such as a graphic character or digit. The isw* functions test wide characters. Character-classification information is in the LC_CTYPE category of the program's current locale. For all functions, a positive return value indicates TRUE. A return value of 0 indicates FALSE. To briefly reference the character-classification functions in a subsequent table, each function is assigned a number, as shown in Table 3-2. Character, String, and Argument-List Functions 3-7 Table_3-2_Character-Classification_Functions_______________ Function Function Number_____Function______Number_____Function_______________ 1 isalnum 7 islower 2 isalpha 8 isprint 3 isascii 9 ispunct 4 iscntrl 10 isspace 5 isdigit 11 isupper 6__________isgraph_______12_________isxdigit_______________ Table 3-3 lists the numbers of the functions (as assigned in Table 3-2) that return the value TRUE for each of the given ASCII characters. The numeric code represents the octal value of each of the ASCII characters. Table 3-3 ASCII Characters and the Character-Classification __________Functions________________________________________ ASCII Function ASCII Function Values_____Numbers______Values_____Numbers_________________ NUL 00 3,4 @ 100 3,6,8,9 SOH 01 3,4 A 101 1,2,3,6,8,11,12 STX 02 3,4 B 102 1,2,3,6,8,11,12 ETX 03 3,4 C 103 1,2,3,6,8,11,12 EOT 04 3,4 D 104 1,2,3,6,8,11,12 ENQ 05 3,4 E 105 1,2,3,6,8,11,12 ACK 06 3,4 F 106 1,2,3,6,8,11,12 BEL 07 3,4 G 107 1,2,3,6,8,11 BS 10 3,4 H 110 1,2,3,6,8,11 HT 11 3,4,10 I 111 1,2,3,6,8,11 LF 12 3,4,10 J 112 1,2,3,6,8,11 VT 13 3,4,10 K 113 1,2,3,6,8,11 FF 14 3,4,10 L 114 1,2,3,6,8,11 (continued on next page) 3-8 Character, String, and Argument-List Functions Table 3-3 (Cont.) ASCII Characters and the Character- __________________Classification_Functions_________________ ASCII Function ASCII Function Values_____Numbers______Values_____Numbers_________________ CR 15 3,4,10 M 115 1,2,3,6,8,11 SO 16 3,4 N 116 1,2,3,6,8,11 SI 17 3,4 O 117 1,2,3,6,8,11 DLE 20 3,4 P 120 1,2,3,6,8,11 DC1 21 3,4 Q 121 1,2,3,6,8,11 DC2 22 3,4 R 122 1,2,3,6,8,11 DC3 23 3,4 S 123 1,2,3,6,8,11 DC4 24 3,4 T 124 1,2,3,6,8,11 NAK 25 3,4 U 125 1,2,3,6,8,11 SYN 26 3,4 V 126 1,2,3,6,8,11 ETB 27 3,4 W 127 1,2,3,6,8,11 CAN 30 3,4 X 130 1,2,3,6,8,11 EM 31 3,4 Y 131 1,2,3,6,8,11 SUB 32 3,4 Z 132 1,2,3,6,8,11 ESC 33 3,4 [ 133 3,6,8,9 FS 34 3,4 \ 134 3,6,8,9 GS 35 3,4 ] 135 3,6,8,9 RS 36 3,4 ^ 136 3,6,8,9 US 37 3,4 - 137 3,6,8,9 SP 40 3,8,10 ?` 140 3,6,8,9 ! 41 3,6,8,9 a 141 1,2,3,6,7,8,12 " 42 3,6,8,9 b 142 1,2,3,6,7,8,12 # 43 3,6,8,9 c 143 1,2,3,6,7,8,12 $ 44 3,6,8,9 d 144 1,2,3,6,7,8,12 % 45 3,6,8,9 e 145 1,2,3,6,7,8,12 (continued on next page) Character, String, and Argument-List Functions 3-9 Table 3-3 (Cont.) ASCII Characters and the Character- __________________Classification_Functions_________________ ASCII Function ASCII Function Values_____Numbers______Values_____Numbers_________________ & 46 3,6,8,9 f 146 1,2,3,6,7,8,12 ' 47 3,6,8,9 g 147 1,2,3,6,7,8 ( 50 3,6,8,9 h 150 1,2,3,6,7,8 ) 51 3,6,8,9 i 151 1,2,3,6,7,8 * 52 3,6,8,9 j 152 1,2,3,6,7,8 + 53 3,6,8,9 k 153 1,2,3,6,7,8 ' 54 3,6,8,9 l 154 1,2,3,6,7,8 - 55 3,6,8,9 m 155 1,2,3,6,7,8 ?. 56 3,6,8,9 n 156 1,2,3,6,7,8 / 57 3,6,8,9 o 157 1,2,3,6,7,8 0 60 1,3,5,6,8,12 p 160 1,2,3,6,7,8 1 61 1,3,5,6,8,12 q 161 1,2,3,6,7,8 2 62 1,3,5,6,8,12 r 162 1,2,3,6,7,8 3 63 1,3,5,6,8,12 s 163 1,2,3,6,7,8 4 64 1,3,5,6,8,12 t 164 1,2,3,6,7,8 5 65 1,3,5,6,8,12 u 165 1,2,3,6,7,8 6 66 1,3,5,6,8,12 v 166 1,2,3,6,7,8 7 67 1,3,5,6,8,12 w 167 1,2,3,6,7,8 (continued on next page) 3-10 Character, String, and Argument-List Functions Table 3-3 (Cont.) ASCII Characters and the Character- __________________Classification_Functions_________________ ASCII Function ASCII Function Values_____Numbers______Values_____Numbers_________________ 8 70 1,3,5,6,8,12 x 170 1,2,3,5,6,8 9 71 1,3,5,6,8,12 y 171 1,2,3,5,6,8 : 72 3,6,8,9 z 172 1,2,3,5,6,8 ; 73 3,6,8,9 { 173 3,6,8,9 < 74 3,6,8,9 | 174 3,6,8,9 = 75 3,6,8,9 } 175 3,6,8,9 > 76 3,6,8,9 ?~ 176 3,6,8,9 ?_77_______3,6,8,9______DEL_177____3,4_____________________ Character, String, and Argument-List Functions 3-11 Example 3-1 shows how the character-classification functions are used. 3-12 Character, String, and Argument-List Functions Example 3-1 Character-Classification Functions /* CHAP_3_CHARCLASS.C */ /* This example uses the isalpha, isdigit, and isspace */ /* functions to count the number of occurrences of letters, */ /* digits, and white-space characters entered through the */ /* standard input (stdin). */ #include #include #include main() { char c; int i = 0, j = 0, k = 0; while ((c = getchar()) != EOF) { if (isalpha(c)) i++; if (isdigit(c)) j++; if (isspace(c)) k++; } printf("Number of letters: %d\n", i); printf("Number of digits: %d\n", j); printf("Number of spaces: %d\n", k); } The sample input and output from Example 3-1 follows: $ RUN EXAMPLE1 I saw 35 men with mustaches on Christopher Street. Number of letters: 39 Number of digits: 2 Number of spaces: 9 $ Character, String, and Argument-List Functions 3-13 3.2 Character-Conversion Functions The character-conversion functions convert one type of character to another type. These functions include: ecvt _tolower fcvt toupper gcvt _toupper mbtowc towctrans mbrtowc wctrans mbsrtowcs wcrtomb toascii wcsrtombs tolower For more information on each of these functions, see the Reference Section. 3-14 Character, String, and Argument-List Functions Example 3-2 shows how to use the ecvt function. Example 3-2 Converting Double Values to an ASCII String /* CHAP_3_CHARCONV.C */ /* This program uses the ecvt function to convert a double */ /* value to a string. The program then prints the string. */ #include #include #include #include main() { double val; /* Value to be converted */ int sign, /* Variables for sign */ point; /* and decimal place */ /* Array for the converted string */ static char string[20]; val = -3.1297830e-10; printf("original value: %e\n", val); if (sign) printf("value is negative\n"); else printf("value is positive\n"); printf("decimal point at %d\n", point); } The output from Example 3-2 is as follows: $ RUN EXAMPLE2 original value: -3.129783e-10 converted string: 31298 value is negative decimal point at -9 $ Character, String, and Argument-List Functions 3-15 Example 3-3 shows how to use the toupper and tolower functions. Example 3-3 Changing Characters to and from Uppercase Letters /* CHAP_3_CONV_UPPERLOWER.C */ /* This program uses the functions toupper and tolower to */ /* convert uppercase to lowercase and lowercase to uppercase */ /* using input from the standard input (stdin). */ #include #include /* To use EOF identifier */ #include main() { char c, ch; while ((c = getchar()) != EOF) { if (c >= 'A' && c <= 'Z') ch = tolower(c); else ch = toupper(c); putchar(ch); } } Sample input and output from Example 3-3 are as follows: $ RUN EXAMPLE3 LET'S GO TO THE stonewall INN. let's go to the STONEWALL inn. $ 3.3 String and Argument-List Functions The Compaq C RTL contains a group of functions that manipulate strings. Some of these functions concatenate strings; others search a string for specific characters or perform some other comparison, such as determining the equality of two strings. 3-16 Character, String, and Argument-List Functions The Compaq C RTL also contains a set of functions that allow you to copy buffers containing binary data. The set of functions defined and declared in the and the header files provide a method of accessing variable-length argument lists. The functions are defined by the ANSI C Standard and are more portable than those defined in . The RTL functions such as printf and execl, for example, use variable-length argument lists. User-defined functions with variable-length argument lists that do not use or are not portable due to the different argument-passing conventions of various machines. The header file does not contain va_alist and va_dcl. The following shows a syntax example when using : function_name(int arg1, ...) { va_list ap; . . . When using : o The identifier va_alist is a parameter in the function definition. o va_dcl declares the parameter va_alist, a declaration that is not terminated with a semicolon (;); o The type va_list is used in the declaration of the variable used to traverse the list. You must declare at least one variable of type va_list when using . These names and declarations have the following syntax: function_name(va_alist) va_dcl { va_list ap; . . Character, String, and Argument-List Functions 3-17 . 3.4 Program Examples Example 3-4 shows how to use the strcat and strncat functions. Example 3-4 Concatenating Two Strings /* CHAP_3_CONCAT.C */ /* This example uses strcat and strncat to concatenate two */ /* strings. */ #include #include main() { static char string1[80] = "Concatenates "; static char string2[] = "two strings "; static char string3[] = "up to a maximum of characters."; static char string4[] = "imum number of characters"; printf("strcat:\t%s\n", strcat(string1, string2)); printf("strncat ( 0):\t%s\n", strncat(string1, string3, 0)); printf("strncat (11):\t%s\n", strncat(string1, string3, 11)); printf("strncat (40):\t%s\n", strncat(string1, string4, 40)); } Example 3-4 produces the following output: $ RUN EXAMPLE1 strcat: Concatenates two strings strncat ( 0): Concatenates two strings strncat (11): Concatenates two strings up to a max strncat (40): Concatenates two strings up to a maximum number of characters. $ Example 3-5 shows how to use the strcspn function. Example 3-5 Four Arguments to the strcspn Function (continued on next page) 3-18 Character, String, and Argument-List Functions Example 3-5 (Cont.) Four Arguments to the strcspn Function /* CHAP_3_STRCSPN.C */ /* This example shows how strcspn interprets four */ /* different kinds of arguments. */ #include main() { printf("strcspn with null charset: %d\n", strcspn("abcdef", "")); printf("strcspn with null string: %d\n", strcspn("", "abcdef")); printf("strcspn(\"xabc\", \"abc\"): %d\n", strcspn("xabc", "abc")); printf("strcspn(\"abc\", \"def\"): %d\n", strcspn("abc", "def")); } The sample output, to the file strcspn.out, in Example 3-5 is as follows: $ RUN EXAMPLE2 strcspn with null charset: 6 strcspn with null string: 0 strcspn("xabc","abc"): 1 strcspn("abc","def"): 3 Example 3-6 shows how to use the functions and definitions. Example 3-6 Using the Functions and Definitions (continued on next page) Character, String, and Argument-List Functions 3-19 Example 3-6 (Cont.) Using the Functions and Definitions /* CHAP_3_STDARG.C */ /* This routine accepts a variable number of string arguments, */ /* preceded by a count of the number of such strings. It */ /* allocates enough space in which to concatenate all of the */ /* strings, concatenates them together, and returns the address */ /* of the new string. It returns NULL if there are no string */ /* arguments, or if they are all null strings. */ #include /* Include appropriate header files. */ #include #include #include /* For the "example" call in main */ /* NSTRINGS is the maximum number of string arguments accepted */ /* (arbitrary). */ #define NSTRINGS 10 char *concatenate(int n,...) { va_list ap; /* Declare the argument pointer. */ char *list[NSTRINGS], *string; int index = 0, size = 0; /* Check that the number of arguments is within range. */ if (n <= 0) return NULL; if (n > NSTRINGS) n = NSTRINGS; va_start(ap, n); /* Initialize the argument pointer. */ do { /* Extract the next argument and save it. */ list[index] = va_arg(ap, char *); size += strlen(list[index]); } while (++index < n); (continued on next page) 3-20 Character, String, and Argument-List Functions Example 3-6 (Cont.) Using the Functions and Definitions va_end(ap); /* Terminate use of ap. */ if (size == 0) return NULL; string = malloc(size + 1); string[0] = '\0'; /* Append each argument to the end of the growing result */ /* string. */ for (index = 0; index < n; ++index) strcat(string, list[index]); return string; } /* An example of calling this routine is */ main() { char *ret_string ; ret_string = concatenate(7, "This ", "message ", "is ", "built with ", "a", " variable arg", " list.") ; puts(ret_string) ; } The call to Example 3-6 produces the following output: This message is built with a variable arg list. Character, String, and Argument-List Functions 3-21 4 _________________________________________________________________ Error and Signal Handling Table 4-1 lists and describes all the error- and signal- handling functions found in the Compaq C Run-Time Library (RTL). For more detailed information on each function, see the Reference Section. Table_4-1_Error-_and_Signal-Handling_Functions_____________ Function_________Description_______________________________ abort Raises the signal SIGABRT that terminates the execution of the program. assert Puts diagnostics into programs. atexit Registers a function to be called at program termination. exit, _exit Terminates the current program. perror Writes a short error message to stderr describing the current errno value. strerror Maps the error code in errno to an error message string. alarm Sends the signal SIGALARM to the invoking process after the number of seconds indicated by its argument has elapsed. gsignal Generates a specified software signal. kill Sends a SIGKILL signal to the process specified by a process ID. longjmp Transfers control from a nested series of function invocations back to a predefined point without returning normally. (continued on next page) Error and Signal Handling 4-1 Table_4-1_(Cont.)_Error-_and_Signal-Handling_Functions_____ Function_________Description_______________________________ pause Causes the process to wait until it receives a signal. raise Generates a specified signal. setjmp Establishes the context for a later transfer of control from a nested series of function invocations, without returning normally. sigaction Specifies the action to take upon delivery of a signal. sigaddset Adds the specified individual signal. sigblock Causes the signals in its argument to be added to the current set of signals being blocked from delivery. sigdelset Deletes a specified individual signal. sigemptyset Initializes the signal set to exclude all signals. sigfillset Initializes the signal set to include all signals. sigismember Tests whether a specified signal is a member of the signal set. siglongjmp Nonlocal goto with signal handling. sigmask Constructs the mask for a given signal number. signal Catches or ignores a signal. sigpause Blocks a specified set of signals and then waits for a signal that was not blocked. sigpending Examines pending signals. sigprocmask Sets the current signal mask. sigsetjmp Sets jump point for a nonlocal goto. sigsetmask Establishes the signals that are blocked from delivery. (continued on next page) 4-2 Error and Signal Handling Table_4-1_(Cont.)_Error-_and_Signal-Handling_Functions_____ Function_________Description_______________________________ sigstack Defines an alternate stack on which to process signals. sigsuspend Atomically changes the set of blocked signals and waits for a signal. sigvec Permanently assigns a handler for a specific signal. ssignal Allows you to specify the action to be taken when a particular signal is raised. VAXC$ESTABLISH Establishes an application exception handler in a way that is compatible with _________________Compaq_C_RTL_exception_handling.__________ 4.1 Error Handling When an error occurs during a call to any of the Compaq C RTL functions, the function returns an unsuccessful status. Many RTL routines also set the external variable errno to a value that indicates the reason for the failure. You should always check the return value for an error situation. The header file declares errno and symbolically defines the possible error codes. By including the header file in your program, you can check for specific error codes after a Compaq C RTL function call. At program startup, the value of errno is 0. The value of errno can be set to a nonzero value by many Compaq C RTL functions. It is not reset to 0 by any Compaq C RTL function, so it is only valid to use errno after a Compaq C RTL function call has been made and a failure status returned. Table 4-2 lists the symbolic values that may be assigned to errno by the Compaq C RTL. Error and Signal Handling 4-3 Table_4-2_The_Error_Code_Symbolic_Values___________________ Symbolic_Constant___Description____________________________ E2BIG Argument list too long EACCES Permission denied EADDRINUSE Address already in use EADDRNOTAVAIL Can't assign requested address EAFNOSUPPORT Address family not supported EAGAIN No more processes EALIGN Alignment error EALREADY Operation already in progress EBADF Bad file number EBADCAT Bad message catalogue format EBADMSG Corrupted message detected EBUSY Mount device busy ECANCELED Operation canceled ECHILD No children ECONNABORTED Software caused connection abort ECONNREFUSED Connection refused ECONNRESET Connection reset by peer EDEADLK Resource deadlock avoided EDESTADDRREQ Destination address required EDOM Math argument EDQUOT Disk quota exceeded EEXIST File exists EFAIL Cannot start operation EFAULT Bad address EFBIG File too large EFTYPE Inappropriate operation for file type EHOSTDOWN Host is down EHOSTUNREACH No route to host EIDRM Identifier removed (continued on next page) 4-4 Error and Signal Handling Table_4-2_(Cont.)_The_Error_Code_Symbolic_Values___________ Symbolic_Constant___Description____________________________ EILSEQ Illegal byte sequence EINPROGRESS Operation now in progress EINPROG Asynchronous operation in progress EINTR Interrupted system call EINVAL Invalid argument EIO I/O error EISCONN Socket is already connected EISDIR Is a directory ELOOP Too many levels of symbolic links EMFILE Too many open files EMLINK Too many links EMSGSIZE Message too long ENAMETOOLONG File name too long ENETDOWN Network is down ENETRESET Network dropped connection on reset ENETUNREACH Network is unreachable ENFILE File table overflow ENOBUFS No buffer space available ENODEV No such device ENOENT No such file or directory ENOEXEC Exec format error ENOLCK No locks available ENOMEM Not enough core ENOMSG No message of desired type ENOPROTOOPT Protocol not available ENOSPC No space left on device ENOSYS Function not implemented ENOTBLK Block device required ENOTCONN Socket is not connected (continued on next page) Error and Signal Handling 4-5 Table_4-2_(Cont.)_The_Error_Code_Symbolic_Values___________ Symbolic_Constant___Description____________________________ ENOTDIR Not a directory ENOTEMPTY Directory not empty ENOTSOCK Socket operation on non-socket ENOTSUP Function not implemented ENOTTY Not a typewriter ENWAIT No waiting processes ENXIO No such device or address EOPNOTSUPP Operation not supported on socket EPERM Not owner EPFNOSUPPORT Protocol family not supported EPIPE Broken pipe EPROCLIM Too many processes EPROTONOSUPPORT Protocol not supported EPROTOTYPE Protocol wrong type for socket ERANGE Result too large EREMOTE Too many levels of remote in path EROFS Read-only file system ESHUTDOWN Can't send after socket shutdown ESOCKTNOSUPPORT Socket type not supported ESPIPE Illegal seek ESRCH No such process ESTALE Stale NFS file handle ETIMEDOUT Connection timed out ETOOMANYREFS Too many references: can't splice ETXTBSY Text file busy EUSERS Too many users (continued on next page) 4-6 Error and Signal Handling Table_4-2_(Cont.)_The_Error_Code_Symbolic_Values___________ Symbolic_Constant___Description____________________________ EVMSERR OpenVMS-specific non-translatable error code EWOULDBLOCK I/O operation would block channel EXDEV_______________Cross-device_link______________________ You can translate the error codes to a message, similar to that found in UNIX systems, by using the perror or strerror function. If errno is set to EVMSERR, perror cannot translate the error code, and prints the following message, followed by the OpenVMS error message associated with the value: %s:nontranslatable vms error code: xxxxxx vms message: In the message, %s is the string you supply to perror; xxxxxx is the OpenVMS condition value. If errno is set to EVMSERR, then the OpenVMS condition value is available in the vaxc$errno variable declared in the header file. The vaxc$errno variable is guaranteed to have a valid value only if errno is set to EVMSERR; if errno is set to a value other than EVMSERR, the value of vaxc$errno is undefined. See also the strerror function in the Reference Section for another way to translate error codes. 4.2 Signal Handling A signal is a form of software interrupt to the normal execution of a user process. Signals occur as a result of a variety of events, including any of the following: o Typing Ctrl/C at a terminal o Certain programming errors o A call to the gsignal or raise function o A wake-up action Error and Signal Handling 4-7 4.2.1 OpenVMS Versus UNIX Terminology Both OpenVMS and UNIX systems provide signal-handling mechanisms that behave differently but use similar terminology. With the Compaq C RTL, you can program using either signal-handling mechanism. Before describing the signal-handling routines, some terminology must be established. The UNIX term for a software interrupt is signal. A routine called by the UNIX system to process a signal is termed a signal handler. A software interrupt on an OpenVMS system is referred to as a signal, condition, or exception. A routine called by the OpenVMS system to process software interrupts is termed a signal handler, condition handler, or exception handler. To prevent confusion, the terms signal and signal handler in this manual refer to UNIX interrupts and interrupt processing routines, while the terms exception and exception handler refer to OpenVMS interrupts and interrupt processing routines. 4.2.2 UNIX Signals and the Compaq C RTL Signals are represented by mnemonics defined in the header file. Table 4-3 lists the supported signal mnemonics and the corresponding event that causes each signal to be generated on the OpenVMS operating system. 4-8 Error and Signal Handling Table_4-3_Compaq_C_RTL_Signals_____________________________ Name______Description________Generated_by__________________ SIGABRT[1]Abort abort() SIGALRM Alarm clock Timer AST, alarm routine SIGBUS Bus error Access violation or change mode user SIGCHLD Child process Child process terminated or stopped stopped SIGEMT EMT instruction Compatibility mode trap or opcode reserved to customer SIGFPE Floating-point Floating-point overflow exception /underflow SIGHUP Hang up Data set hang up SIGILL[1] Illegal Illegal instruction, reserved instruction operand, or reserved address mode SIGINT[4] Interrupt OpenVMS Ctrl/C interrupt SIGIOT[1] IOT instruction Opcode reserved to customer SIGKILL[2]Kill External signal only SIGQUIT[5]Quit Not implemented. SIGPIPE Broken pipe Write to a pipe with no readers. SIGSEGV Segment Length violation or change violation mode user [1]Cannot_be_reset_when_caught.____________________________ [2]Cannot be caught or ignored. [3]Cannot be blocked. [4]Setting SIGINT can affect processing of Ctrl/Y interrupts. For example, in response to a caller's request to block or ignore SIGINT, the Compaq C RTL disables the Ctrl/Y interrupt. [5]"Not implemented" for SIGQUIT means that there is no external event, including a Ctrl/Y interrupt, that would trigger a SIGQUIT signal, thereby causing a signal handler established for SIGQUIT to be invoked. This signal can be generated only through an appropriate Compaq C RTL function, such as raise. (continued on next page) Error and Signal Handling 4-9 Table_4-3_(Cont.)_Compaq_C_RTL_Signals_____________________ Name______Description________Generated_by__________________ SIGSYS System call Bad argument to system call error SIGTERM Software External signal only terminate SIGTRAP[1]Trace trap TBIT trace trap or breakpoint fault instruction SIGUSR1 User-defined Explicit program call to raise signal the signal SIGUSR2 User-defined Explicit program call to raise signal the signal SIGWINCH[6window size Explicit program call to raise changed the signal [1]Cannot_be_reset_when_caught.____________________________ [6]Supported on OpenVMS Version 7.3 and higher. ___________________________________________________________ By default, when a signal (except for SIGCHLD) occurs, the process is terminated. However, you can choose to have the signal ignored by using one of the following functions: sigaction signal sigvec ssignal You can have the signal blocked by using one of the following functions: sigblock sigsetmask sigprocmask sigsuspend sigpause Table 4-3 indicates those signals that cannot be ignored or blocked. You can also establish a signal handler to catch and process a signal by using one of the following functions: sigaction signal 4-10 Error and Signal Handling sigvec ssignal Unless noted in Table 4-3, each signal can be reset. A signal is reset if the signal handler function calls signal or ssignal to re-establish itself to catch the signal. Example 4-1 shows how to establish a signal handler and reset the signal. The calling interface to a signal handler is: void handler (int sigint); Where sigint is the signal number of the raised signal that caused this handler to be called. A signal handler installed with sigvec remains installed until it is changed. A signal handler installed with signal or signal remains installed until the signal is generated. A signal handler can be installed for more than one signal. Use the sigaction routine with the flag SA_RESETHAND to control this. 4.2.3 Signal-Handling Concepts A signal is said to be generated for (or sent to) a process when the event that causes the signal first occurs. Examples of such events include detection of hardware faults, timer expiration, and terminal activity, as well as the invocation of kill. In some circumstances, the same event generates signals for multiple processes. Each process has an action to be taken in response to each signal defined by the system. A signal is said to be delivered to a process when the appropriate action for the process and signal is taken. During the time between the generation of a signal and its delivery, the signal is said to pending. Ordinarily, this interval cannot be detected by an application. However, a signal can be blocked from delivery to a process: o If the action associated with a blocked signal is anything other than to ignore the signal, and if that signal is generated for the process, the signal remains Error and Signal Handling 4-11 pending until either it is unblocked or the action associated with it is set to ignore the signal. o If the action associated with a blocked signal is to ignore the signal and if that signal is generated for the process, it is unspecified whether the signal is discarded immediately upon generation or remains pending. Each process has a signal mask that defines the set of signals currently blocked from delivery to it. The signal mask for a process is initialized from that of its parent. The sigaction, sigprocmask, and sigsuspend function control the manipulation of the signal mask. The determination of which action is taken in response to a signal is made at the time the signal is delivered, allowing for any changes since the time of generation. This determination is independent of the means by which the signal was originally generated. If a subsequent occurrence of a pending signal is generated, it is implementation- dependent as to whether the signal is delivered more than once. The Compaq C RTL delivers the signal only once. The order in which multiple, simultaneously pending signals are delivered to a process is unspecified. 4.2.4 Signal Actions This section applies to the sigaction, signal, sigvec, and ssignal functions. There are three types of action that can be associated with a signal: SIG_DFL SIG_IGN pointer to a function Initially, all signals are set to SIG_DFL or SIG_IGN prior to entry of the main routine (see the exec functions.) The actions prescribed by these values are: SIG_DFL - signal-specific default action o The default actions for the signals defined in this document are specified under . 4-12 Error and Signal Handling o If the default action is to stop the process, the execution of that process is temporarily suspended. When a process stops, a SIGCHLD signal is generated for its parent process, unless the parent process has set the SA_NOCLDSTOP flag. While a process is stopped, any additional signals that are sent to the process are not delivered until the process is continued, except SIGKILL which always terminates the receiving process. A process that is a member of an orphaned process group is not allowed to stop in response to the SIGSTOP, SIGTTIN, or SIGTTOU signals. In cases where delivery of one of these signals would stop such a process, the signal is discarded. o Setting a signal action to SIG_DFL for a signal that is pending and whose default action is to ignore the signal (for example, SIGCHLD), causes the pending signal to be discarded, whether or not it is blocked. SIG_IGN - ignore signal o Delivery of the signal has no effect on the process. The behavior of a process is undefined after it ignores a SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill or raise. o The system does not allow the action for the SIGKILL or SIGSTOP signals to be set to SIG_IGN. o Setting a signal action to SIG_IGN for a signal that is pending causes the pending signal to be discarded, whether or not it is blocked. o If a process sets the action for the SIGCHLD signal to SIG_IGN, the behavior is unspecified. pointer to a function - catch signal o On delivery of the signal, the receiving process executes the signal-catching function at the specified address. After returning from the signal- catching function, the receiving process resumes execution at the point at which it was interrupted. Error and Signal Handling 4-13 o Specify the signal-catching function as: void func(int signo); Where func is the specified signal-catching function and signo is the signal number of the signal being delivered. o The behavior of a process is undefined after it returns normally form a signal-catching function for a SIGFPE, SIGKILL, or SIGSEGV signal that was not generated by kill or raise. o The system does not allow a process to catch the signals SIGKILL and SIGSTOP. o If a process establishes a signal-catching function for the SIGCHLD signal while it has a terminated child process for which it has not waited, it is unspecified whether a SIGCHLD signal is generated to indicate that child process. 4.2.5 Signal Handling and OpenVMS Exception Handling This section discusses how Compaq C RTL signal handling is implemented with and interacts with OpenVMS exception handling. Information in this section allows you to write OpenVMS exception handlers that do not conflict with Compaq C RTL signal handling. For information on OpenVMS exception handling, see the VAX Procedure Calling and Condition Handling Standard. The Compaq C RTL implements signals with OpenVMS exceptions. When gsignal or raise is called, the signal number is translated to a particular OpenVMS exception, which is used in a call to LIB$SIGNAL. This mechanism is necessary to catch an OpenVMS exception resulting from a user error and translate it into a corresponding UNIX signal. For example, an ACCVIO resulting from a write to a NULL pointer is translated to a SIGBUS or SIGSEGV signal. Tables 4-4 and 4-5 list the Compaq C RTL signal names, the corresponding OpenVMS VAX and OpenVMS Alpha exceptions, the event that generates the signal, and the optional signal code for use with the gsignal and raise functions. 4-14 Error and Signal Handling Table 4-4 Compaq C RTL Signals and Corresponding OpenVMS VAX __________Exceptions_(VAX_only)__________________________________ OpenVMS Name______Exception______Generated_By__________Code______________ SIGABRT SS$_OPCCUS The abort function - SIGALRM SS$_ASTFLT The alarm function - SIGBUS SS$_ACCVIO Access violation - SIGBUS SS$_CMODUSER Change mode user - SIGCHLD C$_SIGCHLD Child process - stopped SIGEMT SS$_COMPAT Compatibility mode - trap SIGFPE SS$_DECOVF Decimal overflow FPE_DECOVF_TRAP trap SIGFPE SS$_FLTDIV Floating/decimal FPE_FLTDIV_TRAP division by 0 SIGFPE SS$_FLTDIV_F Floating divide by 0 FPE_FLTDIV_FAULT fault SIGFPE SS$_FLTOVF Floating overflow FPE_FLTOVF_TRAP trap SIGFPE SS$_FLTOVF_F Floating overflow FPE_FLTOVF_FAULT fault SIGFPE SS$_FLTUND Floating undeflow FPE_FLTUND_TRAP trap SIGFPE SS$_FLTUND_F Floating undeflow FPE_FLTUND_FAULT fault SIGFPE SS$_INTDIV Integer division by FPE_INTDIV_TRAP 0 SIGFPE SS$_INTOVF Integer overflow FPE_INTOVF_TRAP SIGFPE SS$_SUBRNG Subscript-range FPE_SUBRNG_TRAP SIGHUP SS$_HANGUP Data set hangup - SIGILL SS$_OPCDEC Reserved instruction ILL_PRIVIN_FAULT SIGILL SS$_RADRMOD Reserved addressing ILL_RESAD_FAULT SIGILL SS$_ROPRAND Reserved operand ILL_RESOP_FAULT (continued on next page) Error and Signal Handling 4-15 Table 4-4 (Cont.) Compaq C RTL Signals and Corresponding OpenVMS __________________VAX_Exceptions_(VAX_only)______________________ OpenVMS Name______Exception______Generated_By__________Code______________ SIGINT SS$_CONTROLC OpenVMS Ctrl/C - interrupt SIGIOT SS$_OPCCUS Customer-reserved - opcode SIGKILL SS$_ABORT External signal only - SIGQUIT SS$_CONTROLY The raise function - SIGPIPE SS$_NOMBX No mailbox - SIGSEGV SS$_ACCVIO Length violation - SIGSEGV SS$_CMODUSER Change mode user - SIGSYS SS$_BADPARAM Bad argument to - system call SIGTERM Not - - implemented SIGTRAP SS$_TBIT TBIT trace trap - SIGTRAP SS$_BREAK Breakpoint fault - instruction SIGUSR1 C$_SIGUSR1 The raise function - SIGUSR2 C$_SIGUSR2 The raise function - SIGWINCH[1C$_ The raise function - SIGWINCH[2] [1]Supported_on_OpenVMS_Version_7.3_and_higher.__________________ [2]SS$_BADWINCNT when C$_SIGWINCH not defined (OpenVMS versions before 7.3). _________________________________________________________________ To call a signal handler that you have established with signal or sigvec, the Compaq C RTL intercepts the OpenVMS exceptions that correspond to signals by having an OpenVMS exception handler in the main routine of the program. If your program has a main function, then this exception handler is automatically established. If you do not have a main function, or if your main function is written in a language other than Compaq C, then you must invoke the VAXC$CRTL_INIT routine to establish this handler. 4-16 Error and Signal Handling The Compaq C RTL uses OpenVMS exceptions to implement the setjmp and longjmp functions. When the longjmp function is called, a C$_LONGJMP OpenVMS exception is signaled. To prevent the C$_LONGJMP exception from being interfered with by user exception handlers, use the VAXC$ESTABLISH routine to establish user OpenVMS exception handlers instead of calling LIB$ESTABLISH. The C$_LONGJMP mnemonic is defined in the header file. If you want to use OpenVMS exception handlers and UNIX signals in your C program, your OpenVMS exception handler must be prepared to accept and resignal the OpenVMS exceptions listed in Tables 4-4 (VAX only) and 4-5 (Alpha only), as well as the C$_LONGJMP exception and any C$ facility exception that might be introduced in future versions of the Compaq C RTL. This is because UNIX signals are global in context, whereas OpenVMS exceptions are stack-frame based. Consequently, an OpenVMS exception handler always receives the exception that corresponds to the UNIX signal before the Compaq C RTL exception handler in the main routine does. By resignaling the OpenVMS exception, you allow the Compaq C RTL exception handler to receive the exception. You can intercept any of those OpenVMS exceptions yourself, but in doing so you will disable the corresponding UNIX signal. Table 4-5 Compaq C RTL Signals and Corresponding OpenVMS Alpha __________Exceptions_(Alpha_only)________________________________ OpenVMS Name______Exception______Generated_By__________Code______________ SIGABRT SS$_OPCCUS The abort function - SIGALRM SS$_ASTFLT The alarm function - SIGBUS SS$_ACCVIO Access violation - SIGBUS SS$_CMODUSER Change mode user - SIGCHLD C$_SIGCHLD Child process - stopped (continued on next page) Error and Signal Handling 4-17 Table 4-5 (Cont.) Compaq C RTL Signals and Corresponding OpenVMS __________________Alpha_Exceptions_(Alpha_only)__________________ OpenVMS Name______Exception______Generated_By__________Code______________ SIGEMT SS$_COMPAT Compatibility mode - trap SIGFP SS$_DECDIV Decimal divide trap FPE_DECDIV_TRAP SIGFPE SS$_DECINV Decimal invalid FPE_DECINV_TRAP operand trap SIGFPE SS$_DECOVF Decimal overflow FPE_DECOVF_TRAP trap SIGFPE SS$_HPARITH Floating/decimal FPE_FLTDIV_TRAP division by 0 SIGFPE SS$_HPARITH Floating overflow FPE_FLTOVF_TRAP trap SIGFPE SS$_HPARITH Floating undeflow FPE_FLTUND_TRAP trap SIGFPE SS$_HPARITH Integer overflow FPE_INTOVF_TRAP SIGFPE SS$_HPARITH Invalid operand FPE_INVOPR_TRAP SIGFPE SS$_HPARITH Inexact result FPE_INXRES_TRAP SIGFPE SS$_INTDIV Integer div by zero FPE_INTDIV_TRAP SIGFPE SS$_SUBRNG Subscript out of FPE_SUBRNG_TRAP range SIGFPE SS$_SUBRNG1 Subscript1 out of FPE_SUBRNG1_TRAP range SIGFPE SS$_SUBRNG2 Subscript2 out of FPE_SUBRNG2_TRAP range SIGFPE SS$_SUBRNG3 Subscript3 out of FPE_SUBRNG3_TRAP range SIGFPE SS$_SUBRNG4 Subscript4 out of FPE_SUBRNG4_TRAP range SIGFPE SS$_SUBRNG5 Subscript5 out of FPE_SUBRNG5_TRAP range (continued on next page) 4-18 Error and Signal Handling Table 4-5 (Cont.) Compaq C RTL Signals and Corresponding OpenVMS __________________Alpha_Exceptions_(Alpha_only)__________________ OpenVMS Name______Exception______Generated_By__________Code______________ SIGFPE SS$_SUBRNG6 Subscript6 out of FPE_SUBRNG6_TRAP range SIGFPE SS$_SUBRNG7 Subscript7 out of FPE_SUBRNG7_TRAP range SIGHUP SS$_HANGUP Data set hangup - SIGILL SS$_OPCDEC Reserved instruction ILL_PRIVIN_FAULT SIGILL SS$_ROPRAND Reserved operand ILL_RESOP_FAULT SIGINT SS$_CONTROLC OpenVMS Ctrl/C - interrupt SIGIOT SS$_OPCCUS Customer-reserved - opcode SIGKILL SS$_ABORT External signal only - SIGQUIT SS$_CONTROLY The raise function - SIGPIPE SS$_NOMBX No mailbox - SIGSEGV SS$_ACCVIO Length violation - SIGSEGV SS$_CMODUSER Change mode user - SIGSYS SS$_BADPARAM Bad argument to - system call SIGTERM Not - - implemented SIGTRAP SS$_BREAK Breakpoint fault - instruction SIGUSR1 C$_SIGUSR1 The raise function - SIGUSR2 C$_SIGUSR2 The raise function - SIGWINCH[1C$_ The raise function - SIGWINCH[2] [1]Supported_on_OpenVMS_Version_7.3_and_higher.__________________ [2]SS$_BADWINCNT when C$_SIGWINCH not defined (OpenVMS versions before 7.3). _________________________________________________________________ __ OpenVMS Alpha Signal-Handling Notes (Alpha only) __ Error and Signal Handling 4-19 o While all signals that exist on OpenVMS VAX systems also exist on OpenVMS Alpha systems, the corresponding OpenVMS exceptions and code is different in a number of cases because on Alpha processors there are two new OpenVMS exceptions and several others that are obsolete. o All floating-point exceptions on OpenVMS Alpha systems are signaled by the OpenVMS exception SS$_HPARITH (high-performance arithmetic trap). The particular type of trap that occurred is translated by the Compaq C RTL through use of the exception summary longword, which is set when a high-performance arithmetic trap is signaled. o Since the SS$_COMPAT, SS$_TBIT, and SS$_RADMOD exceptions are never reported on OpenVMS Alpha systems, they are not recognized by the Compaq C RTL on OpenVMS Alpha systems. Since each signal that corresponds to one of these exceptions also corresponds to another OpenVMS exception as well, all the signals are shown in Table 4-5. ______________________________________________________ 4.3 Program Example Example 4-1 shows how the signal, alarm, and pause functions operate. It also shows how to establish a signal handler to catch a signal, thereby preventing program termination. 4-20 Error and Signal Handling Example 4-1 Suspending and Resuming Programs /* CHAP_4_SUSPEND_RESUME.C */ /* This program shows how to alternately suspend and resume a */ /* program using the signal, alarm, and pause functions. */ #define SECONDS 5 #include #include int number_of_alarms = 5; /* Set alarm counter. */ void alarm_action(int); main() { signal(SIGALRM, alarm_action); /* Establish a signal handler. */ /* to catch the SIGALRM signal.*/ alarm(SECONDS); /* Set alarm clock for 5 seconds. */ pause(); /* Suspend the process until * * the signal is received. */ } void alarm_action(int x) { printf("\t<%d\007>", number_of_alarms); /* Print the value of */ /* the alarm counter. */ signal(SIGALRM, alarm_action); /* Reset the signal. */ alarm(SECONDS); /* Set the alarm clock. */ if (--number_of_alarms) /* Decrement alarm counter. */ pause(); } Here is the sample output from Example 4-1: $ RUN EXAMPLE <5> <4> <3> <2> <1> Error and Signal Handling 4-21 5 _________________________________________________________________ Subprocess Functions The Compaq C Run-Time Library (RTL) provides functions that allow you to create subprocesses from a Compaq C program. The creating process is called the parent and the created subprocess is called the child. To create a child process within the parent process, use the exec functions (execl, execle, execv, execve, execlp, and execvp) and the vfork function. Other functions are available to allow the parent and child to read and write data across processes (pipe) and to allow for synchronization of the two processes (wait). This chapter describes how to implement and use these functions. The parent process can execute Compaq C programs in its children, either synchronously or asynchronously. The number of children that can run simultaneously is determined by the /PRCLM user authorization quota established for each user on your system. Other quotas that may affect the use of subprocesses are /ENQLM (Queue Entry Limit), /ASTLM (AST Waits Limit), and /FILLM (Open File Limit). This chapter discusses the subprocess functions. Table 5-1 lists and describes all the subprocess functions found in the Compaq C RTL. For more detailed information on each function, see the Reference Section. Subprocess Functions 5-1 Table_5-1_Subprocess_Functions_____________________________ Function____________Description____________________________ Implementation_of_Child_Processes__________________________ system Passes a given string to the host environment to be executed by a command processor. vfork Creates an independent child process. ___________________________________________________________ The_exec_Functions_________________________________________ execl, execle, Passes the name of the image to be execlp activated in a child process. execv, execve, execvp ___________________________________________________________ Synchronizing_Process______________________________________ wait, wait3, Suspends the parent process until a wait4, waitpid, value is returned from a child. ___________________________________________________________ Interprocess_Communication_________________________________ pipe Allows for communication between a ____________________parent_and_child.______________________ 5.1 Implementing Child Processes in Compaq C Child processes are created by Compaq C functions with the OpenVMS LIB$SPAWN RTL routine. (See the VMS Run-Time Library Routines Volume for information on LIB$SPAWN.) Using LIB$SPAWN allows you to create multiple levels of child processes; the parent's children can also spawn children, and so on, up to the limits allowed by the user authorization quotas discussed in the introductory section of this chapter. Child processes can only execute other Compaq C programs. Other native-mode OpenVMS languages do not share the ability of Compaq C to communicate between processes; if they do, they do not use the same mechanisms. The parent 5-2 Subprocess Functions process must be run under a Compaq supported command- language interpreter (CLI), such as the DIGITAL Command Language (DCL). You cannot run the parent as a detached process or under control of a user-supplied CLI. Parent and child processes communicate through a mailbox as shown in Figure 5-1. This mailbox transfers the context in which the child will run. This context mailbox passes information to the child that it inherits from the parent, such as the names and file descriptors of all the files opened by the parent and the current location within those files. The mailbox is deleted by the parent when the child image exits. Figure 5-1 Communications Links Between Parent and Child Processes ________________________ Note ________________________ The mailbox created by the vfork and exec functions is temporary. The logical name of this mailbox is VAXC$EXECMBX and is reserved for use by the Compaq C RTL. ______________________________________________________ The mailbox is created with a maximum message size and a buffer quota of 512 bytes each. You need the TMPMBX privilege to create a mailbox with these RTL functions. Since TMPMBX is the privilege required by the DCL commands PRINT and SUBMIT, most users on a system have this privilege. To see what system privileges you have, enter a SHOW PROCESS/PRIVILEGES command. You cannot change the characteristics of these mailboxes. For more information on mailboxes, see the VMS I/O User's Reference Volume. Subprocess Functions 5-3 5.2 The exec Functions There are six exec functions that you can call to execute a Compaq C image in the child process. These functions expect that vfork has been called to set up a return address. The exec functions will call vfork if the parent process did not. When vfork is called by the parent, the exec function returns to the parent process. When vfork was called by an exec function, the exec function returns to itself, waits for the child to exit, and then exits the parent process. The exec function does not return to the parent process unless the parent calls vfork to save the return address. In OpenVMS Version 7.2, the exec functions were enhanced to activate either executable images or DCL command procedures. If no file extension is specified in the file_ name argument, the functions first search for the file with the .EXE file extension and then for the file with the .COM file extension. If both the executable image and the command procedure with the same name exist, you must explicitly specify the .COM file extension to force activating the command procedure. For a DCL command procedure, the exec functions pass the first eight arg0, arg1, ..., arguments specified in the exec call to the command procedure as P1, P2, ... parameters, preserving the case. Unlike UNIX based systems, the exec functions in the Compaq C RTL cannot always determine if the specified executable image or command procedure exists and can be activated and executed. Therefore, the exec functions might appear to succeed even though the specified file cannot be executed by the child process. The status of the child process, returned to the parent process, indicates that the error occurred. You can retrieve this error code by using one of the functions from the wait family of functions. ________________________ Note ________________________ The vfork and exec functions in the Compaq C RTL on OpenVMS systems work differently than on UNIX systems: 5-4 Subprocess Functions o On UNIX systems, vfork creates a child process, suspends the parent, and starts the child running where the parent left off. o On OpenVMS systems, vfork establishes context later used by an exec, function but it is the exec function, not vfork, that starts a process running the specified program. For a progammer, the key differences are: o On OpenVMS systems, code between the the call to vfork and the call to an exec function runs in the parent process. On UNIX systems, this code runs in the child process. o On OpenVMS systems, the child inherits open file descriptors and so on, at the point where the exec function is called. On UNIX systems, this occurs at the point where vfork is called. ______________________________________________________ 5.2.1 Exec Processing The exec functions use the LIB$SPAWN routine to create the subprocess and activate the child image within the subprocess. This child process inherits the parent's environment, including all defined logical names and command-line interpreter symbols. The exec functions use the logical name VAXC$EXECMBX to communicate between parent and child; this logical name must not exist outside the context of the parent image. The exec functions pass the following information to the child: o The parent's umask value, which specifies whether any access is to be disallowed when a new file is created. For more information about the umask function, see the Reference Section. Subprocess Functions 5-5 o The file-name string associated with each file descriptor and the current position within each file. The child opens the file and calls lseek to position the file to the same location as the parent. If the file is a record file, the child is positioned on a record boundary, regardless of the parent's position within the record. For more information about file descriptors, see Chapter 2. For more information on the lseek function, see the Reference Section. This information is sent to the child for all descriptors known to the parent including all descriptors for open files, null descriptors, and duplicate descriptors. File pointers are not transferred to the child. For files opened by a file pointer in the parent, only their corresponding file descriptors are passed to the child. The fdopen function must be called to associate a file pointer with the file descriptor if the child will access the file-by-file pointer. For more information about the fdopen function, see the Reference Section. o The signal database. Only SIG_IGN (ignore) actions are inherited. Actions specified as routines are changed to SIG_DFL (default) because the parent's signal-handling routines are inaccessible to the child. o The environment and argument vectors. When everything is transmitted to the child, exec processing is complete. Control in the parent process then returns to the address saved by vfork and the child's process ID is returned to the parent. See also Section 4.2.4 for a discussion of signal actions and the SIGCHLD signal. 5.2.2 Exec Error Conditions The exec functions will fail if LIB$SPAWN cannot create the subprocess. Conditions that can cause a failure include exceeding the subprocess quota or finding the communications by the context mailbox between the parent and child to be broken. Exceeding some quotas will not cause LIB$SPAWN to fail, but will put LIB$SPAWN into a wait 5-6 Subprocess Functions state that can cause the parent process to hang. An example of such a quota is the Open File Limit quota. You will need an Open File Limit quota of at least 20 files, with an average of three times the number of concurrent processes that your program will run. If you use more than one open pipe at a time, or perform I/O on several files at one time, this quota may need to be even higher. See your system manager if this quota needs to be increased. When an exec function fails, a value of -1 is returned. After such a failure, the parent is expected to call either the exit or _exit function. Both functions then return to the parent's vfork call, which returns the child's process ID. In this case, the child process ID returned by exec is less than zero. For more information about the exit function, see the Reference Section. 5.3 Synchronizing Processes A child process is terminated when the parent process terminates. Therefore, the parent process must check the status of its child processes before exiting. This is done using the Compaq C RTL function wait. 5.4 Interprocess Communication A channel through which parent and child processes communicate is called a pipe. Use the pipe function to create a pipe. 5.5 Program Examples Example 5-1 shows the basic procedures for executing an image in a child process. The child process in Example 5-1 prints a message 10 times. Example 5-1 Creating the Child Process (continued on next page) Subprocess Functions 5-7 Example 5-1 (Cont.) Creating the Child Process /* chap_5_exec_image.c */ /* This example creates the child process. The only */ /* functionality given to the child is the ability to */ /* print a message 10 times. */ #include /* CLI status values */ #include #include #include #include static const char *child_name = "chap_5_exec_image_child.exe" ; main() { int status, cstatus; /* NOTE: */ /* Any local automatic variables, even those */ /* having the volitile attribute, may have */ /* indeterminant values if they are modified */ /* between the vfork() call and the matching */ /* exec() call. */ if ((status = vfork()) != 0) { /* This is either an error or */ /* the "second" vfork return, taking us "back" */ /* to parent mode. */ if (status < 0) printf("Parent - Child process failed\n"); else { printf("Parent - Waiting for Child\n"); if ((status = wait(&cstatus)) == -1) perror("Parent - Wait failed"); else if (cstatus == CLI$_IMAGEFNF) printf("Parent - Child does not exist\n"); (continued on next page) 5-8 Subprocess Functions Example 5-1 (Cont.) Creating the Child Process else printf("Parent - Child final status: %d\n", cstatus); } } else { /* The FIRST Vfork return is zero, do the exec() */ printf("Parent - Starting Child\n"); if ((status = execl(child_name, 0)) == -1) { perror("Parent - Execl failed"); exit(EXIT_FAILURE); } } } ---------------------------------------------------------- /* CHAP_5_EXEC_IMAGE_CHILD.C */ /* This is the child program that writes a message */ /* through the parent to "stdout" */ #include main() { int i; for (i = 0; i < 10; i++) printf("Child - executing\n"); return (255) ; /* Set an unusual success stat */ } Key to Example 5-1: 1 The vfork function is called to set up the return address for the exec call. The vfork function is normally used in the expression of an if statement. This construct allows you to take advantage of the double return aspect of vfork, since one return value is 0 and the other is nonzero. 2 A 0 return value is returned the first time vfork is called and the parent executes the else clause associated with the vfork call, which calls execl. Subprocess Functions 5-9 3 A negative child process ID is returned when an exec function fails. The return value is checked for these conditions. 4 The wait function is used to synchronize the parent and child processes. 5 Since the exec functions can indicate success up to this point even if the image to be activated in the child does not exist, the parent checks the child's return status for the predefined status, CLI$_IMAGEFNF (file not found). In Example 5-2, the parent passes arguments to the child process. Example 5-2 Passing Arguments to the Child Process /* CHAP_5_CHILDARG.C */ /* In this example, the arguments are placed in an array, gargv, */ /* but they can be passed to the child explicitly as a zero- */ /* terminated series of character strings. The child program in this */ /* example writes the arguments that have been passed it to stdout. */ #include #include #include #include #include const char *child_name = "chap_5_childarg_child.exe" ; main() { int status, cstatus; char *gargv[] = {"Child", "ARGC1", "ARGC2", "Parent", 0}; (continued on next page) 5-10 Subprocess Functions Example 5-2 (Cont.) Passing Arguments to the Child Process if ((status = vfork()) != 0) { if (status < -1) printf("Parent - Child process failed\n"); else { printf("Parent - waiting for Child\n"); if ((status = wait(&cstatus)) == -1) perror("Parent - Wait failed"); else if (cstatus == CLI$_IMAGEFNF) printf("Parent - Child does not exist\n"); else printf("Parent - Child final status: %x\n", cstatus); } } else { printf("Parent - Starting Child\n"); if ((status = execv(child_name, gargv)) == -1) { perror("Parent - Exec failed"); exit(EXIT_FAILURE); } } } -------------------------------------------------------- /* CHAP_5_CHILDARG_CHILD.C */ /* This is a child program that echos its arguments */ #include main(argc, argv) int argc; char *argv[]; { int i; printf("Program name: %s\n", argv[0]); (continued on next page) Subprocess Functions 5-11 Example 5-2 (Cont.) Passing Arguments to the Child Process for (i = 1; i < argc; i++) printf("Argument %d: %s\n", i, argv[i]); return(255) ; } Example 5-3 shows how to use the wait function to check the final status of multiple children being run simultaneously. Example 5-3 Checking the Status of Child Processes /* CHAP_5_CHECK_STAT.C */ /* In this example 5 child processes are started. The wait() */ /* function is placed in a separate for loop so that it is */ /* called once for each child. If wait() were called within */ /* the first for loop, the parent would wait for one child to */ /* terminate before executing the next child. If there were */ /* only one wait request, any child still running when the */ /* parent exits would terminate prematurely. */ #include #include #include #include #include const char *child_name = "chap_5_check_stat_child.exe" ; main() { int status, cstatus, i; (continued on next page) 5-12 Subprocess Functions Example 5-3 (Cont.) Checking the Status of Child Processes for (i = 0; i < 5; i++) { if ((status = vfork()) == 0) { printf("Parent - Starting Child %d\n", i); if ((status = execl(child_name, 0)) == -1) { perror("Parent - Exec failed"); exit(EXIT_FAILURE); } } else if (status < -1) printf("Parent - Child process failed\n"); } printf("Parent - Waiting for children\n"); for (i = 0; i < 5; i++) { if ((status = wait(&cstatus)) == -1) perror("Parent - Wait failed"); else if (cstatus == CLI$_IMAGEFNF) printf("Parent - Child does not exist\n"); else printf("Parent - Child %X final status: %d\n", status, cstatus); } } Example 5-4 shows how to use the pipe and dup2 functions to communicate between a parent and child process through specific file descriptors. The #define preprocessor directive defines the preprocessor constants inpipe and outpipe as the names of file descriptors 11 and 12. Example 5-4 Communicating Through a Pipe (continued on next page) Subprocess Functions 5-13 Example 5-4 (Cont.) Communicating Through a Pipe /* CHAP_5_PIPE.C */ /* In this example, the parent writes a string to the pipe for */ /* the child to read. The child then writes the string back */ /* to the pipe for the parent to read. The wait function is */ /* called before the parent reads the string that the child has */ /* passed back through the pipe. Otherwise, the reads and */ /* writes will not be synchronized. */ #include #include #include #include #include #include #include #define inpipe 11 #define outpipe 12 const char *child_name = "chap_5_pipe_child.exe" ; main() { int pipes[2]; int mode, status, cstatus, len; char *outbuf, *inbuf; if ((outbuf = malloc(512)) == 0) { printf("Parent - Outbuf allocation failed\n"); exit(EXIT_FAILURE); } (continued on next page) 5-14 Subprocess Functions Example 5-4 (Cont.) Communicating Through a Pipe if ((inbuf = malloc(512)) == 0) { printf("Parent - Inbuf allocation failed\n"); exit(EXIT_FAILURE); } if (pipe(pipes) == -1) { printf("Parent - Pipe allocation failed\n"); exit(EXIT_FAILURE); } dup2(pipes[0], inpipe); dup2(pipes[1], outpipe); strcpy(outbuf, "This is a test of two-way pipes.\n"); status = vfork(); switch (status) { case 0: printf("Parent - Starting child\n"); if ((status = execl(child_name, 0)) == -1) { printf("Parent - Exec failed"); exit(EXIT_FAILURE); } break; case -1: printf("Parent - Child process failed\n"); break; default: printf("Parent - Writing to child\n"); if (write(outpipe, outbuf, strlen(outbuf) + 1) == -1) { perror("Parent - Write failed"); exit(EXIT_FAILURE); } else { if ((status = wait(&cstatus)) == -1) perror("Parent - Wait failed"); (continued on next page) Subprocess Functions 5-15 Example 5-4 (Cont.) Communicating Through a Pipe if (cstatus == CLI$_IMAGEFNF) printf("Parent - Child does not exist\n"); else { printf("Parent - Reading from child\n"); if ((len = read(inpipe, inbuf, 512)) <= 0) { perror("Parent - Read failed"); exit(EXIT_FAILURE); } else { printf("Parent: %s\n", inbuf); printf("Parent - Child final status: %d\n", cstatus); } } } break; } } ------------------------------------------------------------------ /* CHAP_5_PIPE_CHILD.C */ /* This is a child program which reads from a pipe and writes */ /* the received message back to its parent. */ #include #include #include #include #define inpipe 11 #define outpipe 12 main() { char *buffer; int len; if ((buffer = malloc(512)) == 0) { perror("Child - Buffer allocation failed\n"); exit(EXIT_FAILURE); } (continued on next page) 5-16 Subprocess Functions Example 5-4 (Cont.) Communicating Through a Pipe printf("Child - Reading from parent\n"); if ((len = read(inpipe, buffer, 512)) <= 0) { perror("Child - Read failed"); exit(EXIT_FAILURE); } else { printf("Child: %s\n", buffer); printf("Child - Writing to parent\n"); if (write(outpipe, buffer, strlen(buffer) + 1) == -1) { perror("Child - Write failed"); exit(EXIT_FAILURE); } } exit(EXIT_SUCCESS); } Subprocess Functions 5-17 6 _________________________________________________________________ Curses Screen Management Functions and Macros This chapter describes the screen management routines available with Compaq C for OpenVMS Systems. On all OpenVMS systems, the OpenVMS Curses screen management package is supported. This is the same package of routines used by the VAX C Run-Time Library (RTL). On Alpha systems, for OpenVMS Alpha Version 1.5 or higher, two screen management packages are supported: OpenVMS Curses and a more UNIX compatible package based on the Berkeley Standard Distribution (BSD) Curses software.[1] See Section 6.1 for more information. Furthermore, beginning with OpenVMS Alpha Version 7.0, the Compaq C RTL offers a curses package based on the 4.4BSD Berkeley Software Distribution. Documentation on the 4.4BSD curses package can be found in Screen Updating and Cursor Movement Optimization: A Library Package, by Kenneth C.R.C. Arnold. The functions and macros in the OpenVMS and BSD-based Curses packages are nearly the same. Most differences between them are called out in this chapter. Otherwise, this chapter makes no distinction between the two Curses packages, and refers to "Curses" or the "Curses functions and macros." ____________________ [1] Copyright (c) 1981 Regents of the University of California. All rights reserved. Curses Screen Management Functions and Macros 6-1 6.1 Using the BSD-Based Curses Package (Alpha only) The header file required to use the BSD-based Curses implementation is provided with the Compaq C compiler on OpenVMS Alpha systems. Existing programs are not affected by the BSD-based Curses functions because the OpenVMS Curses functions are still available as the default curses package. (Note that is a change from previous versions of Compaq C, where BSD-based curses was the default.) To get the the 4.4BSD Curses implementation, you must compile modules that include with the following qualifier: /DEFINE=_BSD44_CURSES The BSD-based Curses functions do not provide the support required to call the OpenVMS SMG$ routines with the pasteboard and keyboard allocated by the curses functions. Consequently, Curses programs that rely on calling SMG$ entry points, as well as Curses functions, must continue to use the OpenVMS Curses implementation. The BSD-based Curses implementation is not interoperable with the old implementation. Attempts to mix calls to the new functions and the old functions will result in incorrect output displayed on the screen and could result in an exception from an SMG$ routine. 6.2 Curses Overview Curses, the Compaq C Screen Management Package, is composed of Compaq C RTL functions and macros that create and modify defined sections of the terminal screen and optimize cursor movement. Using the screen management package, you can develop a user interface that is both visually attractive and user-friendly. Curses is terminal-independent and provides simplified terminal screen formatting and efficient cursor movement. Most Curses functions and macros are listed in pairs where the first routine is a macro and the second is a function beginning with the prefix "w," for "window." These prefixes are delimited by brackets ([ ]). For example, [w]addstr designates the addstr macro and the waddstr function. The 6-2 Curses Screen Management Functions and Macros macros default to the window stdscr; the functions accept a specified window as an argument. To access the Curses functions and macros, include the header file. The terminal-independent Screen Management Software, which is part of the OpenVMS RTL, is used to implement Curses. For portability purposes, most functions and macros are designed to perform in a manner similar to other C implementations. However, the Curses routines depend on the OpenVMS system and its Screen Management Software, so performance of some functions and macros could differ slightly from those of other implementations. Some functions and macros available on other systems are not available with the Compaq C RTL Curses package. Some functions, such as [w]clrattr, [w]insstr, mv[w]insstr, and [w]setattr are specific to Compaq C for OpenVMS Systems and are not portable. Table 6-1 lists all of the Curses functions and macros found in the Compaq C RTL. For more detailed information on each function and macro, see the Reference Section. Table_6-1_Curses_Functions_and_Macros______________________ Function or Macro____________Description_______________________________ [w]addch Adds a character to the window at the current position of the cursor. [w]addstr Adds a string to the window at the current position of the cursor. box Draws a box around the window. [w]clear Erases the contents of the specified window and resets the cursor to coordinates (0,0). clearok Sets the clear flag for the window. (continued on next page) Curses Screen Management Functions and Macros 6-3 Table_6-1_(Cont.)_Curses_Functions_and_Macros______________ Function or Macro____________Description_______________________________ [w]clrattr Deactivates the video display attribute within the window. [w]clrtobot Erases the contents of the window from the current position of the cursor to the bottom of the window. [w]clrtoeol Erases the contents of the window from the current cursor position to the end of the line on the specified window. [no]crmode Sets and unsets the terminal from cbreak mode. [w]delch Deletes the character on the specified window at the current position of the cursor. [w]deleteln Deletes the line at the current position of the cursor. delwin Deletes the specified window from memory. [no]echo Sets the terminal so that characters may or may not be echoed on the terminal screen. endwin Clears the terminal screen and frees any virtual memory allocated to Curses data structures. [w]erase Erases the window by painting it with blanks. [w]getch Gets a character from the terminal screen and echoes it on the specified window. [w]getstr Gets a string from the terminal screen, stores it in a character variable, and echoes it on the specified window. getyx Puts the (y,x) coordinates of the current cursor position on the window in the variables y and x. (continued on next page) 6-4 Curses Screen Management Functions and Macros Table_6-1_(Cont.)_Curses_Functions_and_Macros______________ Function or Macro____________Description_______________________________ [w]inch Returns the character at the current cursor position on the specified window without making changes to the window. initscr Initializes the terminal-type data and all screen functions. [w]insch Inserts a character at the current cursor position in the specified window. [w]insertln Inserts a line above the line containing the current cursor position. [w]insstr Inserts a string at the current cursor position on the specified window. leaveok Leaves the cursor at the current coordinates after an update to the window. longname Assigns the full terminal name to a character name that must be large enough to hold the character string. [w]move Changes the current cursor position on the specified window. mv[w]addch Moves the cursor and adds a character to the specified window. mv[w]addstr Moves the cursor and adds a string to the specified window. mvcur Moves the terminal's cursor. mv[w]delch Moves the cursor and deletes a character on the specified window. mv[w]getch Moves the cursor, gets a character from the terminal screen, and echoes it on the specified window. mv[w]getstr Moves the cursor, gets a string from the terminal screen, stores it in a variable, and echoes it on the specified window. (continued on next page) Curses Screen Management Functions and Macros 6-5 Table_6-1_(Cont.)_Curses_Functions_and_Macros______________ Function or Macro____________Description_______________________________ mv[w]inch Moves the cursor and returns the character on the specified window without making changes to the window. mv[w]insch Moves the cursor and inserts a character in the specified window. mv[w]insstr Moves the cursor and inserts a string in the specified window. mvwin Moves the starting position of the window to the specified coordinates. newwin Creates a new window with lines and columns starting at the coordinates on the terminal screen. [no]nl Provided only for UNIX software compatibility and has no functionality in the OpenVMS environment. overlay Writes the contents of one window that will fit over the contents of another window, beginning at the starting coordinates of both windows. overwrite Writes the contents of one window, insofar as it will fit, over the contents of another window beginning at the starting coordinates of both windows. [w]printw Performs a printf on the window starting at the current position of the cursor. [no]raw Provided only for UNIX software compatibility and has no functionality in the OpenVMS environment. [w]refresh Repaints the specified window on the terminal screen. [w]scanw Performs a scanf on the window. (continued on next page) 6-6 Curses Screen Management Functions and Macros Table_6-1_(Cont.)_Curses_Functions_and_Macros______________ Function or Macro____________Description_______________________________ scroll Moves all the lines on the window up one line. scrollok Sets the scroll flag for the specified window. [w]setattr Activates the video display attribute within the window. [w]standend Deactivates the boldface attribute for the specified window. [w]standout Activates the boldface attribute of the specified window. subwin Creates a new subwindow with lines and columns starting at the coordinates on the terminal screen. touchwin Places the most recently edited version of the specified window on the terminal screen. wrapok OpenVMS Curses only. Allows the wrapping of a word from the right border of the _________________window_to_the_beginning_of_the_next_line._ 6.3 Curses Terminology This section explains some of the Curses terminology and shows you how Curses looks on the terminal screen. Consider a Curses application as being a series of overlapping windows. Window overlapping is called occlusion. To distinguish the boundaries of these occluding windows, you can outline the rectangular windows with specified characters, or you can turn on the reverse video option (make the window a light background with dark writing). Curses Screen Management Functions and Macros 6-7 6.3.1 Predefined Windows (stdscr and curscr) Initially, two windows the size of the terminal screen are predefined by Curses. These windows are called stdscr and curscr. The stdscr window is defined for your use. Many Curses macros default to this window. For example, if you draw a box around stdscr, move the cursor to the left- corner area of the screen, write a string to stdscr, and then display stdscr on the terminal screen, your display will look like that in Figure 6-1. Figure 6-1 An Example of the stdscr Window The second predefined window, curscr, is designed for internal Curses work; it is an image of what is currently displayed on the terminal screen. The only Compaq C for OpenVMS Curses function that will accept this window as an argument is clearok. Do not write to or read from curscr. Use stdscr and user-defined windows for all your Curses applications. 6-8 Curses Screen Management Functions and Macros 6.3.2 User-Defined Windows You can occlude stdscr with your own windows. The size and location of each window is given in terms of the number of lines, the number of columns, and the starting position. The lines and columns of the terminal screen form a coordinate system, or grid, on which the windows are formed. You specify the starting position of a window with the (y,x) coordinates on the terminal screen where the upper left corner of the window is located. The coordinates (0,0) on the terminal screen, for example, are the upper left corner of the screen. The entire area of the window must be within the terminal screen borders; windows can be as small as a single character or as large as the entire terminal screen. You can create as many windows as memory allows. When writing to or deleting from windows, changes do not appear on the terminal screen until the window is refreshed. When refreshing a window, you place the updated window onto the terminal screen, which leaves the rest of the screen unaltered. All user-defined windows, by default, occlude stdscr. You can create two or more windows that occlude each other as well as stdscr. When writing data to one occluding window, the data is not written to the underlying window. You can create overlapping windows (called subwindows). A declared window must contain the entire area of its subwindow. When writing data to a subwindow or to the portion of the window overlapped by the subwindow, both windows contain the new data. For instance, if you write data to a subwindow and then delete that subwindow, the data is still present on the underlying window. If you create a window that occludes stdscr and a subwindow of stdscr, your terminal screen will look like Figure 6-2. Curses Screen Management Functions and Macros 6-9 Figure 6-2 Displaying Windows and Subwindows If you delete both the user-defined window and the subwindow, and then update the terminal screen with the new image, your terminal screen will look like Figure 6-3. 6-10 Curses Screen Management Functions and Macros Figure 6-3 Updating the Terminal Screen The string written on the window is deleted, but the string written on the subwindow remains on stdscr. 6.4 Getting Started with Curses There are commands that you must use to initialize and restore the terminal screen when using Curses Screen Management functions and macros. Also, there are predefined variables and constants on which Curses depends. Example 6-1 shows how to set up a program using Curses. Example 6-1 A Curses Program (continued on next page) Curses Screen Management Functions and Macros 6-11 Example 6-1 (Cont.) A Curses Program 1 #include 2 WINDOW *win1, *win2, *win3; main() { 3 initscr(); . . . endwin(); } Key to Example 6-1: 1 The preprocessor directive includes the header file, which defines the data structures and variables used to implement Curses. The header file includes the header file, so it is not necessary to duplicate this action by including again in the program source code. You must include to use any of the Curses functions or macros. 2 In the example, WINDOW is a data structure defined in . You must declare each user-specified window in this manner. In Example 6-1, the three defined windows are win1, win2, and win3. 3 The initscr and endwin functions begin and end the window editing session. The initscr function clears the terminal screen (OpenVMS Curses only; BSD-based Curses does not), and allocates space for the windows stdscr and curscr. The endwin function deletes all windows and clears the terminal screen. Most Curses users wish to define and modify windows. Example 6-2 shows you how to define and write to a single window. Example 6-2 Manipulating Windows (continued on next page) 6-12 Curses Screen Management Functions and Macros Example 6-2 (Cont.) Manipulating Windows #include WINDOW *win1, *win2, *win3; main() { initscr(); 1 win1 = newwin(24, 80, 0, 0); 2 mvwaddstr(win1, 2, 2, "HELLO"); . . . endwin(); } Key to Example 6-2: 1 The newwin function defines a window 24 rows high and 80 columns wide with a starting position at coordinates (0,0), the upper left corner of the terminal screen. The program assigns these attributes to win1. The coordinates are specified as follows: (lines,columns) or (y,x). 2 The mvwaddstr macro performs the same task as a call to the separate macros move and addstr. The mvwaddstr macro moves the cursor to the specified coordinates and writes a string onto stdscr. ________________________ Note ________________________ Most Curses macros update stdscr by default. Curses functions that update other windows have the same name as the macros but with the added prefix "w". For example, the addstr macro adds a given string to stdscr at the current cursor position. The waddstr function adds a given string to a specified window at the current cursor position. ______________________________________________________ Curses Screen Management Functions and Macros 6-13 When updating a window, specify the cursor position relative to the origin of the window, not the origin of the terminal screen. For example, if a window has a starting position of (10,10) and you want to add a character to the window at its starting position, specify the coordinates (0,0), not (10,10). The string HELLO in Example 6-2 does not appear on the terminal screen until you refresh the screen. You accomplish this by using the wrefresh function. Example 6-3 shows how to display the contents of win1 on the terminal screen. Example 6-3 Refreshing the Terminal Screen #include WINDOW *win1, *win2, *win3; main() { initscr(); win1 = newwin(22, 60, 0, 0); mvwaddstr(win1, 2, 2, "HELLO"); wrefresh(win1); . . . endwin(); } The wrefresh function updates just the region of the specified window on the terminal screen. When the program is executed, the string HELLO appears on the terminal screen until the program executes the endwin function. The wrefresh function only refreshes the part of the window on the terminal screen that is not overlapped by another window. If win1 was overlapped by another window and you want all of win1 to be displayed on the terminal screen, call the touchwin function. 6-14 Curses Screen Management Functions and Macros 6.5 Predefined Variables and Constants The header file defines variables and constants useful for implementing Curses (see Table 6-2). Table_6-2_Curses_Predefined_Variables_and_#define_Constants Name________Type______Description__________________________ curscr WINDOW * Window of current screen stdscr WINDOW * Default window LINES int Number of lines on the terminal screen COLS int Number of columns on the terminal screen ERR - Flag (0) for failed routines OK - Flag (1) for successful routines TRUE - Boolean true flag (1) FALSE - Boolean false flag (0) _BLINK - Parameter for setattr and clrattr _BOLD - Parameter for setattr and clrattr _REVERSE - Parameter for setattr and clrattr _UNDERLINE__-_________Parameter_for_setattr_and_clrattr____ For example, you can use the predefined macro ERR to test the success or failure of a Curses function. Example 6-4 shows how to perform such a test. Example 6-4 Curses Predefined Variables #include WINDOW *win1, *win2, *win3; (continued on next page) Curses Screen Management Functions and Macros 6-15 Example 6-4 (Cont.) Curses Predefined Variables main() { initscr(); win1 = newwin(10, 10, 1, 5); . . . if (mvwin(win1, 1, 10) == ERR) addstr("The MVWIN function failed."); . . . endwin(); } In Example 6-4, if the mvwin function fails, the program adds a string to stdscr that explains the outcome. The Curses mvwin function moves the starting position of a window. 6.6 Cursor Movement In the UNIX system environment, you can use Curses functions to move the cursor across the terminal screen. With other implementations, you can either allow Curses to move the cursor using the move function, or you can specify the origin and the destination of the cursor to the mvcur function, which moves the cursor in a more efficient manner. In Compaq C for OpenVMS Systems, the two functions are functionally equivalent and move the cursor with the same efficiency. Example 6-5 shows how to use the move and mvcur functions. 6-16 Curses Screen Management Functions and Macros Example 6-5 The Cursor Movement Functions #include main() { initscr(); . . . 1 clear(); 2 move(10, 10); 3 move(LINES/2, COLS/2); 4 mvcur(0, COLS-1, LINES-1, 0); . . . endwin(); } Key to Example 6-5: 1 The clear macro erases stdscr and positions the cursor at coordinates (0,0). 2 The first occurrence of move moves the cursor to coordinates (10,10). 3 The second occurrence of move uses the predefined variables LINES and COLS to calculate the center of the screen (by calculating the value of half the number of LINES and COLS on the screen). 4 The mvcur function forces absolute addressing. This function can address the lower left corner of the screen by claiming that the cursor is presently in the upper right corner. You can use this method if you are unsure of the current position of the cursor, but move works just as well. Curses Screen Management Functions and Macros 6-17 6.7 Program Example The following program example shows the effects of many of the Curses macros and functions. You can find explanations of the individual lines of code, if not self-explanatory, in the comments to the right of the particular line. Detailed discussions of the functions follow the source code listing. Example 6-6 shows the definition and manipulation of one user-defined window and stdscr. Example 6-6 stdscr and Occluding Windows /* CHAP_6_STDSCR_OCCLUDE.C */ /* This program defines one window: win1. win1 is */ /* located towards the center of the default window */ /* stdscr. When writing to an occluding window (win1) */ /* that is later erased, the writing is erased as well. */ #include /* Include header file. */ WINDOW *win1; /* Define windows. */ main() { char str[80]; /* Variable declaration.*/ initscr(); /* Set up Curses. */ noecho(); /* Turn off echo. */ /* Create window. */ win1 = newwin(10, 20, 10, 10); box(stdscr, '|', '-'); /* Draw a box around stdscr. */ box(win1, '|', '-'); /* Draw a box around win1. */ refresh(); /* Display stdscr on screen. */ wrefresh(win1); /* Display win1 on screen. */ 1 getstr(str); /* Pause. Type a few words! */ mvaddstr(22, 1, str); 2 getch(); /* Add string to win1. */ (continued on next page) 6-18 Curses Screen Management Functions and Macros Example 6-6 (Cont.) stdscr and Occluding Windows mvwaddstr(win1, 5, 5, "Hello"); wrefresh(win1); /* Add win1 to terminal scr. */ getch(); /* Pause. Press Return. */ delwin(win1); /* Delete win1. */ 3 touchwin(stdscr); /* Refresh all of stdscr. */ getch(); /* Pause. Press Return. */ endwin(); /* Ends session. */ } Key to Example 6-6: 1 The program waits for input. The echo was disabled using the noecho macro, so the words that you type do not appear on stdscr. However, the macro stores the words in the variable str for use elsewhere in the program. 2 The getch macro causes the program to pause. When you are finished viewing the screen, press Return so the program can resume. The getch macro refreshes stdscr on the terminal screen without calling refresh. The screen appears like Figure 6-4. Curses Screen Management Functions and Macros 6-19 Figure 6-4 An Example of the getch Macro 3 The touchwin function refreshes the screen so that all of stdscr is visible and the deleted occluding window no longer appears on the screen. 6-20 Curses Screen Management Functions and Macros 7 _________________________________________________________________ Math Functions Table 7-1 lists and describes the math functions in the Compaq C Run-Time Library (RTL). For more detailed information on each function, see the Reference Section. Table_7-1_Math_Functions___________________________________ Function_________Description_______________________________ abs Returns the absolute value of an integer. acos Returns a value in the range 0 to , which is the arc cosine of its radian argument. asin Returns a value in the range -/2 to /2, which is the arc sine of its radian argument. atan Returns a value in the range -pi/2 to /2, which is the arc tangent of its radian argument. atan2 Returns a value in the range -pi to , which is the arc tangent of y/x where y and x are the two arguments. cabs Returns: sqrt ( x * x + y * y ). ceil Returns (as a double) the smallest integer that is greater than or equal to its argument. cos Returns the cosine of its radian argument. cot Returns the cotangent of its radian argument. cosh Returns the hyperbolic cosine of its argument. (continued on next page) Math Functions 7-1 Table_7-1_(Cont.)_Math_Functions___________________________ Function_________Description_______________________________ drand48, Generates uniformly distributed erand48, pseudorandom number sequences. Returns jrand48, 48-bit, nonnegative, double-precision lrand48, floating-point values. mrand48, nrand48 exp Returns the base e raised to the power of the argument. fabs Returns the absolute value of a floating- point value. floor Returns (as a double) the largest integer that is less than or equal to its argument. fmod Computes the floating-point remainder of the first argument to fmod divided by the second. frexp Calculates the fractional and exponent parts of a double value. hypot Returns the square root of the sum of the squares of two arguments. initstate Initializes random number generators. labs Returns the absolute value of an integer as a long int. lcong48 Initializes a 48-bit uniformly distributed pseudorandom number sequence. llabs, qabs Returns the absolute value of an __int64 (Alpha only) integer. ldexp Returns its first argument multiplied by 2 raised to the power of its second argument. ldiv, div Returns the quotient and remainder after the division of their arguments. (continued on next page) 7-2 Math Functions Table_7-1_(Cont.)_Math_Functions___________________________ Function_________Description_______________________________ lldiv, qdiv Returns the quotient and remainder after (Alpha only) the division of their arguments. log, log 10 Returns the logarithm of their arguments. modf Returns the positive fractional part of its first argument and assigns the integral part, expressed as a double, to the object whose address is specified by the second argument. pow Returns the first argument raised to the power of the second argument. rand, srand Returns pseudorandom numbers in the range 0 to 231-1. random, srandom Generates pseudorandom numbers in a more random sequence. seed48, srand48 Initializes a 48-bit random number generator. setstate Restarts, and changes random number generators. sin Returns the sine of its radian argument. sinh Returns the hyperbolic sine of its argument. sqrt Returns the square root of its argument. tan Returns a double value that is the tangent of its radian argument. tanh Returns a double value that is the _________________hyperbolic_tangent_of_its_double_argument. 7.1 Math Function Variants-float, double, long double The following additional Compaq C RTL math routines are supported for Compaq C on OpenVMS Alpha systems only. They are defined in . Many of them are float, double, and long double variants of the routines listed in the preceding table. See the Compaq Portable Mathematics Library (DPML) manual for descriptions of these routines. Math Functions 7-3 Note that for programs compiled without /L_DOUBLE=64 (that is, compiled with the default /L_DOUBLE=128), the long double variants of these Compaq C RTL math routines map to the X_FLOAT entry points documented in the DPML manual. acosd cbrt expm1l ldexpl scalbf acosdf cbrtf fabsf lgamma scalbl acosdl cbrtl fabsl lgammaf sind acosf ceilf fabsl lgammal sindf acosl ceill finite log10f sindl acosh copysign finitef log10l sinf acoshf copysignf finitel log1p sinl acoshl copysignl floorf log1pf sinhf asind cosd floorl log1pl sinhl asindf cosdf fmodf log2 sqrtf asindl cosdl fmodl log2f sqrtl asinf cosf fp_class log2l tand asinl cosl fp_classf logb tandf asinh coshf fp_classl logbf tandl asinhf coshl frexpf logbl tanf asinhl cot frexpl logf tanl atan2f cotd hypotf logl tanhf atan2l cotdf hypotl modff tanhl atand cotdl isnan modfl trunc atand2 cotf isnanf nextafter truncf atand2f cotl isnanl nextafterf truncl atand2l erf j0 nextafterl unordered atandf erfc j0f nint unorderedf atandl erfcf j0l nintf unorderedl atanf erfcl j1 nintl y0 atanl erff j1f powf y0f atanh erfl j1l powl y0l atanhf expf jn rint y1 atanhl expl jnf rintf y1f cabsf expm1 jnl rintl y1l cabsl expm1f ldexpf scalb yn ynf ynl 7-4 Math Functions 7.2 Error Detection To help you detect run-time errors, the header file defines the following two symbolic values that are returned by many (but not all) of the mathematical functions: o EDOM indicates that an argument is inappropriate; the argument is not within the function's domain. o ERANGE indicates that a result is out of range; the argument is too large or too small to be represented by the machine. When using the math functions, you can check the external variable errno for either or both of these values and take the appropriate action if an error occurs. The following program example checks the variable errno for the value EDOM, which indicates that a negative number was specified as input to the function sqrt: #include #include #include main() { double input, square_root; printf("Enter a number: "); scanf("%le", &input); errno = 0; square_root = sqrt(input); if (errno == EDOM) perror("Input was negative"); else printf("Square root of %e = %e\n", input, square_root); } If you did not check errno for this symbolic value, the sqrt function returns 0 when a negative number is entered. For more information about the header file, see Chapter 4. Math Functions 7-5 7.3 The Header File The header file implements some of the features defined by the Numerical C Extensions Group of the ANSI X3J11 committee. You might find this useful for applications that make extensive use of floating-point functions. Some of the double-precision functions listed in this chapter return the value ±HUGE_VAL (defined in either or ) if the result is out of range. The float version of those functions return the value HUGE_VALF (defined only in ) for the same conditions. The long double version returns the value HUGE_VALL (also defined in ). For programs compiled to enable IEEE infinity and NaN values, the values HUGE_VAL, HUGE_VALF, and HUGE_VALL are expressions, not compile-time constants. Initializations such as the following cause a compile-time error: $ CREATE IEEE_INFINITY.C #include double my_huge_val = HUGE_VAL ^Z $ CC /FLOAT=IEEE/IEEE=DENORM IEEE_INFINITY double my_huge_val = HUGE_VAL; .....................^ %CC-E-NEEDCONSTEXPR, In the initializer for my_huge_val, "decc$gt_dbl_infinity" is not constant, but occurs in a context that requires a constant expression. at line number 3 in file WORK1$:[RTL]IEEE_INFINITY.C;1 $ When using both and , be aware that defines a function isnan and defines a macro by the same name. Whichever header is included first in the application will resolve a reference to isnan. 7-6 Math Functions 7.4 Example Example 7-1 shows how the tan, sin, and cos functions operate. Example 7-1 Calculating and Verifying a Tangent Value /* CHAP_7_MATH_EXAMPLE.C */ /* This example uses two functions --- mytan and main --- */ /* to calculate the tangent value of a number, and to check */ /* the calculation using the sin and cos functions. */ #include #include /* This function calculates the tangent using the sin and */ /* cos functions. */ double mytan(x) double x; { double y, y1, y2; y1 = sin(x); y2 = cos(x); if (y2 == 0) y = 0; else y = y1 / y2; return y; } main() { double x; /* Print values: compare */ for (x = 0.0; x < 1.5; x += 0.1) printf("tan of %4.1f = %6.2f\t%6.2f\n", x, mytan(x), tan(x)); } Math Functions 7-7 Example 7-1 produces the following output: $ RUN EXAMPLE tan of 0.0 = 0.00 0.00 tan of 0.1 = 0.10 0.10 tan of 0.2 = 0.20 0.20 tan of 0.3 = 0.31 0.31 tan of 0.4 = 0.42 0.42 tan of 0.5 = 0.55 0.55 tan of 0.6 = 0.68 0.68 tan of 0.7 = 0.84 0.84 tan of 0.8 = 1.03 1.03 tan of 0.9 = 1.26 1.26 tan of 1.0 = 1.56 1.56 tan of 1.1 = 1.96 1.96 tan of 1.2 = 2.57 2.57 tan of 1.3 = 3.60 3.60 tan of 1.4 = 5.80 5.80 $ 7-8 Math Functions 8 _________________________________________________________________ Memory Allocation Functions Table 8-1 lists and describes all the memory allocation functions found in the Compaq C Run-Time Library (RTL). For a more detailed description of each function, see the Reference Section. Table_8-1_Memory_Allocation_Functions______________________ Function_________Description_______________________________ brk, sbrk Determine the lowest virtual address that is not used with the program. calloc, malloc Allocate an area of memory. cfree, free Make available for reallocation the area allocated by a previous calloc, malloc, or realloc call. realloc Changes the size of the area pointed to by the first argument to the number of bytes given by the second argument. strdup___________Finds_and_points_to_a_duplicate_string.___ All Compaq C RTL functions requiring additional storage from the heap get that storage using the Compaq C RTL memory allocation functions malloc, calloc, realloc, free, and cfree. Memory allocated by these functions is quadword- aligned. The ANSI C standard does not include cfree. For this reason, it is preferable to free memory using the functionally equivalent free function. The brk and sbrk functions assume that memory can be allocated contiguously from the top of your address space. However, the malloc function and RMS may allocate space from this same address space. You should not use the brk Memory Allocation Functions 8-1 and sbrk functions in conjunction with RMS and Compaq C RTL routines that use malloc. Previous versions of the VAX C RTL documentation indicated that the memory allocation routines used the OpenVMS RTL functions LIB$GET_VM and LIB$FREE_VM to acquire and return dynamic memory. This is no longer the case; interaction between these routines and the Compaq C RTL memory allocation routines is no longer problematic (although LIB$SHOW_VM can no longer be used to track Compaq C RTL malloc and free usage). The Compaq C RTL memory allocation functions calloc, malloc, realloc, and free are based on the LIB$ routines LIB$VM_CALLOC, LIB$VM_MALLOC, LIB$VM_REALLOC and LIB$VM_ FREE, respectively. The routines VAXC$CALLOC_OPT, VAXC$CFREE_OPT, VAXC$FREE_ OPT, VAXC$MALLOC_OPT, and VAXC$REALLOC_OPT are now obsolete and should not be used in new development. However, versions of these routines that are equivalent to the standard C memory allocation routines are provided for backward compatibility. 8.1 Program Example Example 8-1 shows the use of the malloc, calloc, and free functions. Example 8-1 Allocating and Deallocating Memory for Structures /* CHAP_8_MEM_MANAGEMENT.C */ /* This example takes lines of input from the terminal until */ /* it encounters a Ctrl/Z, places the strings into an */ /* allocated buffer, copies the strings to memory allocated for */ /* structures, prints the lines back to the screen, and then */ /* deallocates all the memory used for the structures. */ #include #include #define MAX_LINE_LENGTH 80 (continued on next page) 8-2 Memory Allocation Functions Example 8-1 (Cont.) Allocating and Deallocating Memory for Structures struct line_rec { /* Declare the structure. */ struct line_rec *next; /* Pointer to next line. */ char *data; /* A line from terminal. */ }; int main(void) { char *buffer; /* Define pointers to */ /* structure (input lines). */ struct line_rec *first_line = NULL, *next_line, *last_line = NULL; /* Buffer points to memory. */ buffer = malloc(MAX_LINE_LENGTH); if (buffer == NULL) { /* If error ... */ perror("malloc"); exit(EXIT_FAILURE); } while (gets(buffer) != NULL) { /* While not Ctrl/Z ... */ /* Allocate for input line. */ next_line = calloc(1, sizeof (struct line_rec)); if (next_line == NULL) { perror("calloc"); exit(EXIT_FAILURE); } /* Put line in data area. */ next_line->data = buffer; if (last_line == NULL) /* Reset pointers. */ first_line = next_line; else last_line->next = next_line; (continued on next page) Memory Allocation Functions 8-3 Example 8-1 (Cont.) Allocating and Deallocating Memory for Structures last_line = next_line; /* Allocate space for the */ /* next input line. */ buffer = malloc(MAX_LINE_LENGTH); if (buffer == NULL) { perror("malloc"); exit(EXIT_FAILURE); } } free(buffer); /* Last buffer always unused. */ next_line = first_line; /* Pointer to beginning. */ while (next_line != NULL) { puts(next_line->data); /* Write line to screen. */ free(next_line->data); /* Deallocate a line. */ last_line = next_line; next_line = next_line->next; free(last_line); } exit(EXIT_SUCCESS); } The sample input and output for Example 8-1 are as follows: $ RUN EXAMPLE line one line two EXIT line one line two $ 8-4 Memory Allocation Functions 9 _________________________________________________________________ System Functions The C programming language is a good choice if you wish to write operating systems. For example, much of the UNIX operating system is written in C. When writing system programs, it is sometimes necessary to retrieve or modify the environment in which the program is running. This chapter describes the Compaq C Run-Time Library (RTL) functions that accomplish this and other system tasks. Table 9-1 lists and describes all the system functions found in the Compaq C RTL. For a more detailed description of each function, see the Reference Section. Table_9-1_System_Functions_________________________________ Function_________Description_______________________________ System_Functions-Searching_and_Sorting_Utilities___________ bsearch Performs a binary search on an array of sorted objects for a specified object. qsort Sorts an array of objects in place by implementing the quick-sort algorithm. ___________________________________________________________ System_Functions-Retrieving_Process_Information____________ ctermid Returns a character string giving the equivalence string of SYS$COMMAND, which is the name of the controlling terminal. cuserid Returns a pointer to a character string containing the name of the user who initiated the current process. (continued on next page) System Functions 9-1 Table_9-1_(Cont.)_System_Functions_________________________ Function_________Description_______________________________ System_Functions-Retrieving_Process_Information____________ getcwd Returns a pointer to the file specification for the current working directory. getegid, Returns, in OpenVMS terms, group geteuid, and member numbers from the user getgid, getuid identification code (UIC). getenv Searches the environment array for the current process and returns the value associated with a specified environment. getlogin Gets the login name of the user associated with the current session. getpid Returns the process ID of the current process. getppid Returns the parent process ID of the calling process. getpwnam Accesses user-name information in the user database. getpwuid Accesses user-ID information in the user database. ___________________________________________________________ System_Functions-Changing_Process_Information______________ chdir Changes the default directory. chmod Changes the file protection of a file. chown Changes the owner user identification code (UIC) of a file. mkdir Creates a directory. nice Increases or decreases the process priority to the process base priority by the amount of the argument. putenv Sets an environmental variable. (continued on next page) 9-2 System Functions Table_9-1_(Cont.)_System_Functions_________________________ Function_________Description_______________________________ System_Functions-Changing_Process_Information______________ setenv Inserts or resets the environment variable name in the current environment list. setgid, setuid Implemented for program portability and have no functionality. sleep, usleep Suspends the execution of the current process for at least the number of seconds indicated by its argument. umask Creates a file protection mask that is used whenever a new file is created. It returns the old mask value. ___________________________________________________________ System Functions-Retrieving and Converting Date/Time Information________________________________________________ asctime Converts a broken-down time into a 26- character string. clock Determines the CPU time (in microseconds) used since the beginning of the program execution. ctime Converts a time, in seconds, to an ASCII string in the form generated by the asctime function. decc$fix_time Converts OpenVMS binary system times to UNIX binary times. difftime Computes the difference, in seconds, between the two times specified by its arguments. ftime Returns the elapsed time since 00:00:00, January 1, 1970, in the structure timeb. getclock Gets the current value of the system-wide clock. (continued on next page) System Functions 9-3 Table_9-1_(Cont.)_System_Functions_________________________ Function_________Description_______________________________ System Functions-Retrieving and Converting Date/Time Information________________________________________________ getdate Converts a formatted string to a time/date structure. getitimer Returns the value of interval timers. gettimeofday Gets date and time. gmtime Converts time units to broken-down UTC time. localtime Converts a time (expressed as the number of seconds elapsed since 00:00:00, January 1, 1970) into hours, minutes, seconds, and so on. mktime Converts a local-time structure into time since the Epoch. setitimer Sets the value of interval timers. strftime, Places characters into an array, as wcsftime controlled by a specified format string. strptime Converts a character string into date and time values. time Returns the time elapsed since 00:00:00, January 1, 1970, in seconds. times Returns the accumulated times of the current process and of its terminated child processes. tzset Sets and accesses time-zone conversion. ualarm Sets or changes the timeout of interval timers. wcsftime Uses date and time information stored in a tm structure to create a wide-character output string. (continued on next page) 9-4 System Functions Table_9-1_(Cont.)_System_Functions_________________________ Function_________Description_______________________________ System_Functions-Miscellaneous_____________________________ VAXC$CRTL_INIT Initializes the run-time environment and establishes an exit and condition handler, which makes it possible for Compaq C RTL functions to be called from other _________________languages.________________________________ Example 9-1 shows how the cuserid function is used. Example 9-1 Accessing the User Name /* CHAP_9_GET_USER.C */ /* Using cuserid, this program returns the user name. */ #include main() { static char string[L_cuserid]; cuserid(string); printf("Initiating user: %s\n", string); } If a user named TOLLIVER runs the program, the following is displayed on stdout: $ RUN EXAMPLE1 Initiating user: TOLLIVER Example 9-2 shows how the getenv function is used. System Functions 9-5 Example 9-2 Accessing Terminal Information /* CHAP_9_GETTERM.C */ /* Using getenv, this program returns the terminal. */ #include #include main() { printf("Terminal type: %s\n", getenv("TERM")); } Running Example 9-2 on a Compaq VT100 terminal in 132- column mode displays the following: $ RUN EXAMPLE3 Terminal type: vt100-132 Example 9-3 shows how to use getenv to find the user's default login directory and how to use chdir to change to that directory. 9-6 System Functions Example 9-3 Manipulating the Default Directory /* CHAP_9_CHANGE_DIR.C */ /* This program performs the equivalent of the DCL command */ /* SET DEFAULT SYS$LOGIN. However, once the program exits, the */ /* directory is reset to the directory from which the program */ /* was run. */ #include #include #include main() { char *dir; int i; dir = getenv("HOME"); if ((i = chdir(dir)) != 0) { perror("Cannot set directory"); exit(0); } printf("Current directory: %s\n", dir); } Running Example 9-3 displays the following: $ RUN EXAMPLE4 Current directory: dba0:[tolliver] $ Example 9-4 shows how to use the time, localtime, and strftime functions to print the correct date and time at the terminal. Example 9-4 Printing the Date and Time /* CHAP_9_DATE_TIME.C */ /* The time function returns the time in seconds; the localtime */ /* function converts the time to hours, minutes, and so on; */ /* the strftime function uses these values to obtain a string */ /* in the desired format. */ (continued on next page) System Functions 9-7 Example 9-4 (Cont.) Printing the Date and Time #include #include #define MAX_STRING 80 main() { struct tm *time_structure; time_t time_val; char output_str[MAX_STRING]; time(&time_val); time_structure = localtime(&time_val); /* Print the date */ strftime(output_str, MAX_STRING, "Today is %A, %B %d, %Y", time_structure); printf("%s\n", output_str); /* Print the time using a 12-hour clock format. */ strftime(output_str, MAX_STRING, "The time is %I:%M %p", time_structure); printf("%s\n", output_str); } Running Example 9-4 displays the following: $ RUN EXAMPLE5 Today is Thursday, May 20, 1993 The time is 10:18 AM $ 9-8 System Functions 10 _________________________________________________________________ Developing International Software This chapter describes typical features of international software and the features provided with the Compaq C Run- Time Library (RTL) that enable you to design and implement international software. See the Reference Section for more detailed information on the functions described in this chapter. 10.1 Internationalization Support The Compaq C RTL has added capabilities to allow application developers to create international software. The Compaq C RTL obtains information about a language and a culture by reading this information from locale files. 10.1.1 Installation If you are using these Compaq C RTL capabilities, you must install a separate kit to provide these files to your system. The save set, VMSI18N0nn, is provided on the same media as the OpenVMS operating system. To install this save set, follow the standard OpenVMS installation procedures using this save set name as the name of the kit. There are several categories of locales that you can select to install. You can select as many locales as you need by answering the following prompts: Do you want European and US support? Do you want Chinese support? Do you want Japanese support? Do you want Korean support? Do you want Thai support? Do you want the Unicode converters? Developing International Software 10-1 This kit also has an Installation Verification Procedure that Compaq recommends you run to verify the correct installation of the kit. 10.1.2 Unicode Support In OpenVMS Version 7.2, the Compaq C Run-Time Library added the Universal Unicode locale, which is distributed with the OpenVMS system, not with the VMSI18N0nn kit. The name of the Unicode locale is: UTF8-20 Like those locales shipped with the VMSI18N0nn kit, the Unicode locale is located at the standard location referred to by the SYS$I18N_LOCALE logical name. The UTF8-20 Unicode is based on Unicode standard Version V2.0. The Unicode locale uses UCS-4 as wide-character encoding and UTF-8 as multibyte character encoding. Compaq C RTL also includes converters that perform conversions between Unicode and any other supported character sets. The expanded set of converters includes converters for UCS-2, UCS-4, and UTF-8 Unicode encoding. The Unicode converters can be used by the ICONV CONVERT utility and by the iconv family of functions in the Compaq C Run-Time Library. In OpenVMS Version 7.2, the Compaq C Run-Time Library added Unicode character set converters for Microsoft Code Page 437. 10.2 Features of International Software International software is software that can support multiple languages and cultures. An international program should be able to: o Display messages in the user's own language. This includes screen displays, error messages and prompts. o Handle culture-specific information such as: - Date and time formatting 10-2 Developing International Software The conventions for representing dates and times vary from one country to another. For example, in the U.S.A., the month is given first; in the U.K the day is specified first. Therefore, the date 12/5/1993 is interpreted as December 5, 1993 in the U.S.A., and as May 12,1993 in the U.K. - Numeric formatting The character that represents the decimal point (the radix character) and the thousands separator character vary from one country to another. For example, in the U.K. the period (.) is used to represent the radix character, and the comma is used as a separator. However, in Germany, the comma is used as the radix character and the period is the separator character. Therefore, the number 2,345.67 in the U.K. is the same as 2.345,67 in Germany. - Monetary formatting Currency values are represented by different symbols and can be formatted using a variety of separator characters, depending on the currency. o Handle different coded character sets (not just ASCII). o Handle a mixture of single and multibyte characters. o Provide multipass string comparisons. String comparison functions such as strcmp compare strings by comparing the codepoint values of the characters in the strings. However, some languages require more complex comparisons to correctly sort strings. To meet the above requirements, an application should not make any assumptions about the language, local customs or the coded character set used. All this localization data should be defined separately from the program, and only bound to it at run-time. The rest of the chapter describes how you can create international software using Compaq C. Developing International Software 10-3 10.3 Developing International Software Using Compaq C The Compaq C environment provides the following facilities for creating international software: o A method for separating localization data from a program. Localization data is held in a database known as a locale. This stores all the language and culture information required by a program. See Section 10.4 for details of the structure of locales. A program specifies what locales to use by calling the setlocale function. See Section 10.5 for more information. o A method of separating message text from the program source. This is achieved using message catalogs that store all the messages for an application. The message catalog is linked to the application at run-time. This means that the messages can be translated into different languages and then the required language version is selected at run-time. See Section 10.6. o Compaq C RTL functions that are sensitive to localization data. The Compaq C RTL includes functions for: - Converting between different codesets. See Section 10.7. - Handling culture-specific information. See Section 10.8. - Multipass string collation. See Section 10.10. o A special wide-character data type defined in the Compaq C RTL makes it easier to handle codesets that have a mixture of single and multibyte characters. A set of functions is also defined to support this wide character data type. See Section 10.9. 10-4 Developing International Software 10.4 Locales A locale consists of different categories, each of which determines one aspect of the international environment. Table 10-1 lists the categories in a locale and describes the information in each. Table_10-1_Locale_Categories_______________________________ Category_________Description_______________________________ LC_COLLATE Contains information about collating sequences. LC_CTYPE Contains information about character classification. LC_MESSAGES Defines the answers that are expected in response to yes/no prompts. LC_MONETARY Contains monetary formatting information. LC_NUMERIC Contains information about formatting numbers. LC_TIME__________Contains_time_and_date_information._______ The locales provided by Compaq reside in the directory defined by the SYS$I18N_LOCALE logical name. The file naming convention for locales is: language_country_codeset.locale Where: o language is the mnemonic for the language. For example, EN indicates an English locale. o country is the mnemonic for the country. For example, GB indicates a British locale. o codeset is the name of the ISO standard codeset for the locale. For example, ISO8859-1 is the ISO 8859 codeset for the Western European languages. See Section 10.7 for more information about the codesets supported. Developing International Software 10-5 10.5 Using the setlocale Function to Set Up an International Environment An application sets up its international environment at run-time by calling the setlocale function. The international environment is set up in one of two ways: o The environment is defined by one locale. In this case, each of the locale categories is defined by the same locale. o Categories are defined separately. This lets you define a mixed environment that uses different locales depending on the operation performed. For example, if an English user has some Spanish files that are to be processed by an application, the LC_COLLATE category could be defined by a Spanish locale while the other categories are defined by an English locale. To do this you would call setlocale once for each category. The syntax for the setlocale function is: char *setlocale(int category, const char *locale) Where: o category is either the name of a category, or LC_ALL. Specifying LC_ALL means that all the categories are defined by the same locale. Specify a category name to set up a mixed environment. o locale is one of the following: - The name of the locale to use. If you want users to specify the locale interactively, your application could prompt the user for a locale name, and then pass the name as an argument to the setlocale function. A locale name has the following format: language_country.codeset[@modifier] For example, setlocale(LC_COLLATE, "en_US.ISO8859-1") selects the locale en_US.ISO8859-1 for the LC_COLLATE category. - "" 10-6 Developing International Software This causes the function to use logical names to determine the locale for the category specified. See Specifying the Locale Using Logical Names for details. If an application does not call the setlocale function, the default locale is the C locale. This allows such applications to call those functions that use information in the current locale. Specifying the Locale Using Logical Names If the setlocale function is called with "" as the locale argument, the function checks for a number of logical names to determine the locale name for the category specified. There are a number of logical names that users can set up to define their international environment: o Logical name corresponding to a category For example, the LC_NUMERIC logical name defines the locale associated with the LC_NUMERIC category within the user's environment. o LC_ALL o LANG The LANG logical name defines the user's language. In addition to the logical names defined by a user, there are a number of system-wide logical names, set up during system startup, that define the default international environment for all users on a system: o SYS$category Where category is the name of a category. This specifies the system default for that category. o SYS$LC_ALL o SYS$LANG The setlocale function checks for user-defined logical names first, and if these are not defined, it checks the system logical names. Developing International Software 10-7 10.6 Using Message Catalogs An important requirement for international software is that it should be able to communicate with the user in the user's own language. The messaging system enables program messages to be created separately from the program source, and linked to the program at run-time. Messages are defined in a message text source file, and compiled into a message catalog using the GENCAT command. The message catalog is accessed by a program using the functions provided in the Compaq C RTL. The functions provided to access the messages in a catalog are: o The catopen function, which opens a specified catalog ready for use. o The catgets function, which enables the program to read a specific message from a catalog. o The catclose function, which closes a specified catalog. Open message catalogs are also closed by the exit function. For information on generating message catalogs, see the GENCAT command description in the OpenVMS system documentation. 10.7 Handling Different Character Sets The Compaq C RTL supports a number of state-independent codesets and codeset encoding schemes that contain the ASCII encoded Portable Character Set. It does not support state-dependent codesets. The codesets supported are: o ISO8859-n where n = 1,2,5,7,8 or 9. This covers codesets for North America, Europe (West and East), Israel, and Turkey. o eucJP, SJIS, DECKANJI, SDECKANJI: Codesets used in Japan. o eucTW, DECHANYU, BIG5, DECHANZI: Chinese codesets used in China (PRC), Hong-Kong, and Taiwan. o DECKOREAN: Codeset used in Korea. 10-8 Developing International Software 10.7.1 Charmap File The characters in a codeset are defined in a charmap file. The charmap files supplied by Compaq are located in the directory defined by the SYS$I18N_LOCALE logical name. The file type for a charmap file is .CMAP. 10.7.2 Converter Functions As well as supporting different coded character sets, the Compaq C RTL provides the following converter functions that enable you to convert characters from one codeset to another: o iconv_open-specifies the type of conversion. It allocates a conversion descriptor required by the iconv function. o iconv-converts characters in a file to the equivalent characters in a different codeset. The converted characters are stored in a separate file. o iconv_close-deallocates a conversion descriptor and the resources allocated to the descriptor. 10.7.3 Using Codeset Converter Files The file naming convention for codeset converters is: fromcode_tocode.iconv Where fromcode is the name of the source codeset, and tocode is the name of the codeset to which characters are converted. You can add codeset converters to a given system by installing the converter files in the directory pointed by the logical name SYS$I18N_ICONV. Codeset converter files can be implemented either as table- based conversion files or as algorithm-based converter files created as OpenVMS shareable images. Developing International Software 10-9 Creating a Table-based Conversion File The following summarizes the necessary steps to create a table-based codeset converter file: 1. Create a text file that describes the mapping between any character from the source codeset to the target codeset. For the format of this file, see the DCL command ICONV COMPILE in the OpenVMS New Features Manual, which processes such a file and creates a codeset converter table file. 2. Copy the resulting file from the previous step to the directory pointed by the logical SYS$I18N_ICONV, assuming you have the privilege to do so. Creating an Algorithm-based Conversion File Use the following steps to create an algorithm-based codeset converter file implemented as a shareable image: 1. Create C source files that implement the codeset converter. The API is documented in the public header file as follows: o The universal entry point _u_iconv_open is called by the Compaq C RTL routine iconv_open to initialize a conversion. o _u_iconv_open returns to iconv_open a pointer to the structure __iconv_extern_obj_t. o Within this structure, the converter exports its own conversion entry point and conversion close routine, which are called by the Compaq C RTL routines iconv and iconv_close, respectively. o The major and minor identifier fields are required by iconv_open to test for a possible mismatch between the library and the converter. The converter usually assigns the constants __ICONV_MAJOR and __ICONV_ MINOR, defined in the header file. o The field tcs_mb_cur_max is used only by the DCL command ICONV CONVERT to optimize its buffer usage. This field reflects the maximum number of bytes that comprise a single character in the target codeset, including the shift sequence (if any). 10-10 Developing International Software 2. Compile and link the modules that comprise the codeset converter as an OpenVMS shareable image, making sure that the file name adheres to the preceding conventions. 3. Copy the resulting file from the previous step to the directory pointed by the logical SYS$I18N_ICONV, assuming you have the privilege to do so. Some Final Notes SYS$I18N_ICONV is by default a search list where the first directory in the list SYS$SYSROOT:[SYS$I18N.ICONV.USER] is meant for use as a site-specific repository for iconv codeset converters. The number of codesets and locales installed vary from system to system. Check the SYS$I18N directory tree for the codesets, converters, and locales installed on your system. 10.8 Handling Culture-Specific Information Each locale contains the following cultural information: o Date and time information The LC_TIME category defines the conventions for writing date and time, the names of the days of the week, and the names of months of the year. o Numeric information The LC_NUMERIC category defines the conventions for formatting non-monetary values. o Monetary information The LC_MONETARY category defines currency symbols and the conventions used to format monetary values. o Yes and no responses The LC_MESSAGES category defines the strings expected in response to yes/no questions. You can extract some of this cultural information using the nl_langinfo function and the localeconv function. See Section 10.8.1. Developing International Software 10-11 10.8.1 Extracting Cultural Information From a Locale The nl_langinfo function returns a pointer to a string that contains an item of information obtained from the program's current locale. The information you can extract from the locale is: o Date and time formats o The names of the days of the week, and months of the year in the local language o The radix character o The character used to separate groups of digits in non- monetary values o The currency symbol o The name of the codeset for the locale o The strings defined for responses to yes/no questions The localeconv function returns a pointer to a data structure that contains numeric formatting and monetary formatting data from the LC_NUMERIC and LC_MONETARY categories. 10.8.2 Date and Time Formatting Functions The functions that use the date and time information are: o strftime-takes date and time values stored in a data structure and formats them into an output string. The format of the output string is controlled by a format string. o strptime-converts a string (of type char) into date and time values. A format string defines how the string is interpreted. o wcsftime-does the same as strftime except that it creates a wide-character string. 10.8.3 Monetary Formatting Function The strfmon function uses the monetary information in a locale to convert a number of values into a string. The format of the string is controlled by a format string. 10-12 Developing International Software 10.8.4 Numeric Formatting The information in LC_NUMERIC is used by various functions. For example, strtod, wcstod, and the print and scan functions determine the radix character from the LC_NUMERIC category. 10.9 Functions for Handling Wide Characters A character can be represented by single-byte or multibyte values depending on the codeset. To make it easier to handle both single-byte and multibyte characters in the same way, the Compaq C RTL defines a wide-character data type, wchar_t. This data type can store characters that are represented by 1-, 2-, 3-, or 4-byte values. The functions provided to support wide characters are: o Character classification functions. See Section 10.9.1. o Case conversion functions. See Section 10.9.2. o Input and output functions. See Section 10.9.3. o Multibyte to wide-character conversion functions. See Section 10.9.4. o Wide-character to multibyte conversion functions. See Section 10.9.4. o Wide-character string manipulation functions. See Section 10.9.5. o Wide-character string collation and comparison functions. See Section 10.10. 10.9.1 Character Classification Functions The LC_CTYPE category in a locale classifies the characters in the locale's codeset into different types (alphabetic, numeric, lowercase, uppercase, and so on). There are two sets of functions, one for wide characters and one for single-byte characters, that test whether a character is of a specific type. The is* functions test single-byte characters, and the isw* functions test wide characters. Developing International Software 10-13 For example, the iswalnum function tests if a wide character is classed as either alphabetic or numeric. It returns a nonzero value if the character is one of these types. For more information about the classification functions see Chapter 3 and the Reference Section. 10.9.2 Case Conversion Functions The LC_CTYPE category defines mapping between pairs of characters of the locale. The most common character mapping is between uppercase and lowercase characters. However, a locale can support other than just case mappings. Two functions are provided to map one character to another according to the information in the LC_CTYPE category of the locale: o wctrans-looks for the named mapping (predefined in the locale) between characters. o towctrans-maps one character to another according to the named mapping given to the wctrans function. Two functions are provided for character case mapping: o towlower-maps an uppercase wide character to its lowercase equivalent. o towupper-maps a lowercase wide character to its uppercase equivalent. For more information about these functions, see the Reference Section. 10.9.3 Functions for Input and Output of Wide Characters The set of input and output functions manages wide characters and wide-character strings. Read Functions The functions for reading wide characters and wide- character strings are fgetwc, fgetws, getwc, and getwchar. There is also an ungetwc function that pushes a wide character back into the input stream. Write Functions The functions for writing wide characters and wide- character strings are fputwc, fputws, putwc, and putwchar. 10-14 Developing International Software Scan Functions All the scan functions allow for a culture-specific radix character, as defined in the LC_NUMERIC category of the current locale. The %lc, %C, %ls, and %S conversion specifiers enable the scan functions fwscanf, wscanf, swscanf, fscanf, scanf, and sscanf to read in wide characters. Print Functions All the print functions can format numeric values according to the data in the LC_NUMERIC category of the current locale. The %lc, %C and %ls, %S conversion specifiers used with print functions convert wide characters to multibyte characters and print the resulting characters. See Chapter 2 for details of all input and output functions. 10.9.4 Functions for Converting Multibyte and Wide Characters Wide characters are used internally by an application to manage single-byte or multibyte characters. However, text files are generally stored in multibyte character format. To process these files, the multibyte characters need converting to wide-character format. This can be achieved using the following functions: o mbtowc, mbrtowc, btowc-convert one multibyte character to a wide character. o mbsrtowcs, mbstowcs-convert a multibyte character string to a wide-character string. Similarly, the following functions convert wide characters into their multibyte equivalent: o wcrtomb, wctomb, wctob-convert a single wide character to a multibyte character. o wcsrtombs, wcstombs-convert a wide-character string to a multibyte character string. Associated with these conversion functions, the mblen and mbrlen functions are used to determine the size of a multibyte character. Developing International Software 10-15 Several of the wide-character functions take an argument of type "pointer to mbstate_t", where mbstate_t is an opaque datatype (like FILE or fpos_t) intended to keep the conversion state for the state-dependent codesets. 10.9.5 Functions for Manipulating Wide-Character Strings and Arrays The Compaq C RTL contains a set of functions (the wcs* and wmem* functions) that manipulate wide-character strings. For example, the wcscat function appends a wide-character string to the end of another string in the same way that the strcat function works on character strings of type char. See Chapter 3 for details of the string manipulation functions. 10.10 Collating Functions In an international environment, string comparison functions need to allow for multipass collations. The collation requirements include: o Ordering accented characters. o Collating a character sequence as a single character. For example, ch in Spanish should be collated after c but before d. o Collating a single character as a two-character sequence. o Ignoring some characters. Collating information is stored in the LC_COLLATE category of a locale. The Compaq C RTL includes the strcoll and wcscoll functions that use this collating information to compare two strings. Multipass collations by strcoll or wcscoll can be slower than using the strcmp or wcscmp functions. If your program needs to do many string comparisons using strcoll or wcscoll, it may be quicker to transform the strings once, using the strxfrm or wcsxfrm function, and then use the strcmp or wcscmp function. 10-16 Developing International Software The term collation refers to the relative order of characters. The collation order is locale-specific and might ignore some characters. For example, an American dictionary ignores the hyphen in words and lists take-out between takeoff and takeover. Comparison, on the other hand, refers to the examination of characters for sameness or difference. For example, takeout and take-out are different words, although they may collate the same. Suppose an application sorts a list of words so it can later perform a binary search on the list to quickly retrieve a word. Using strcmp, take-in, take-out, and take- up would be grouped in one part of the table. Using strcoll and a locale that ignores hyphens, take-out would be grouped with takeoff and takeover, and would be considered a duplicate of takeout. To avoid a binary search finding takeout as a duplicate of take-out, an application would most likely use strcmp rather than strcoll for forming a binary tree. Developing International Software 10-17 11 _________________________________________________________________ Date/Time Functions This chapter describes the date/time functions available with Compaq C for OpenVMS Systems. For more detailed information on each function, see the Reference Section. Table_11-1_Date/Time_Functions_____________________________ Function____Description____________________________________ asctime Converts a broken-down time from localtime into a 26-character string. ctime Converts a time, in seconds, since 00:00:00, January 1, 1970 to an ASCII string of the form generated by the asctime function. ftime Returns the elapsed time since 00:00:00, January 1, 1970 in the structure pointed to by its argument. getclock Gets the current value of the system-wide clock. gettimeofdayGets the date and time. gmtime Converts time units to GMT (Greenwich Mean Time). localtime Converts a time (expressed as the number of seconds elapsed since 00:00:00, January 1, 1970) into hours, minutes, seconds, and so on. mktime Converts a local time structure to a calendar time value. time Returns the time elapsed since 00:00:00, January 1, 1970, in seconds. tzset_______Sets_and_accesses_time-zone_conversion.________ Date/Time Functions 11-1 Also, the time-related information returned by fstat and stat uses the new date/time model described in the next section. 11.1 Date/Time Support Models Beginning with OpenVMS Version 7.0, the Compaq C RTL changed its date/time support model from one based on local time to one based on Universal Coordinated Time (UTC). This allows the Compaq C RTL to implement ANSI C/POSIX functionality that previously could not be implemented. A UTC time-based model also makes the Compaq C RTL compatible with the behavior of the Tru64 UNIX time functions. By default, newly compiled programs will generate entry points into UTC-based date/time routines. For compatibility with OpenVMS systems prior to Version 7.0, previously compiled programs that relink on an OpenVMS Version 7.0 system will retain local-time-based date/time support. Relinking alone will not access UTC support. Compiling programs with the _DECC_V4_SOURCE and _VMS_V6_ SOURCE feature-test macros defined will also enable local- time-based entry points. That is, the new OpenVMS Version 7.0 date/time functions will not be enabled. Functions with both UTC-based and local-time-based entry points are: ctime mktime fstat stat ftime strftime gmtime time localtime wcsftime ________________________ Note ________________________ Introducing a UTC-based, date/time model implies a certain loss of performance because time-related functions supporting UTC must read and interpret time- zone files instead of doing simple computations in memory as was done for the date/time model based on local time. To decrease this performance degradation, OpenVMS Version 7.1 and higher can maintain the process-wide 11-2 Date/Time Functions cache of time-zone files. The size of the cache (that is, the number of files in the memory) is determined by the value of the logical name DECC$TZ_CACHE_SIZE. The default value is 2. Because the time-zone files are relatively small (about 3 blocks each) you might consider defining DECC$TZ_CACHE_SIZE as the maximum number of time zones used by the application. For example, the default cache size fits an application that does not switch time zones during the run and runs on a system where the TZ environment variable is defined with both Standard and Summer time zone. ______________________________________________________ 11.2 Overview of Date/Time Functions In the UTC-based model, times are represented as seconds since the Epoch. The Epoch is defined as the time 0 hours, 0 minutes, 0 seconds, January 1, 1970 UTC. Seconds since the Epoch is a value interpreted as the number of seconds between a specified time and the Epoch. The functions time and ftime return the time as seconds since the Epoch. The functions ctime, gmtime, and localtime take as their argument a time value that represents the time in seconds from the Epoch. The function mktime converts a broken-down time, expressed as local time, into a time value in terms of seconds since the Epoch. The values st_ctime, st_atime, and st_mtime returned in the stat structure by the stat and fstat functions are also in terms of UTC. Time support new to OpenVMS Version 7.0 includes the functions tzset, gettimeofday, and getclock, and the external variables tzname, timezone and daylight. The UTC-based time model enables the Compaq C RTL to: o Implement the ANSI C gmtime function, which returns a structure in terms of GMT time. Date/Time Functions 11-3 o Specify the ANSI tm_isdst field of the tm structure, which specifies whether daylight-savings time is in effect. o Provide time-related POSIX and X/Open extensions (such as the tzset function (which lets you get time information from any timezone), and the external variables tzname, timezone, and daylight. o Correctly compute the local time for times in the past, something that the time functions like localtime need to do. o Enable localtime and gmtime, through the use of feature- test macros (see Section 1.5), to return two additional fields: tm_zone (an abbreviation of the timezone name) and tm_gmtoff (the offset from UTC in seconds) in the tm structure they return. 11.3 Compaq C RTL Date/Time Computations-UTC and Local Time Universal Coordinated Time (UTC) is an international standard for measuring time of day. Under the UTC time standard, zero hours occurs when the Greenwich Meridian is at midnight. UTC has the advantage of always increasing, unlike local time, which can go backwards/forwards depending on daylight saving time. Also, UTC has two additional components: o A measure of inaccuracy (optional) o A time-differential factor, which is an offset applied to UTC to derive local time. The time-differential factor associates each local time zone with UTC; the time differential factor is applied to UTC to derive local time. (Local times can vary up to -12 hours West of the Greenwich Meridian and +13 hours East of it). For the Compaq C RTL time support to work correctly on OpenVMS Version 7.0 and higher, the following must be in place: o Your OpenVMS system must be correctly configured to use a valid OpenVMS TDF. Make sure this is set correctly by checking the value of the SYS$TIMEZONE_DIFFERENTIAL 11-4 Date/Time Functions logical. This logical should contain the time difference added to UTC to arrive at your local time. o Your OpenVMS installation must correctly set the local time zone that describes the location that you want to be your default local time zone. In general, this is the local time zone in which your system is running. For more information, see the section on setting up your system to compensate for different time zones in your OpenVMS System Manager's Manual: Essentials. The Compaq C RTL uses local time-zone conversion rules to compute local time from UTC, as follows: 1. The Compaq C RTL internally computes time in terms of UTC. 2. The Compaq C RTL then uses time-zone conversion rules to compute a time-differential factor to apply to UTC to derive local time. See the tzset function in the reference section of this manual for more information on the time-zone conversion rules. By default, the time-zone conversion rules used for computing local time from UTC are specified in time-zone files defined by the SYS$LOCALTIME and SYS$POSIXRULES system logicals. These logicals are set during an OpenVMS installation to point to time-zone files that represent the system's best approximation to local wall-clock time: o SYS$LOCALTIME defines the time-zone file containing the default conversion rules used by the Compaq C RTL to compute local time. o SYS$POSIXRULES defines the time-zone file that specifies the default rules to be applied to POSIX-style time zones that do not specify when to change to summer time and back. SYS$POSIXRULES can be the same as SYS$LOCALTIME. See the tzset function for more information. Date/Time Functions 11-5 11.4 Time-Zone Conversion Rule Files The time-zone files pointed to by the SYS$LOCALTIME and SYS$POSIXRULES logicals are part of a public-domain, time- zone support package installed on OpenVMS Version 7.0 and higher systems. This support package includes a series of source files that describe the timezone conversion rules for computing local time from UTC in world-wide timezones. OpenVMS Version 7.0 and higher systems provide a time-zone compiler called ZIC. The ZIC compiler compiles time-zone source files into binary files that the Compaq C RTL reads to acquire time- zone conversion specifications. For more information on the format of these source files see the OpenVMS system documentation for ZIC. The time-zone files are organized as follows: o The root time-zone directory is SYS$COMMON:[SYS$TIMEZONE.SYSTEM]. The system logical SYS$TZDIR is set during installation to point to this area. o Time-zone source files are found in SYS$COMMON:[SYS$TIMEZONE.SYSTEM.SOURCES]. o Binary time-zone files use SYS$COMMON:[SYS$TIMEZONE.SYSTEM] as their root directory. Some binaries reside in this directory while others reside in its subdirectories. o Binaries residing in subdirectories are time- zone files that represent specific time zones in a larger geographic area. For example, SYS$COMMON:[SYS$TIMEZONE.SYSTEM] contains a subdirectory for the United States and a subdirectory for Canada, because each of these geographic locations contains several time zones. Each time zone in the US is represented by a time-zone file in the Unites States subdirectory. Each time zone in Canada is represented by a time-zone file in the Canada subdirectory. 11-6 Date/Time Functions Several of the time-zone files have names based on acronyms for the areas that they represent. Table 11-2 lists these acronyms. Table_11-2_Time-zone_Filename_Acronyms_____________________ Time-Zone Acronym____Description_____________________________________ CET Central European Time EET Eastern European Time Factory Specifies No Time Zone GB-Eire Great Britain/Ireland GMT Greenwich Mean Time NZ New Zealand NZ-CHAT New Zealand, Chatham Islands MET Middle European Time PRC Peoples Republic of China ROC Republic of China ROK Republic of Korea SystemV Specific to System V operating system UCT Universal Coordinated Time US United States UTC Universal Coordinated Time Universal Universal Coordinated Time W-SU Middle European Time WET________Western_European_Time___________________________ A mechanism is available for you to define and implement your own time-zone rules. For more information, see the OpenVMS system documentation on the ZIC compiler and the description of tzset in the reference section of this manual. Also, the SYS$LOCALTIME and SYS$POSIXRULES system logicals can be redefined to user-supplied time zones. Date/Time Functions 11-7 11.5 Sample Date/Time Scenario The following example and explanation shows how to use the Compaq C RTL time functions to print the current time: #include #include main () { time_t t; t = time((time_t)0); printf ("The current time is: %s\n",asctime (localtime (&t))); } This example: 1. Calls the time function to get the current time in seconds since the Epoch, in terms of UTC. 2. Passes this value to the localtime function, which uses time-conversion information as specified by tzset to determine which time-zone conversion rules should be used to compute local time from UTC. By default, these rules are specified in the file defined by SYS$LOCALTIME: a. For a user in the Eastern United States interested in their local time, SYS$LOCALTIME would be defined during installation to SYS$COMMON:[SYS$ZONEINFO.US]EASTERN, the time-zone file containing conversion rules for the Eastern U.S. time zone.. b. If the local time falls during daylight savings time (DST), SYS$COMMON:[SYS$ZONEINFO.US]EASTERN indicates that a time differential factor of -4 hours needs to be applied to UTC to get local time. If the local time falls during Eastern standard time (EST), SYS$COMMON:[SYS$ZONEINFO.US]EASTERN indicates that a time differential factor of -5 hours needs to be applied to UTC to get local time. c. The Compaq C RTL applies -4 (DST) or -5 (EST) to UTC, and localtime returns the local time in terms of a tm structure. 11-8 Date/Time Functions 3. Pass this tm structure to the asctime function to print the local time in a readable format. Date/Time Functions 11-9 Reference Section _________________________________________________________________ This section alphabetically describes the functions contained in the Compaq C Run-Time Library (RTL). abort _________________________________________________________________ abort Sends the signal SIGABRT that terminates execution of the program. Format #include void abort (void); REF-3 abs _________________________________________________________________ abs Returns the absolute value of an integer. Format #include int abs (int x); Argument x An integer. Return Value x The absolute value of the input argument. If the argument is LONG_ MIN, abs returns LONG_MIN because -LONG_MIN cannot fit in an int variable. REF-4 access _________________________________________________________________ access Checks a file to see whether a specified access mode is allowed. This function only checks UIC protection; ACLs are not checked. ________________________ Note ________________________ The access function does not accept network files as arguments. ______________________________________________________ Format #include int access (const char *file_spec, int mode); Arguments file_spec A character string that gives an OpenVMS or UNIX style file specification. The usual defaults and logical name translations are applied to the file specification. mode Interpreted as shown in Table REF-1. Table_REF-1_Interpretation_of_the_mode_Argument____________ Mode_Argument__Access_Mode_________________________________ F_OK Tests to see if the file exists X_OK Execute W_OK Write (implies delete access) R_OK___________Read________________________________________ Combinations of access modes are indicated by ORing the values. For example, to check to see if a file has RWED access mode, invoke access as follows: access (file_spec, R_OK | W_OK | X_OK); REF-5 access Return Values 0 Indicates that the access is allowed. -1 Indicates that the access is not allowed. Example #include #include #include main() { if (access("sys$login:login.com", F_OK)) { perror("ACCESS - FAILED"); exit(2); } } REF-6 acos _________________________________________________________________ acos Returns a value in the range 0 to , which is the arc cosine of its radian argument. Format #include double acos (double x); Argument x A radian expressed as a real value. Description When abs(x) is greater than 1.0, the value of acos(x) is 0 and the acos function sets errno to EDOM. REF-7 [w]addch _________________________________________________________________ [w]addch Add a character to the window at the current position of the cursor. Format #include int addch (char ch); int waddch (WINDOW *win, char ch); Arguments win A pointer to the window. ch The character to be added. A new-line character (\n) clears the line to the end, and moves the cursor to the next line at the same x coordinate. A return (\r) moves the cursor to the beginning of the line on the window. A tab (\t) moves the cursor to the next tabstop within the window. Description When the waddch function is used on a subwindow, it writes the character onto the underlying window as well. The addch routine performs the same function as waddch, but on the stdscr window. The cursor is moved after the character is written to the screen. Return Values OK Indicates success. REF-8 [w]addch ERR Indicates that writing the character would cause the screen to scroll illegally. For more information, see the scrollok function in this section. REF-9 [w]addstr _________________________________________________________________ [w]addstr Add the string pointed to by str to the window at the current position of the cursor. Format #include int addstr (char *str); int waddstr (WINDOW *win, char *str); Arguments win A pointer to the window. str A pointer to a character string. Description When the waddstr function is used on a subwindow, the string is written onto the underlying window as well. The addstr routine performs the same function as waddstr, but on the stdscr window. The cursor position changes as a result of calling this routine. Return Values OK Indicates success. ERR Indicates that the function causes the screen to scroll illegally, but it places as much of the string onto the window as possible. For more information, see the scrollok function in this section. REF-10 alarm _________________________________________________________________ alarm Sends the signal SIGALRM (defined in the header file) to the invoking process after the number of seconds indicated by its argument has elapsed. Format #include unsigned int alarm (unsigned int seconds); (ISO POSIX-1) int alarm (unsigned int seconds); (Compatability) Argument seconds Has a maximum limit of LONG_MAX seconds. Description Calling the alarm function with a 0 argument cancels any pending alarms. Unless it is caught or ignored, the signal generated by alarm terminates the process. Successive alarm calls reinitialize the alarm clock. Alarms are not stacked. Because the clock has a 1-second resolution, the signal may occur up to 1 second early. If the SIGALRM signal is caught, resumption of execution may be held up due to scheduling delays. When the SIGALRM signal is generated, a call to SYS$WAKE is generated whether or not the process is hibernating. The pending wake causes the current pause() to return immediately (after completing any function that catches the SIGALRM). Return Value n The number of seconds remaining from a previous alarm request. REF-11 asctime, asctime_r _________________________________________________________________ asctime, asctime_r Converts a broken-down time in a tm structure into a 26- character string in the following form: Sun Sep 16 01:03:52 1984\n\0 All fields have a constant width. Format #include char *asctime (const struct tm *timeptr); char *asctime_r (const struct tm *timeptr, char *buffer); (ISO POSIX-1) Argument timeptr A pointer to a structure of type tm, which contains the broken-down time. The tm structure is defined in the header file, and also shown in Table REF-4 in the description of localtime. buffer A pointer to a character array that is at least 26 bytes long. This array is used to store the generated date-and- time string. Description The asctime and asctime_r functios convert the contents of tm into a 26-character string and returns a pointer to the string. The difference between asctime_r and asctime is that the former puts the result into a user-specified buffer. The latter puts the result into thread-specific static memory allocated by the Compaq C RTL, which can be overwritten by subsequent calls to ctime or asctime; you must make a copy if you want to save it. REF-12 asctime, asctime_r On success, asctime returns a pointer to the string; asctime_r returns its second argument. On failure, these functions return the NULL pointer. See the localtime function in this section for a list of the members in tm. ________________________ Note ________________________ Generally speaking, UTC-based time functions can affect in-memory time-zone information, which is process-wide data. However, if the system time zone remains the same during the execution of the application (which is the common case) and the cache of timezone files is enabled (which is the default), then the _r variant of the time functions asctime_r, ctime_r, gmtime_r and localtime_r, is both thread-safe and AST-reentrant. If, however, the system time zone can change during the execution of the application or the cache of timezone files is not enabled, then both variants of the UTC-based time functions belong to the third class of functions, which are neither thread-safe nor AST-reentrant. ______________________________________________________ Return Value x A pointer to the string, if successful. NULL Indicates failure. REF-13 asin _________________________________________________________________ asin Returns a value in the range -/2 to /2, which is the arc sine of its radian argument. Format #include double asin (double x); Argument x A radian expressed as a real number. Description When abs(x) is greater than 1.0, the value of asin(x) is 0 and errno is set to EDOM. REF-14 assert _________________________________________________________________ assert Used for implementing run-time diagnostics in programs. Format #include void assert (int expression); Argument expression An expression that has an int type. Description When assert is executed, if expression is false (that is, it evaluates to 0), assert writes information about the particular call that failed (including the text of the argument, the name of the source file, and the source line number; the latter two are respectively the values of the preprocessing macros __FILE__ and __LINE__) to the standard error file in an implementation-defined format. Then, it calls the abort function. The assert function writes a message in the following form: Assertion failed: expression, file aaa, line nnn If expression is true (that is, it evaluates to nonzero) or if the signal SIGABRT is being ignored, assert returns no value. ________________________ Note ________________________ If a null character ('\0') is part of the expression being asserted, then only the text up to and including the null character is printed, since the null character effectively terminates the string being output. ______________________________________________________ REF-15 assert Compiling with the CC command qualifier /DEFINE=NDEBUG or with the preprocessor directive #define NDEBUG ahead of the #include assert statement causes the assert function to have no effect. Example #include #include main() { printf("Only this and the assert\n"); assert(1 == 2); /* expression is FALSE */ /* abort should be called so the printf will not happen. */ printf("FAIL abort did not execute"); } REF-16 atan _________________________________________________________________ atan Returns a value in the range -/2 to /2, which is the arc tangent of its radian argument. Format #include double atan (double x); Argument x A radian expressed as a real value. REF-17 atan2 _________________________________________________________________ atan2 Returns a value in the range - to . The returned value is the arc tangent of y/x, where y and x are the two arguments. Format #include double atan2 (double y, double x); Arguments y A real value. x A real value. REF-18 atexit _________________________________________________________________ atexit Registers a function that is called without arguments at program termination. Format #include int atexit (void (*func) (void)); Argument func A pointer to the function to be registered. Return Values 0 Indicates that the registration has succeeded. nonzero Indicates failure. Restriction The longjmp function cannot be executed from within the handler, because the destination address of the longjmp no longer exists. Example #include #include static void hw(void); main() { atexit(hw); } static void hw() { puts("Hello, world\n"); } REF-19 atexit Running this example produces the following output: Hello, world REF-20 atof _________________________________________________________________ atof Converts an ASCII character string to a double-precision number. Format #include double atof (const char *nptr); Argument nptr A pointer to the character string to be converted to a double-precision number. The string is interpreted by the same rules that are used to interpret floating constants. Description The string to be converted has the following format: [white-spaces][+|-]digits[radix-character][digits][e|E[+|- ]integer] Where radix-character is defined in the current locale. The first unrecognized character ends the conversion. This function is equivalent to strtod(nptr, (char**) NULL). Return Values x The converted value. 0 Indicates an underflow or the conversion could not be performed. The function sets errno to ERANGE or EINVAL, respectively. (+/-)HUGE_VAL Indicates overflow; errno is set to ERANGE. REF-21 atoi, atol _________________________________________________________________ atoi, atol Convert strings of ASCII characters to the appropriate numeric values. Format #include int atoi (const char *nptr); long int atol (const char *nptr); Argument nptr A pointer to the character string to be converted to a numeric value. Description The atoi and atol functions convert the initial portion of a string to its decimal int or long int value, respectively. The atoi and atol functions do not account for overflows resulting from the conversion. The string to be converted has the following format: [white-spaces][+|-]digits The function call atol (str) is equivalent to strtol (str, (char**)NULL, 10), and the function call atoi (str) is equivalent to (int) strtol (str, (char**)NULL, 10), except, in both cases, for the behavior on error. Return Value n The converted value. REF-22 atoq, atoll (Alpha only) _________________________________________________________________ atoq, atoll (Alpha only) Convert strings of ASCII characters to the appropriate numeric values. atoll is a synonym for atoq. Format #include __int64 atoq (const char *nptr); __int64 atoll (const char *nptr); Argument nptr A pointer to the character string to be converted to a numeric value. Description The atoq (or atoll) function converts the initial portion of a string to its decimal __int64 value. This function does not account for overflows resulting from the conversion. The string to be converted has the following format: [white-spaces][+|-]digits The function call atoq (str) is equivalent to strtoq (str, (char**)NULL, 10), except for the behavior on error. Return Value n The converted value. REF-23 basename _________________________________________________________________ basename Returns the last component of a path name. Format #include char *basename (char *path); Function Variants This function also has variants named _basename32 and _ basename64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument path A UNIX style pathname from which the base path name is extracted. Description This function takes the UNIX style pathname pointed to by path and returns a pointer to the pathname's final component, deleting any trailing slash (/) characters. If path consists entirely of the slash (/) character, the function returns a pointer to the string "/". If path is a NULL pointer or points to an empty string, the function returns a pointer to the string ".". The basename function can modify the string pointed to by path. REF-24 basename Return Values x A pointer to the final component of path. "/" If path consists entirely of the '/' character. "." If path is a NULL pointer or points to an empty string. REF-25 bcmp _________________________________________________________________ bcmp Compares byte strings. Format #include void bcmp (const void *string1, const void *string2, size_t length); Arguments string1, string2 The byte strings to be compared. length The length (in bytes) of the strings. Description The bcmp function compares the byte string in string1 against the byte string in string2. Unlike the string functions, there is no checking for null bytes. Zero-length strings are always identical. Note that bcmp is equivalent to memcmp, which is defined by the ANSI C Standard. Therefore, using memcmp is recommended for portable programs. Return Values 0 The strings are identical. Nonzero The strings are not identical. REF-26 bcopy _________________________________________________________________ bcopy Copies byte strings. Format #include void bcopy (const void *source, void *destination, size_t length); Arguments source Pointer to the source string. destination Pointer to the destination string. length The length (in bytes) of the string. Description The bcopy function operates on variable-length strings of bytes. It copies the value of the length argument in bytes from the string in the source argument to the string in the destination argument. Unlike the string functions, there is no checking for null bytes. If the length argument is 0 (zero), no bytes are copied. Note that bcopy is equivalent to memcpy, which is defined by the ANSI C Standard. Therefore, using memcpy is recommended for portable programs. REF-27 box _________________________________________________________________ box Draws a box around the window using the character vert as the character for drawing the vertical lines of the rectangle, and hor for drawing the horizontal lines of the rectangle. Format #include int box (WINDOW *win, char vert, char hor); Arguments win The address of the window. vert The character for the vertical edges of the window. hor The character for the horizontal edges of the window. Description This function copies boxes drawn on subwindows onto the underlying window. Use caution when using functions such as overlay and overwrite with boxed subwindows. Such functions copy the box onto the underlying window. Return Values OK Indicates success. ERR Indicates an error. REF-28 brk _________________________________________________________________ brk Determines the lowest virtual address that is not used with the program. Format #include void *brk (unsigned long int addr); Argument addr The lowest address, which the function rounds up to the next multiple of the page size. This rounded address is called the break address. Description An address that is greater than or equal to the break address and less than the stack pointer is considered to be outside the program's address space. Attempts to reference it will cause access violations. When a program is executed, the break address is set to the highest location defined by the program and data storage areas. Consequently, brk is needed only by programs that have growing data areas. Return Values n The new break address. (void *)(-1) Indicates that the program is requesting too much memory. errno and vaxc$errno are updated. REF-29 brk Restriction Unlike other C library implementations, the Compaq C RTL memory allocation functions (such as malloc) do not rely on brk or sbrk to manage the program heap space. Consequently, on OpenVMS systems, calling brk or sbrk can interfere with memory allocation routines. The brk and sbrk functions are provided only for compatibility purposes. REF-30 bsearch _________________________________________________________________ bsearch Performs a binary search. It searches an array of sorted objects for a specified object. Format #include void *bsearch (const void *key, const void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *)); Function Variants This function also has variants named _bsearch32 and _ bsearch64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments key A pointer to the object to be sought in the array. This pointer should be of type pointer-to-object and cast to type pointer-to-void. base A pointer to the initial member of the array. This pointer should be of type pointer-to-object and cast to type pointer-to-void. nmemb The number of objects in the array. size The size of an object, in bytes. compar A pointer to the comparison function. REF-31 bsearch Description The array must first be sorted in increasing order according to the specified comparison function pointed to by compar. Two arguments are passed to the comparison function pointed to by compar. The two arguments point to the objects being compared. Depending on whether the first argument is less than, equal to, or greater than the second argument, the comparison function must return an integer less than, equal to, or greater than 0. It is not necessary for the comparison function (compar) to compare every byte in the array. Therefore, the objects in the array can contain arbitrary data in addition to the data being compared. Since it is declared as type pointer-to-void, the value returned must be cast or assigned into type pointer-to- object. Return Values x A pointer to the matching member of the array or a null pointer if no match is found. NULL Indicates that the key cannot be found in the array. Example #include #include #define SSIZE 30 extern int compare(); /* prototype for comparison function */ int array[SSIZE] = {30, 1, 29, 2, 28, 3, 27, 4, 26, 5, 24, 6, 23, 7, 22, 8, 21, 9, 20, 10, 19, 11, 18, 12, 17, 13, 16, 14, 15, 25}; /* This program takes an unsorted array, sorts it using qsort, */ /* and then calls bsearch for each element in the array, */ /* making sure that bsearch returns the correct element. */ REF-32 bsearch main() { int i; int failure = FALSE; int *rkey; qsort(array, SSIZE, sizeof (array[0]), &compare); /* search for each element */ for (i = 0; i < SSIZE - 1; i++) { /* search array element i */ rkey = bsearch((array + i), array, SSIZE, sizeof(array[0]), &compare); /* check for successful search */ if (&array[i] != rkey) { printf("Not in array, array element %d\n", i); failure = TRUE; break; } } if (!failure) printf("All elements successfully found!\n"); } /* Simple comparison routine. */ /* */ /* Returns: = 0 if a == b */ /* < 0 if a < b */ /* > 0 if a > b */ int compare(int *a, int *b) { return (*a - *b); } This example program outputs the following: All elements successfully found! REF-33 btowc _________________________________________________________________ btowc Converts a one-byte multibyte character to a wide character in the initial shift state. Format #include wint_t btowc (int c); Arguments c The character to be converted to a wide-character representation. Description This function determines whether (unsigned char)c is a valid one-byte multibyte character in the initial shift state, and if so, returns a wide-character representation of that character. Return Values x The wide-character representation of unsigned char c. WEOF Indicates an error. The c argument has the value EOF or does not constitute a valid one-byte multibyte character in the initial shift state. REF-34 bzero _________________________________________________________________ bzero Copies null characters into byte strings. Format #include void bzero (void *string, size_t length); Arguments string Specifies the byte string into which you want to copy null characters. length Specifies the length (in bytes) of the string. Description This function copies null characters ('\0') into the byte string pointed to by string for length bytes. If length is 0 (zero), then no bytes are copied. REF-35 cabs _________________________________________________________________ cabs Computes the Euclidean distance between two points as the square root of their respective squares, returning the following value: sqrt(x[2] + y[2]) Format #include double cabs (cabs_t z); Arguments z A structure of type cabs_t. This type is defined in the header file as follows: typedef struct {double x,y;} cabs_t; Description On overflow, the return value is undefined. REF-36 calloc _________________________________________________________________ calloc Allocates an area of zeroed memory. This function is AST- reentrant. Format #include void *calloc (size_t number, size_t size); Function Variants This function also has variants named _calloc32 and _ calloc64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments number The number of items to be allocated. size The size of each item. Description The calloc function initializes the items to 0. See also malloc and realloc in this section. Return Values n The address of the first byte, which is aligned on a quadword boundary. NULL Indicates an inability to allocate the space. REF-37 catclose _________________________________________________________________ catclose Closes a message catalog. Format #include int catclose (nl_catd catd); Arguments catd A message catalog descriptor. This is returned by a successful call to catopen. Description This function closes the message catalog referenced by catd and frees the catalog file descriptor. Return Values 0 Indicates that the catalog was successfully closed. -1 Indicates that an error occurred. The function sets errno to the following value: o EBADF - The catalog descriptor is not valid. REF-38 catgets _________________________________________________________________ catgets Retrieves a message from a message catalog. Format #include char *catgets (nl_catd catd, int set_id, int msg_id, const char *s); Function Variants This function also has variants named _catgets32 and _ catgets64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments catd A message catalog descriptor. This is returned by a successful call to catopen. set_id An integer set identifier. msg_id An integer message identifier. s A pointer to a default message string that is returned by the function if the message cannot be retrieved. Description This function retrieves a message identified by set_id and msg_id, in the message catalog catd. The message is stored in a message buffer in the nl_catd structure, which is overwritten by subsequent calls to catgets. If a message string needs to be preserved, it should be copied to another location by the program. REF-39 catgets Return Values x Pointer to the retrieved message. s Pointer to the default message string. Indicates that the function is not able to retrieve the requested message from the catalogue. This condition can arise if the requested pair (set_d, msg_id) does not represent an existing message from the open catalogue, or it indicates that an error occurred. If an error occurred, the function sets errno to one of the following values: o EBADF - The catalog descriptor is not valid. o EVMSRR - A VMS I/O read error; the VMS error code can be found in vaxc$errno. Example #include #include #include #include #include #include REF-40 catgets /* This test makes use of all the message catalog routines. catopen() */ /* opens the catalog ready for reading, then each of the three messages */ /* in the catalog are extracted in turn using catgets() and printed out. */ /* catclose() closes the catalog after use. */ /* The catalog source file used to create the catalog is as follows: */ /* $ this is a message file * $ * $quote " * $ another comment line * $set 1 * 1 "First set, first message" * 2 "second message -- This long message uses a backslash \ * for continuation." * $set 2 * 1 "Second set, first message" */ char *default_msg = "this is the first message."; main() { nl_catd catalog; int msg1, msg2, retval; char *cat = "sys$disk:[]catgets_ example.cat"; /* Force local catalog */ char *msgtxt; char string[128]; /* Create the message test catalog */ system("gencat catgets_example.msgx catgets_example.cat") ; if ((catalog = catopen(cat, 0)) == (nl_catd) - 1) { perror("catopen"); exit(EXIT_FAILURE); } msgtxt = catgets(catalog, 1, 1, default_msg); printf("%s\n", msgtxt); msgtxt = catgets(catalog, 1, 2, default_msg); printf("%s\n", msgtxt); msgtxt = catgets(catalog, 2, 1, default_msg); printf("%s\n", msgtxt); REF-41 catgets if ((retval = catclose(catalog)) == -1) { perror("catclose"); exit(EXIT_FAILURE); } delete("catgets_example.cat;") ; /* Remove the test catalog */ } Running the example program produces the following result: First set, first message second message -- This long message uses a backslash for continuation. Second set, first message REF-42 catopen _________________________________________________________________ catopen Opens a message catalog. Format #include nl_catd catopen (const char *name, int oflag); Arguments name The name of the message catalog to open. oflag An object of type int that determines whether the locale set for the LC_MESSAGES category in the current program's locale or the logical name LANG is used to search for the catalog file. Description This function opens the message catalog identified by name. If name contains a colon (:), a square opening bracket ([), or an angle bracket (<), or is defined as a logical name, then it is assumed that name is the complete file specification of the catalog. If it does not include these characters, catopen assumes that name is a logical name pointing to an existing catalog file. If name is not a logical name, then the logical name NLSPATH is used to define the file specification of the message catalog. NLSPATH is defined in the user's process. If the NLSPATH logical name is not defined, or no message catalog can be opened in any of the components specified by the NLSPATH, then the SYS$NLSPATH logical name is used to search for a message catalog file. Both NLSPATH and SYS$NLSPATH is a comma-separated list of templates. The catopen function uses each template to construct a file specification. For example, NLSPATH could be defined as: REF-43 catopen DEFINE NLSPATH SYS$SYSROOT:[SYS$I18N.MSG]%N.CAT,SYS$COMMON:[SYSMSG]%N.CAT In this example, catopen first searches the directory SYS$SYSROOT:[SYS$I18N.MSG] for the named catalog. If the named catalog is not found there, the directory SYS$COMMON:[SYSMSG] is searced. The catalog name is constructed by substituting %N with the name passed to catopen, and adding the .cat suffix. %N is known as a substitution field. The following substitution fields are valid: ___________________________________________________________ Field__Meaning_____________________________________________ %N Substitute the name passed to catopen %L Substitute the locale name. [1] The period (.) and at-sign (@) characters in the locale name are replaced by an underscore (_) character. For example, the "zh_CN.dechanzi@radical" locale name results in a substitution of ZH_CN_DECHANZI_RADICAL. %l Substitute the language part of the locale name. For [1] example, the language part of the en_GB.ISO8859-1 locale name is en. %t Substitute the territory part of the locale [1] name. For example, the territory part of the en_GB.ISO8859-1 locale is GB. %c Substitute the codeset name from the locale name. [1] For example, the codeset name of the en_GB.ISO8859-1 locale name is ISO8859-1. [1]This_substitution_assumes_that_the_locale_name_is_of_the form_language_territory.codeset@mode_______________________ If the oflag argument is set to NL_CAT_LOCALE, then the current locale as defined for the LC_MESSAGES category is used to determine the substitution for the %L, %l, %t, and %c substitution fields. If the oflag argument is set to 0, then the value of the LANG environment variable is used as a locale name to determine the substitution for these fields. Note that using NL_CAT_LOCALE conforms to the XPG4 specification while a value of 0 (zero) exists for the purpose of preserving XPG3 compatibility. Note also, that REF-44 catopen catopen uses the value of the LANG environment variable without checking whether the program's locale can be set using this value. That is, catopen does not check whether this value can serve as a valid locale argument in the setlocale call. If the substitution value is not defined, an empty string is substituted. A leading comma or two adjacent commas (,,) is equivalent to specifying %N. For example, DEFINE NLSPATH ",%N.CAT,SYS$COMMON:[SYSMSG.%L]%N.CAT" In this example, catopen searches in the following locations in the order shown: 1. name (in the current directory) 2. name.cat (in the current directory) 3. SYS$COMMON:[SYSMSG.locale_name]name.cat Return Values x A message catalog file descriptor. Indicates the call was successful. This descriptor is used in calls to catgets and catclose. REF-45 catopen (nl_catd) -1 Indicates an error occurred. The function sets errno to one of the following values: o EACCES - Insufficient privilege or file protection violation, or file currently locked by another user. o EMFILE - Process channel count exceeded. o ENAMETOOLONG - The full file specification for message catalogue is too long o ENOENT - Unable to find the requested message catalogue. o ENOMEM - Insufficient memory available. o ENOTDIR - Part of the name argument is not a valid directory. o EVMSERR - An error occurred that does not match any errno value. Check the value of vaxc$errno. REF-46 ceil _________________________________________________________________ ceil Returns (as a double) the smallest integer that is greater than or equal to its argument. Format #include double ceil (double x); Argument x A real value. Return Values x The smallest integer greater than or equal to the function argument. REF-47 cfree _________________________________________________________________ cfree Makes available for reallocation the area allocated by a previous calloc, malloc, or realloc call. This function is AST-reentrant. Format #include void cfree (void *ptr); Argument ptr The address returned by a previous call to malloc, calloc, or realloc. Description The contents of the deallocated area are unchanged. In Compaq C for OpenVMS Systems, the free and cfree functions are equivalent. Some other C implementations use free with malloc or realloc, and cfree with calloc. However, since the ANSI C standard does not include cfree, using free may be preferable. See also free in this section. REF-48 chdir _________________________________________________________________ chdir Changes the default directory. Format #include int chdir (const char *dir_spec); (ISO POSIX-1) int chdir (const char *dir_spec, . . . ); (DEC C Extension) Argument dir_spec A null-terminated character string naming a directory in either an OpenVMS or UNIX style specification. . . . This argument is a Compaq C extension available when not defining any of the standards-related feature-test macros (see Section 1.5 and not compiling in strict ANSI C mode (/STANDARD=ANSI89). The argument is an optional flag of type int that is significant only when calling chdir from USER mode. If the value of the flag is 1, the new directory is effective across images. If the value is not 1, the original default directory is restored when the image exits. Description This function changes the default directory. The change can be permanent or temporary. Permanent means that the new directory remains as the default directory after the image exits. Temporary means that on image exit, the default is set to whatever it was before the execution of the image. There are two ways of making the change permanent: o Call chdir from USER mode with the second argument set to 1. REF-49 chdir o Call chdir from SUPERVISOR or EXECUTIVE mode, regardless of the value of the second argument. Otherwise, the change is temporary. Return Values 0 Indicates that the directory is successfully changed to the given name. -1 Indicates that the change attempt has failed. REF-50 chmod _________________________________________________________________ chmod Changes the file protection of a file. Format #include int chmod (const char *file_spec, mode_t mode); Arguments file_spec The name of an OpenVMS or UNIX style file specification. mode A file protection. Modes are constructed by performing a bitwise OR on any of the values shown in Table REF-2. Table_REF-2_File_Protection_Values_and_Their_Meanings______ Value___Privilege__________________________________________ 0400 OWNER:READ 0200 OWNER:WRITE 0100 OWNER:EXECUTE 0040 GROUP:READ 0020 GROUP:WRITE 0010 GROUP:EXECUTE 0004 WORLD:READ 0002 WORLD:WRITE 0001____WORLD:EXECUTE______________________________________ When you supply a mode value of 0, the chmod function gives the file the user's default file protection. The system is given the same privileges as the owner. A WRITE privilege also implies a DELETE privilege. REF-51 chmod Description You must have a WRITE privilege for the file specified to change the mode. Return Values 0 Indicates that the mode is successfully changed. -1 Indicates that the change attempt has failed. REF-52 chown _________________________________________________________________ chown Changes the owner user identification code (UIC) of the file. Format #include int chown (const char *file_spec, uid_t owner, gid_t group); Arguments file_spec The address of an ASCII file name. owner An integer corresponding to the new owner UIC of the file. group An integer corresponding to the group UIC of the file. Return Values 0 Indicates success. -1 Indicates failure. REF-53 [w]clear _________________________________________________________________ [w]clear Erase the contents of the specified window and reset the cursor to coordinates (0,0). The clear function acts on the stdscr window. Format #include int clear(); int wclear (WINDOW *win); Argument win A pointer to the window. Return Values OK Indicates success. ERR Indicates an error. REF-54 clearerr _________________________________________________________________ clearerr Resets the error and end-of-file indicators for a file (so that ferror and feof will not return a nonzero value). Format #include void clearerr (FILE *file_ptr); Argument file_ptr A file pointer. REF-55 clearok _________________________________________________________________ clearok Sets the clear flag for the window. Format #include clearok (WINDOW *win, bool boolf); Arguments win The entire size of the terminal screen. You can use the windows stdscr and curscr with clearok. boolf A Boolean value of TRUE or FALSE. If the argument is TRUE, this forces a clearscreen to be printed on the next call to refresh, or stops the screen from being cleared if boolf is FALSE. The type bool is defined in the header file as follows: #define bool int Description Unlike the clear function, the clearok function does not alter the contents of the window. If the win argument is curscr, the next call to refresh causes a clearscreen, even if the window passed to refresh is not a window the size of the entire terminal screen. REF-56 clock _________________________________________________________________ clock Determines the CPU time (in 10-millisecond units) used since the beginning of the process. The time reported is the sum of the user and system times of the calling process and any terminated child processes for which the calling process has executed wait or system. Format #include clock_t clock (void); Description The value returned by the clock function must be divided by the value of the CLK_TCK, as defined in the standard header file , to obtain the time in seconds. The type clock_t is defined in the header file as follows: typedef long int clock_t; Only the accumulated times for child processes running a C main program or a program that calls VAXC$CRTL_INIT or DECC$CRTL_INIT are included. A typical usage of the clock function is to call it after a program does its initial setup, and then again after the program executes the code to be timed. Then subtract the two values to give elapsed CPU time. Return Values n The processor time used. -1 Indicates that the processor time used is not available. REF-57 close _________________________________________________________________ close Closes the file associated with a file descriptor. Format #include int close (int file_desc); Argument file_desc A file descriptor. Description This function tries to write buffered data by using an implicit call to fflush. If the write fails (because the disk is full or the user's quota was exceeded, for example), close continues executing. It closes the VMS channel, deallocates any buffers, and releases the memory associated with the file descriptor (or FILE pointer). Any buffered data is lost, and the file descriptor (or FILE pointer) no longer refers to the file. If your program needs to recover from errors when flushing buffered data, it should make an explicit call to fsync (or fflush) before calling close. Return Values 0 Indicates that the file is properly closed. -1 Indicates that the file descriptor is undefined or an error occurred while the file was being closed (for example, if the buffered data cannot be written out). REF-58 close Example #include int fd; . . . fd = open ("student.dat", 1); . . . close(fd); REF-59 closedir _________________________________________________________________ closedir Closes directories. Format #include int closedir (DIR *dir_pointer); Argument dir_pointer Pointer to the dir structure of an open directory. Description This function closes a directory stream and frees the structure associated with the dir_pointer argument. Upon return, the value of dir_pointer does not necessarily point to an accessible object of the type DIR. The type DIR, which is defined in the header file, represents a directory stream that is an ordered sequence of all the directory entries in a particular directory. Directory entries represent files. You can remove files from or add files to a directory asynchronously to the operation of the readdir function. ________________________ Note ________________________ An open directory must always be closed with the closedir function to ensure that the next attempt to open the directory is successful. ______________________________________________________ REF-60 closedir Example The following example shows how to search a directory for the entry name, using the opendir, readdir, and closedir functions: #include #include #include #include #define FOUND 1 #define NOT_FOUND 0 static int dirent_example(const char *name, unsigned int unix_style) { DIR *dir_pointer; struct dirent *dp; if ( unix_style ) dir_pointer = opendir("."); else dir_pointer = opendir(getenv("PATH")); if ( !dir_pointer ) { perror("opendir"); return NOT_FOUND; } /* Note, that if opendir() was called with Unix-style file */ /* spec like ".", readdir() will return only a single */ /* version of each file in the directory. In this case the */ /* name returned in d_name member of the dirent structure */ /* will contain only file name and file extension fields, */ /* both lowercased like "foo.bar". */ /* If opendir() was called with VMS-style file spec, */ /* readdir() will return every version of each file in the */ /* directory. In this case the name returned in d_name */ /* member of the dirent structure will contain file name, */ /* file extension and file version fields. All in upper */ /* case, like "FOO.BAR;1". */ for ( dp = readdir(dir_pointer); dp && strcmp(dp->d_name, name); dp = readdir(dir_pointer) ) ; REF-61 closedir closedir(dir_pointer); if ( dp != NULL ) return FOUND; else return NOT_FOUND; } int main(void) { char *filename = "foo.bar"; FILE *fp; remove(filename); if ( !(fp = fopen(filename, "w")) ) { perror("fopen"); return (EXIT_FAILURE); } if ( dirent_example( "FOO.BAR;1", 0 ) == FOUND ) puts("VMS style: found"); else puts("VMS style: not found"); if ( dirent_example( "foo.bar", 1 ) == FOUND ) puts("Unix style: found"); else puts("Unix style: not found"); fclose(fp); remove(filename); return( EXIT_SUCCESS ); } Return Values 0 Indicates success. -1 Indicates an error and is further specified in the global errno. REF-62 [w]clrattr _________________________________________________________________ [w]clrattr Deactivate the video display attribute attr within the window. The clrattr function acts on the stdscr window. Format #include int clrattr (int attr); int wclrattr (WINDOW *win, int attr); Arguments win A pointer to the window. attr Video display attributes that can be blinking, boldface, reverse video, and underlining; they are represented by the defined constants _BLINK, _BOLD, _REVERSE, and _UNDERLINE. To clear multiple attributes, separate them with a bitwise OR operator (|) as follows: clrattr(_BLINK | _UNDERLINE); Description These functions are specific to Compaq C for OpenVMS Systems and are not portable. Return Values OK Indicates success. ERR Indicates an error. REF-63 [w]clrtobot _________________________________________________________________ [w]clrtobot Erase the contents of the window from the current position of the cursor to the bottom of the window. The clrtobot function acts on the stdscr window. Format #include int clrtobot(); int wclrtobot (WINDOW *win); Argument win A pointer to the window. Return Values OK Indicates success. ERR Indicates an error. REF-64 [w]clrtoeol _________________________________________________________________ [w]clrtoeol Erase the contents of the window from the current cursor position to the end of the line on the specified window. The clrtoeol function acts on the stdscr window. Format #include int clrtoeol(); int wclrtoeol (WINDOW *win); Argument win A pointer to the window. Return Values OK Indicates success. ERR Indicates an error. REF-65 confstr _________________________________________________________________ confstr Determines the current value of a specified system variable defined by a string value. Format #include size_t confstr (int name, char *buf, size_t len); Arguments name The system variable setting. Valid values for the name argument are the _CS_X names defined in the header file. buf Pointer to the buffer where the confstr function copies the name value. len The size of the buffer storing the name value. Description This function allows an application to determine the current setting of certain system parameters, limits, or options that are defined by a string value. The function is mainly used by applications to find the system default value for the PATH environment variable. If the following conditions are true, then the confstr function copies that value into a len-byte buffer pointed to by buf: o The len argument is not 0 (zero). o The name argument has a system-defined value. o The buf argument is not a NULL pointer. REF-66 confstr If the returned string is longer than len bytes, including the terminating null, then the confstr function truncates the string to len -1 bytes and adds a terminating null to the result. The application can detect that the string was truncated by comparing the value returned by the confstr function with the value of the len argument. The header file contains system-defined limits. The header file contains system-defined environmental variables. Example To find out how big a buffer is needed to store the string value of name, enter: confstr(_CS_PATH, NULL, (size_t) 0) The confstr function returns the size of the buffer necessary. Return Values 0 Indicates an error. When the specified name value: o Is invalid, errno is set to EINVAL. o Does not have a system-defined value, errno is not set. REF-67 confstr n The size of the buffer needed to hold the value. o When the value of the name argument is system-defined, confstr returns the size of the buffer needed to hold the entire value. If this return value is greater than the len value, the string returned as the buf value is truncated. o When the value of the len argument is set to 0 or the buf value is NULL, confstr returns the size of the buffer needed to hold the entire system-defined value. The string value is not copied. REF-68 cos _________________________________________________________________ cos Returns the cosine of its radian argument. Format #include double cos (double x); Argument x A radian expressed as a real value. Return Values x The cosine of the argument. HUGE_VAL Indicates that the argument is too large; errno is set to ERANGE. REF-69 cosh _________________________________________________________________ cosh Returns the hyperbolic cosine of its argument. Format #include double cosh (double x); Argument x A real value. Return Values x The hyperbolic cosine of the argument. HUGE_VAL Indicates that the argument is too large; errno is set to ERANGE. REF-70 cot _________________________________________________________________ cot Returns the cotangent of its radian argument. Format #include double cot (double x); Argument x A radian expressed as a real number. Return Values x The cotangent of the argument. HUGE_VAL Indicates that the argument is zero; errno is set to ERANGE. REF-71 creat _________________________________________________________________ creat Creates a new file. Format #include int creat (const char *file_spec, mode_t mode); (ISO POSIX-1) int creat (const char *file_spec, mode_t mode, . . . ); (DEC C Extension) Arguments file_spec A null-terminated string containing any valid file specification. mode An unsigned value that specifies the file-protection mode. The compiler performs a bitwise AND operation on the mode and the complement of the current protection mode. You can construct modes by using the bitwise OR operator (|) to create mode combinations. The modes are as follows: 0400 OWNER:READ 0200 OWNER:WRITE 0100 OWNER:EXECUTE 0040 GROUP:READ 0020 GROUP:WRITE 0010 GROUP:EXECUTE 0004 WORLD:READ 0002 WORLD:WRITE 0001 WORLD:EXECUTE REF-72 creat The system is given the same privileges as the owner. A WRITE privilege implies a DELETE privilege. ________________________ Note ________________________ To create files with OpenVMS RMS default protections using the UNIX system-call functions umask, mkdir, creat, and open, call mkdir, creat, and open with a file-protection mode argument of 0777 in a program that never specifically calls umask. These default protections include correctly establishing protections based on ACLs, previous versions of files, and so on. In programs that do vfork/exec calls, the new process image inherits whether umask has ever been called or not from the calling process image. The umask setting and whether the umask function has ever been called are both inherited attributes. ______________________________________________________ . . . An optional argument list of character strings of the following form: "keyword = value", . . . ,"keyword = value" Or in the case of "acc" or "err", this form: "keyword" Here, keyword is an RMS field in the file access block (FAB) or record access block (RAB); value is valid for assignment to that field. Some fields permit you to specify more than one value. In these cases, the values are separated by commas. The RMS callback keywords "acc" and "err" are the only keywords that do not take values. Instead, they are followed by a pointer to the callback routine to be used, followed by a pointer to a user-specified value to be used as the first argument of the callback routine. For example, to set up an access callback routine called acc_callback whose first argument is a pointer to the integer variable first_arg in a call to open, you can use the following statement: REF-73 creat open("file.dat", O_RDONLY, 0 ,"acc", acc_callback, &first_arg) The second and third arguments to the callback routine must be pointers to a FAB and RAB, respectively, and the routine must have a return type of int. If the callback retruns a value less than 0, the open, creat, or fopen fails. The error callback can correct the error condition and return a status greater than or equal to 0 to continue the creat call. Assuming the previous open statement, the function prototype for acc_callback would be similar to the following statement: #include int acc_callback(int *first_arg, struct FAB *fab, struct RAB *rab); FAB and RAB are defined in the header file, and the actual pointers passed to the routine are pointers to the RAB and FAB being used to open the file file.dat. If an access callback routine is established, then it will be called in the open-type routine immediately before the call to the RMS function sys$create or sys$open. If an error callback routine is established and an error status is returned from the sys$create or sys$open function, then the callback routine will be invoked immediately after the status is checked and the error value is discovered. ________________________ Note ________________________ Any manipulation of the RAB or FAB in a callback function could lead to serious problems in later calls to the Compaq C RTL I/O functions. ______________________________________________________ Table REF-3 describes the RMS keywords and values. Table_REF-3_RMS_Valid_Keywords_and_Values__________________ Keyword__________Value___Description_______________________ "acc" callbackAccess callback routine. "alq = n" decimal Allocation quantity. (continued on next page) REF-74 creat Table_REF-3_(Cont.)_RMS_Valid_Keywords_and_Values__________ Keyword__________Value___Description_______________________ "bls = n" decimal Block size. "ctx = bin" string No translation of '\n' to the terminal. Use this for writing binary data to files. "ctx=cvt" string Negates a previous setting of "ctx=nocvt". This is the default. "ctx = nocvt" string No conversion of Fortran carriage- control bytes. "ctx = rec" string Force record mode access. "ctx = stm" string Force stream mode access. "ctx=xplct" string Causes records to be written only when explicitly specified by a call to fflush, close, or fclose. "deq = n" decimal Default extension quantity. "dna = string Default file-name string. filespec" "err" callbackError callback routine. "fop = val, val File-processing options: , . . . " (continued on next page) REF-75 creat Table_REF-3_(Cont.)_RMS_Valid_Keywords_and_Values__________ Keyword__________Value___Description_______________________ ctg Contiguous. cbt Contiguous-best-try. dfw Deferred write; only applicable to files opened for shared access. dlt Delete file on close. tef Truncate at end-of-file. cif Create if nonexistent. sup Supersede. scf Submit as command file on close. spl Spool to system printer on close. tmd Temporary delete. tmp Temporary (no file directory). nef Not end-of-file. rck Read check compare operation. wck Write check compare operation. mxv Maximize version number. rwo Rewind file on open. pos Current position. rwc Rewind file on close. sqo File can only be processed in a sequential manner. "fsz = n" decimal Fixed header size. "gbc = n" decimal The requested number of global buffers for a file. "mbc = n" decimal Multiblock count. "mbf = n" decimal Multibuffer count. "mrs = n" decimal Maximum record size. "pmt=usr-prmpt" string Prompts for terminal input. Any RMS input from a terminal device will be preceded by "usr-prmpt" when this option and "rop=pmt" are specified. "rat = val, Record attributes: val . . . " (continued on next page) REF-76 creat Table_REF-3_(Cont.)_RMS_Valid_Keywords_and_Values__________ Keyword__________Value___Description_______________________ cr Carriage-return control. blk Disallow records to span block ftn boundaries. none FORTRAN print control. prn Explicitly forces no carriage control. Print file format. "rfm = val" Record format: fix Fixed-length record format. stm RMS stream record format. stmlf Stream format with line-feed stmcr terminator. Stream format with carriage-return var terminator. vfc Variable-length record format. udf Variable-length record with fixed control. Undefined. "rop = val, Record-processing operations: val . . . " asy Asynchronous I/O. cco Cancel Ctrl/O (used with Terminal I/O). cvt Capitalizes characters on a read from the terminal. eof Positions the record stream to the end-of-file for the connect operation only. nlk Do not lock record. pmt Enables use of the prompt specified by "pmt=usr-prmpt" on input from the terminal. (continued on next page) REF-77 creat Table_REF-3_(Cont.)_RMS_Valid_Keywords_and_Values__________ Keyword__________Value___Description_______________________ pta Eliminates any information in the type-ahead buffer on a read from the terminal. rea Locks record for a read operation for this process, while allowing other accessors to read the record. rlk Locks record for write. rne Suppresses echoing of input data on the screen as it is entered on the keyboard. rnf Indicates that Ctrl/U, Ctrl/R, and DELETE are not to be considered control commands on terminal input, but are to be passed to the application program. rrl Reads regardless of lock. syncsts Returns success status of RMS$_ SYNCH if the requested service completes its task immediately. tmo Timeout I/O. tpt Allows put/write services using sequential record access mode to occur at any point in the file, truncating the file at that point. ulk Prohibits RMS from automatically unlocking records. wat Wait until record is available, if currently locked by another stream. rah Read ahead. (continued on next page) REF-78 creat Table_REF-3_(Cont.)_RMS_Valid_Keywords_and_Values__________ Keyword__________Value___Description_______________________ wbh Write behind. "rtv=n" decimal The number of retrieval pointers that RMS has to maintain in memory (0 to 127,255). "shr = val" File sharing options: del Allows users to delete. get Allows users to read. mse Allows mainstream access. nil Prohibits file sharing. put Allows users to write. upd Allows users to update. upi Allows one or more writers. "tmo_=_n"________decimal_I/O_timeout_value.________________ In addition to these options, any option that takes a key value (such as "fop" or "rat") can be negated by prefixing the value with "no". For example, specify "fop=notmp" to clear the "tmp" bit in the "fop" field. ________________________ Notes ________________________ o While these options provide much flexibility and functionality, many of them can also cause severe problems if not used correctly. o You cannot share the default Compaq C for OpenVMS stream file I/O. If you wish to share files, you must specify "ctx=rec" to force record access mode. You must also specify the appropriate "shr" options depending on the type of access you want. o If you intend to share a file opened for append, you must specify appropriate share and record- locking options, to allow other accessors to read the record. The reason for doing this: the file is positioned at end-of-file through reading records in a loop until end-of-file is reached. ______________________________________________________ REF-79 creat For more information on these options, see the OpenVMS Record Management Services Reference Manual manual. Description The Compaq C RTL opens the new file for reading and writing, and returns the corresponding file descriptor. If the file exists: o A version number one greater than any existing version is assigned to the newly created file. o By default, the new file inherits certain attributes from the existing version of the file unless those attributes are specified in the creat call. The following attributes are inherited: - Record format (fab$b_rfm) - Maximum record size (fab$w_mrs) - Carriage control (fab$b_rat) - File protection If the file did not previously exist: o It is given the file protection that results from performing a bitwise AND on the mode argument and the complement of the current protection mask. o It defaults to stream format with line-feed record separator and implied carriage-return attributes. See also open, close, read, write, and lseek in this section. Return Values n A file descriptor. -1 Indicates errors, including protection violations, undefined directories, and conflicting file attributes. REF-80 [no]crmode _________________________________________________________________ [no]crmode In the UNIX system environment, the crmode and nocrmode functions set and unset the terminal from cbreak mode. In cbreak mode, a single input character can be processed without pressing Return. This mode of single-character input is only supported with the Curses input routine getch. Format #include crmode() nocrmode() Example /* Program to demonstrate the use of crmod() and curses */ #include main() { WINDOW *win1; char vert = '.', hor = '.', str[80]; /* Initialize standard screen, turn echo off. */ initscr(); noecho(); /* Define a user window. */ win1 = newwin(22, 78, 1, 1); /* Turn on reverse video and draw a box on border. */ setattr(_REVERSE); box(stdscr, vert, hor); mvwaddstr(win1, 2, 2, "Test cbreak input"); refresh(); wrefresh(win1); REF-81 [no]crmode /* Set cbreak, do some input, and output it. */ crmode(); getch(); nocrmode(); /* Turn off cbreak. */ mvwaddstr(win1, 5, 5, str); mvwaddstr(win1, 7, 7, "Type something to clear the screen"); wrefresh(win1); /* Get another character, then delete the window. */ getch(); wclear(win1); touchwin(stdscr); endwin(); } In this example, the first call to getch returns as soon as one character is entered, because crmode was called before getch was called. The second time getch is called, it waits until the Return key is pressed before processing the character entered, because nocrmode was called before getch was called the second time. REF-82 ctermid _________________________________________________________________ ctermid Returns a character string giving the equivalence string of SYS$COMMAND. This is the name of the controlling terminal. Format #include char *ctermid (char *str); Function Variants This function also has variants named _ctermid32 and _ ctermid64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument str Must be a pointer to an array of characters. If this argument is NULL, the file name is stored internally and might be overwritten by the next ctermid call. Otherwise, the file name is stored beginning at the location indicated by the argument. The argument must point to a storage area of length L_ctermid (defined by the header file). Return Value pointer Points to a character string. REF-83 ctime, ctime_r _________________________________________________________________ ctime, ctime_r Converts a time in seconds, since 00:00:00 January 1, 1970, to an ASCII string in the form generated by the asctime function. Format #include char *ctime (const time_t *bintim); char *ctime_r (const time_t *bintim, char *buffer); (ISO POSIX-1) Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Argument bintim A pointer to a variable that specifies the time value (in seconds) to be converted. buffer A pointer to a character array that is at least 26 bytes long. This array is used to store the generated date-and- time string. Description The ctime and ctime_r functions convert the time pointed to by bintim into a 26-character string, and return a pointer to the string. The difference between the ctime_r and ctime functions is that the former puts its result into a user-specified buffer. The latter puts its result into thread-specific static memory allocated by the Compaq C RTL, which can be REF-84 ctime, ctime_r overwritten by subsequent calls to ctime or asctime; you must make a copy if you want to save it. On success, ctime returns a pointer to the string; ctime_r returns its second argument. On failure, these functions return the NULL pointer. The type time_t is defined in the header file as follows: typedef long int time_t The ctime function behaves as if it called tzset. ________________________ Note ________________________ Generally speaking, UTC-based time functions can affect in-memory time-zone information, which is process-wide data. However, if the system time zone remains the same during the execution of the application (which is the common case) and the cache of timezone files is enabled (which is the default), then the _r variant of the time functions asctime_r, ctime_r, gmtime_r and localtime_r, is both thread-safe and AST-reentrant. If, however, the system time zone can change during the execution of the application or the cache of timezone files is not enabled, then both variants of the UTC-based time functions belong to the third class of functions, which are neither thread-safe nor AST-reentrant. ______________________________________________________ Return Value x A pointer to the 26-character ASCII string, if successful. NULL Indicates failure. REF-85 cuserid _________________________________________________________________ cuserid Returns a pointer to a character string containing the name of the user initiating the current process. Format #include (X/Open, POSIX-1) #include (X/Open) char *cuserid (char *str); Function Variants This function also has variants named _cuserid32 and _ cuserid64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument str If this argument is NULL, the user name is stored internally. If the argument is not NULL, it points to a storage area of length L_cuserid (defined by the header file), and the name is written into that storage. If the user name is a null string, the function returns NULL. Return Values pointer Points to a string. NULL If the user name is a null string. REF-86 DECC$CRTL_INIT _________________________________________________________________ DECC$CRTL_INIT Allows you to call the Compaq C RTL from other languages or to use the Compaq C RTL when your main function is not in C. It initializes the run-time environment and establishes both an exit and condition handler. VAXC$CRTL_INIT is a synonym for DECC$CRTL_INIT. Either name invokes the same routine. Format #include void DECC$CRTL_INIT(void); Description The following example shows a Pascal program that calls the Compaq C RTL using the DECC$CRTL_INIT function: $ PASCAL EXAMPLE1 $ LINK EXAMPLE1 $ TY EXAMPLE1.PAS PROGRAM TESTC(input, output); PROCEDURE DECC$CRTL_INIT; extern; BEGIN DECC$CRTL_INIT; END A shareable image need only call this function if it contains a Compaq C function for signal handling, environment variables, I/O, exit handling, a default file protection mask, or if it is a child process that should inherit context. Although many of the initialization activities are performed only once, DECC$CRTL_INIT can safely be called multiple times. On OpenVMS VAX systems, DECC$CRTL_INIT establishes the Compaq C RTL internal OpenVMS exception handler in the frame of the routine that calls DECC$CRTL_ INIT each time DECC$CRTL_INIT is called. At least one frame in the current call stack must have that handler established for OpenVMS exceptions to get mapped to UNIX signals. REF-87 decc$fix_time _________________________________________________________________ decc$fix_time Converts OpenVMS binary system times to UNIX binary times. Format #include unsigned int decc$fix_time (void *vms_time); Argument vms_time The address of a quadword containing an OpenVMS binary time: unsigned int quadword[2]; unsigned int *vms_time = quadword; Description This routine converts an OpenVMS binary system time (a 64-bit quadword containing the number of 100-nanosecond ticks since 00:00 November 17, 1858) to a UNIX binary time (a longword containing the number of seconds since 00:00 January 1, 1970). This routine is useful for converting binary times returned by OpenVMS system services and RMS services to the format used by some Compaq C RTL routines, such as ctime and localtime. Return Values x A longword containing the number of seconds since 00:00 January 1, 1970. (unsigned int)(-1) Indicates an error. Be aware, that a return value of (unsigned int)(-1) can also represent a valid date of Sun Feb 7 06:28:15 2106. REF-88 decc$fix_time Example #include #include #include /* VMS Specific SYS$ routines) */ main() { unsigned int current_vms_ time[2]; /* quadword for OpenVMS time */ unsigned int number_of_ seconds; /* number of seconds */ /* first get the current system time */ sys$gettim(¤t_vms_time[0]); /* fix the time */ number_of_seconds = decc$fix_time(¤t_vms_ time[0]); printf("Number of seconds since 00:00 January 1, 1970 = %d", number_of_seconds); } This example shows how to use the decc$fix_time routine in Compaq C. It also shows the use of the SYS$GETTIM system service. REF-89 decc$from_vms _________________________________________________________________ decc$from_vms Converts OpenVMS file specifications to UNIX style file specifications. Format #include int decc$from_vms (const char *vms_filespec, int action_routine, int wild_flag); Arguments vms_filespec The address of a null-terminated string containing a name in OpenVMS file specification format. action_routine The address of a routine that takes as its only argument a null-terminated string containing the translation of the given OpenVMS file name to a valid UNIX style file name. If the action_routine returns a nonzero value (TRUE), file translation continues. If it returns a zero value (FALSE), no further file translation takes place. wild_flag Either 0 or 1, passed by value. If a 0 is specified, wildcards found in vms_filespec are not expanded. Otherwise, wildcards are expanded and each one is passed to action_routine. Only expanded file names that correspond to existing UNIX style files are included. Description This routine converts the given OpenVMS file specification into the equivalent UNIX style file specification. It allows you to specify OpenVMS wildcards, which are translated into a list of corresponding existing files in UNIX style file specification format. REF-90 decc$from_vms Return Value x The number of file names that result from the specified OpenVMS file specification. Example /* This example must be run as a foreign command */ /* and be supplied with a VMS file specification */ #include #include int main(int argc, char *argv[]) { int number_ found; /* number of files found */ int print_ name(); /* name printer */ printf("Translating: %s\n", argv[1]); number_found = decc$from_vms(argv[1], print_ name, 1); printf("\n%d files found", number_found); } /* print the name on each line */ print_name(char *name) { printf("\n%s", name); /* will continue as long as success status is returned */ return (1); } This example shows how to use the decc$from_vms routine in Compaq C. It produces a simple form of the ls command that lists existing files that match an OpenVMS file specification supplied on the command line. The matching files are displayed in UNIX style file specification format. REF-91 decc$match_wild _________________________________________________________________ decc$match_wild Matches a string to a pattern. Format #include int decc$match_wild (char *test_string, char *string_pattern); Arguments test_string The address of a null-terminated string. string_pattern The address of a string containing the pattern to be matched. This pattern can contain wildcards (such as asterisks (*), question marks (?), and percent signs (%) as well as regular expressions (such as the range [a-z]). Description This routine determines whether the specified test string is a member of the set of strings specified by the pattern. Return Values 1 (TRUE) The string matches the pattern. 0 (FALSE) The string does not match the pattern. Example /* Define as a foreign command and then provide two parameters */ /* match_wild string_to_ test pattern */ REF-92 decc$match_wild #include #include int main(int argc, char *argv[]) { if (decc$match_wild(argv[1], argv[2])) printf("\n%s matches %s", argv[1], argv[2]); else printf("\n%s does not match %s", argv[1], argv[2]); } REF-93 decc$record_read _________________________________________________________________ decc$record_read Reads a record from a file. Format #include int decc$record_read (FILE *fp, void *buffer, int nbytes); Arguments fp A file pointer. The specified file pointer must refer to a file currently opened for reading. buffer The address of contiguous storage in which the input data is placed. nbytes The maximum number of bytes involved in the read operation. Description This function is specific to OpenVMS systems and should not be used when writing portable applications. The decc$record_read function is functionally equivalent to the read function, except that the first argument is a file pointer, not a file descriptor. Return Values x The number of characters read. -1 Indicates a read error, including physical input errors, illegal buffer addresses, protection violations, undefined file descriptors, and so forth. REF-94 decc$record_write _________________________________________________________________ decc$record_write Writes a record to a file. Format #include int decc$record_write (FILE *fp, void *buffer, int nbytes); Arguments fp A file pointer. The specified file pointer must refer to a file currently opened for writing or updating. buffer The address of contiguous storage from which the output data is taken. nbytes The maximum number of bytes involved in the write operation. Description This function is specific to OpenVMS systems and should not be used when writing portable applications. The decc$record_write function is functionally equivalent to the write function, except that the first argument is a file pointer, not a file descriptor. Return Values x The number of bytes written. -1 Indicates errors, including undefined file descriptors, illegal buffer addresses, and physical I/O errors. REF-95 decc$set_child_standard_streams _________________________________________________________________ decc$set_child_standard_streams For a child spawned by a function from the exec family of functions, associates specified file descriptors with a child's standard streams: stdin, stdout, and stderr. Format #include int decc$set_child_standard_streams (int fd1, int fd2, int fd3); Arguments fd1 The file associated with this file descriptor in the parent process is associated with file descriptor number 0 (stdin) in the child process. If -1 is specified, the file associated with the parent's file descriptor number 0 is used (the default). fd2 The file associated with this file descriptor in the parent process is associated with file descriptor number 1 (stdout) in the child process. If -1 is specified, the file associated with the parent's file descriptor number 1 is used (the default). fd3 The file associated with this file descriptor in the parent process is associated with file descriptor number 2 (stderr) in the child process. If -1 is specified, the file associated with the parent's file descriptor number 2 is used (the default). REF-96 decc$set_child_standard_streams Description This function allows mapping of specified file descriptors to the child's stdin/out/err streams, thereby compensating, to a certain degree, the lack of a real fork function on OpenVMS systems. On UNIX systems, the code between fork and exec is executed in the context of the child process: parent: create pipes p1, p2 and p3 fork child: map stdin to p1 like dup2(stdin, p1); map stdout to p2 like dup2(stdout, p2); map stderr to p3 like dup2(stderr, p3); exec (child reads from stdin and writes to stdout and stderr) exit parent: communicates with the child using pipes On OpenVMS systems, the same task could be achieved as follows: parent: create pipes p1, p2 and p3 decc$set_child_standard_streams(p1, p2, p3); vfork exec (child reads from stdin and writes to stdout and stderr) parent: communicates with the child using pipes Once established through the call to decc$set_child_ standard_streams, the mapping of the child's standard streams remains in effect until explicitly disabled by one of the following calls: decc$set_child_standard_streams(-1, -1, -1); OR decc$set_child_standard_streams(0, 1, 2); REF-97 decc$set_child_standard_streams Usually, the child process inherits all its parent's open file descriptors. However, if file descriptor number n was specified in the call to decc$set_child_standard_streams, it is not inherited by the child process as file descriptor number n; instead, it becomes one of the child's standard streams. ________________________ Notes ________________________ o Standard streams can be redirected only to pipes. o If the parent process redefines the DCL DEFINE command, this redefinition is not in effect in a subprocess with user-defined channels. The subprocess always sees the standard DCL DEFINE command. o It is the responsibility of the parent process to consume all the output written by the child process to stdout and stderr. Depending on how the subprocess writes to stdout and stderr - in wait or nowait mode-the subprocess might be placed in LEF state waiting for the reader. For example, DCL writes to SYS$OUTPUT and SYS$ERROR in a wait mode, so a child process executing a DCL command procedure will wait until all the output is read by the parent process. Recommendation: Read the pipes associated with the child process' stdout and stderr in a loop until an EOF message is received, or declare write attention ASTs on these mailboxes. o The amount of data written to SYS$OUTPUT depends on the verification status of the process (SET VERIFY/NOVERIFY command); the subprocess inherits the verification status of the parent process. It is the caller's responsibility to set the verification status of the parent process to match the expected amount of data written to SYS$OUTPUT by the subprocess. REF-98 decc$set_child_standard_streams o Some applications, like DTM, define SYS$ERROR as SYS$OUTPUT. If stderr is not redefined by the caller, it is set in the subprocess as the parent's SYS$ERROR, which in this case translates to the parent's SYS$OUTPUT. If the caller redefines stdout to a pipe and does not redefine stderr, output sent to stderr goes to the pipe associated with stdout, and the amount of data written to this mailbox may be more than expected. Although redefinition of any subset of standard channels is supported, it is always safe to explicitly redefine all of them (or at least stdout and stderr) to avoid this situation. o For a child process executing a DCL command procedure, SYS$COMMAND is set to the pipe specified for the child's stdin so that the parent process can feed the child requesting data from SYS$COMMAND through the pipe. For DCL command procedures, it is impossible to pass data from the parent to the child by means of the child's SYS$INPUT because for a command procedure, DCL defines SYS$INPUT as the command file itself. ______________________________________________________ Return Value x The number of file descriptors set for the child. This number does not include file descriptors specified as -1 in the call. -1 indicates that an invalid file descriptor was specified; errno is set to EBADF. REF-99 decc$set_child_standard_streams Example parent.c ======== #include #include #include int decc$set_child_standard_streams(int, int, int); main() { int fdin[2], fdout[2], fderr[2]; char msg[] = "parent writing to child's stdin"; char buf[80]; int nbytes; pipe(fdin); pipe(fdout); pipe(fderr); if ( vfork() == 0 ) { decc$set_child_standard_ streams(fdin[0], fdout[1], fderr[1]); execl( "child", "child" ); } else { write(fdin[1], msg, sizeof(msg)); nbytes = read(fdout[0], buf, sizeof(buf)); buf[nbytes] = '\0'; puts(buf); nbytes = read(fderr[0], buf, sizeof(buf)); buf[nbytes] = '\0'; puts(buf); } } child.c ======= #include #include REF-100 decc$set_child_standard_streams main() { char msg[] = "child writing to stderr"; char buf[80]; int nbytes; nbytes = read(0, buf, sizeof(buf)); write(1, buf, nbytes); write(2, msg, sizeof(msg)); } child.com ========= $ read sys$command s $ write sys$output s $ write sys$error "child writing to stderr" This example program returns the following for both child.c and child.com: $ run parent parent writing to child's stdin child writing to stderr Note that in order to activate child.com, you must explicitly specify execl("child.com", ...) in the parent.c program. REF-101 decc$set_reentrancy _________________________________________________________________ decc$set_reentrancy Controls the type of reentrancy that reentrant Compaq C RTL routines will exhibit. Format #include int decc$set_reentrancy (int type); Argument type The type of reentrancy desired. Use one of the following values: o C$C_MULTITHREAD - Designed to be used in conjunction with the DECthreads product. It performs DECthreads locking and never disables ASTs. DECthreads must be available on your system to use this form of reentrancy. o C$C_AST - Uses the _BBSSI (VAX only) or __TESTBITSSI (Alpha only) built-in function to perform simple locking around critical sections of RTL code, and it may additionally disable asynchronous system traps (ASTs) in locked regions of code. This type of locking should be used when AST code contains calls to Compaq C RTL I/O routines, or when the user application disables ASTs. o C$C_TOLERANT - Uses the _BBSSI (VAX only) or __TESTBITSSI (Alpha only) built-in function to perform simple locking around critical sections of RTL code, but ASTs are not disabled. This type of locking should be used when ASTs are used and must be delivered immediately. TOLERANT is the default reentrancy type. o C$C_NONE - Gives optimal performance in the Compaq C RTL, but does absolutely no locking around critical sections of RTL code. It should only be used in a single-threaded environment when there is no chance that the thread of execution will be interrupted by an AST that would call the Compaq C RTL. REF-102 decc$set_reentrancy The reentrancy type can be raised but never lowered. The ordering of reentrancy types from low to high is C$C_NONE, C$C_TOLERANT, C$C_AST and C$C_MULTITHREAD. For example, once an application is set to multithread, a call to set the reentrancy to AST is ignored. A call to decc$set_ reentrancy that attempts to lower the reentrancy type returns a value of -1. Description Use this function to change the type of reentrancy exhibited by reentrant routines. decc$set_reentrancy must be called exclusively at the non- AST level. In an application using DECthreads, DECthreads automatically sets the reentrancy to multithread. Return Value type The type of reentrancy used before this call. -1 The reentrancy was set to a lower type. REF-103 decc$to_vms _________________________________________________________________ decc$to_vms Converts UNIX style file specifications to OpenVMS file specifications. Format #include int decc$to_vms (const char *unix_style_filespec, int (*action_routine)(char *unix_style_filespec, int type_of_file), int allow_wild, int no_directory); Arguments unix_style_filespec The address of a null-terminated string containing a name in UNIX style file specification format. action_routine The address of a routine that accepts the following arguments: o A pointer to a null-terminated string that contains the UNIX style file name to be translated to a valid OpenVMS file name o An integer that has one of the following values: ________________________________________________________ Value_______________Translation_________________________ 0 (DECC$K_FOREIGN) A file on a remote system that is not running the OpenVMS or VAXELN operating system. 2 (DECC$K_ The OpenVMS translation of the UNIX DIRECTORY) style file name is a directory. 1_(DECC$K_FILE)_____The_translation_is_a_file.__________ These values can be defined symbolically with the symbols DECC$K_FOREIGN, DECC$K_DIRECTORY, and DECC$K_ FILE. See the example for more information. REF-104 decc$to_vms If action_routine returns a nonzero value (TRUE), file translation continues. If it returns a 0 value (FALSE), no further file translation takes place. allow_wild Either 0 or 1, passed by value. If a 0 is specified, wildcards found in unix_style_filespec are not expanded. Otherwise, wildcards are expanded and each one is passed to action_routine. Only expanded file names that correspond to existing OpenVMS files are included. no_directory An integer that has one of the following values: ___________________________________________________________ Value_______________Translation____________________________ 0 Directory is not allowed. 1 Prevent expansion of the string as a directory name. 2___________________Forced_to_be_a_directory_name._________ Description This routine converts the given UNIX style file specification into the equivalent OpenVMS file specification (in all uppercase letters). It allows you to specify UNIX style wildcards, which are translated into a list of corresponding OpenVMS files. Return Value x The number of file names that result from the specified UNIX style file specification. REF-105 decc$to_vms Example /* Translate "Unix" wildcard file names to VMS names */ /* Define as a foreign command and provide the name */ /* as an argument. */ #include #include int print_name(char *, int); int main(int argc, char *argv[]) { int number_ found; /* number of files found */ printf("Translating: %s\n", argv[1]); number_found = decc$to_vms(argv[1], print_ name, 1, 0); printf("%d files found\n", number_found); } /* action routine that prints name and type on each line */ int print_name(char *name, int type) { if (type == DECC$K_DIRECTORY) printf("directory: %s\n", name); else if (type == DECC$K_FOREIGN) printf("remote non-VMS: %s\n", name); else printf("file: %s\n", name); /* Translation continues as long as success status is returned */ return (1); } This example shows how to use the decc$to_vms routine in Compaq C. It takes a UNIX style file specification argument and displays, in OpenVMS file specification format, the name of each existing file that matches it. REF-106 decc$translate_vms _________________________________________________________________ decc$translate_vms Translates OpenVMS file specifications to UNIX style file specifications. Format #include char *decc$translate_vms (const char *vms_filespec); Argument vms_filespec The address of a null-terminated string containing a name in OpenVMS file specification format. Description This function translates the given OpenVMS file specification into the equivalent UNIX style file specification, whether or not the file exists. The translated name string is stored in a thread- specific memory, which is overwritten by each call to decc$translate_vms from the same thread. This function differs from the decc$from_vms function, which does the conversion for existing files only. Return Values x The address of a null-terminated string containing a name in UNIX style file specification format. 0 Indicates that the file name is null or syntactically incorrect. REF-107 decc$translate_vms -1 Indicates that the file specification contains an ellipsis (for example, [ . . . ]a.dat), but is otherwise correct. You cannot translate the OpenVMS ellipsis syntax into a valid UNIX style file specification. Example /* Demonstrate translation of a "UNIX" name to VMS form */ /* define a foreign command and pass the name as the */ /* argument. */ #include #include int main(int argc, char *argv[]) { char *ptr; /* translation result */ ptr = decc$translate_vms( argv[1] ); if ((int) ptr == 0 || (int) ptr == -1) printf( "could not translate %s\n", argv[1]); else printf( "%s is translated to %s\n", argv[1], ptr ); } REF-108 decc$validate_wchar _________________________________________________________________ decc$validate_wchar Confirms that its argument is a valid wide character in the current program's locale. Format #include int decc$validate_wchar (wchar_t wc); Argument wc Wide character to be validated. Description This function provides a convenient way to verify whether a specified argument of wchar_t type is a valid wide character in the current program's locale. One reason to call decc$validate_wchar is that the isw* wide-character classification functions and macros do not validate their argument before dereferencing the classmask array describing character properties. Passing an isw* function a value that exceeds the maximum wide-character value for the current program's locale can result in an attempt to access memory beyond the allocated classmask array. A standard way to validate a wide character is to call the wctomb function, but this way is less convenient because it requires declaring a multibyte character array of sufficient size and passing it to wctomb. Return Values 1 Indicates that the specified wide character is a valid wide character in the current program's locale. REF-109 decc$validate_wchar 0 Indicates that the specified wide character is not a valid wide character in the current program's locale. errno is not set. REF-110 decc$write_eof_to_mbx _________________________________________________________________ decc$write_eof_to_mbx Writes an end-of-file message to the mailbox. Format #include int decc$write_eof_to_mbx (int fd); Argument fd File descriptor associated with the mailbox. Description This function writes end-of-file message to the mailbox. For a mailbox that is not a pipe, the write function called with an nbytes parameter value of 0 sends an end-of-file message to the mailbox. For a pipe, however, the only way to write an end-of-file message to the mailbox is to close the pipe. If the child's standard input is redirected to a pipe through a call to the decc$set_child_standard_streams function, the parent process can call decc$write_eof_to_ mbx for this pipe to send an EOF message to the child. It has the same effect as if the child read the data from a terminal, and Ctrl/Z was pressed. After a call to decc$write_eof_to_mbx, the pipe can be reused for communication with another child, for example. This is the purpose of decc$write_eof_to_mbx: to allow reuse of the pipe instead of having to close it just to send an end-of-file message. REF-111 decc$write_eof_to_mbx Return Values 0 Indicates success -1 Indicates failure; errno and vaxc$errno are set according to the failure status returned by SYS$QIOW. Example /* decc$write_eof_to_mbx_example.c */ #include #include #include #include #include #include #include #include #include int decc$write_eof_to_mbx( int ); main() { int status, nbytes, failed = 0; int fd, fd2[2]; short int channel; $DESCRIPTOR(mbxname_dsc, "TEST_MBX"); char c; /* first try a mailbox created by SYS$CREMBX */ status = sys$crembx(0, &channel, 0, 0, 0, 0, &mbxname_ dsc, 0, 0); if ( status != SS$_NORMAL ) { printf("sys$crembx failed: %s\n",strerror(EVMSERR, status)); failed = 1; } REF-112 decc$write_eof_to_mbx if ( (fd = open(mbxname_dsc.dsc$a_pointer, O_ RDWR, 0)) == -1 ) { perror("? open mailbox"); failed = 1; } if ( decc$write_eof_to_mbx(fd) == -1 ) { perror("? decc$write_eof_to_mbx to mailbox"); failed = 1; } if ( (nbytes = read(fd, &c, 1)) != 0 || errno != 0 ) { perror("? read mailbox"); printf("? nbytes = %d\n", nbytes); failed = 1; } if ( close(fd) == -1 ) { perror("? close mailbox"); failed = 1; } /* Now do the same thing with a pipe */ errno = 0; /* Clear errno for consistency */ if ( pipe(fd2) == -1 ) { perror("? opening pipe"); failed = 1; } if ( decc$write_eof_to_mbx(fd2[1]) == -1 ) { perror("? decc$write_eof_to_mbx to pipe"); failed = 1; } if ( (nbytes = read(fd2[0], &c, 1)) != 0 || errno != 0 ) { perror("? read pipe"); printf("? nbytes = %d\n", nbytes); failed = 1; } /* Close both file descriptors involved with the pipe */ if ( close(fd2[0]) == -1 ) { perror("close(fd2[0])"); failed = 1; } REF-113 decc$write_eof_to_mbx if ( close(fd2[1]) == -1 ) { perror("close(fd2[1])"); failed = 1; } if ( failed ) puts("?Example program failed"); else puts("Example ran to completion"); } This example program produces the following result: Example ran to completion REF-114 [w]delch _________________________________________________________________ [w]delch Delete the character on the specified window at the current position of the cursor. The delch function operates on the stdscr window. Format #include int delch(); int wdelch (WINDOW *win); Argument win A pointer to the window. Description All of the characters to the right of the cursor on the same line are shifted to the left, and a blank character is appended to the end of the line. Return Values OK Indicates success. ERR Indicates an error. REF-115 delete _________________________________________________________________ delete Deletes a file. Format #include int delete (const char *file_spec); Argument file_spec A pointer to the string that is an OpenVMS or UNIX style file specification. The file specification can include a wildcard in its version number (but not in any other part of the file spec). So, for example, files of the form filename.txt;* can be deleted. Description If you specify a directory in the file name and it is a search list that contains an error, Compaq C for OpenVMS Systems interprets it as a file error. The remove and delete functions are functionally equivalent in the Compaq C RTL. See also remove in this section. ________________________ Note ________________________ The delete routine is not available to C++ programmers because it conflicts with the C++ reserved word delete. C++ programmers should use the ANSI/ISO C standard function remove instead. ______________________________________________________ REF-116 delete Return Values 0 Indicates success. nonzero value Indicates that the operation has failed. REF-117 [w]deleteln _________________________________________________________________ [w]deleteln Delete the line at the current position of the cursor. The deleteln function acts on the stdscr window. Format #include int deleteln(); int wdeleteln (WINDOW *win); Argument win A pointer to the window. Description Every line below the deleted line moves up, and the bottom line becomes blank. The current (y,x) coordinates of the cursor remain unchanged. Return Values OK Indicates success. ERR Indicates an error. REF-118 delwin _________________________________________________________________ delwin Deletes the specified window from memory. Format #include int delwin (WINDOW *win); Argument win A pointer to the window. Description If the window being deleted contains a subwindow, the subwindow is invalidated. Delete subwindows before deleting their parent. The delwin function refreshes all windows covered by the deleted window. Return Values OK Indicates success. ERR Indicates an error. REF-119 difftime _________________________________________________________________ difftime Computes the difference, in seconds, between the two times specified by the time1 and time2 arguments. Format #include double difftime (time_t time2, time_t time1); Arguments time2 A time value of type time_t. time1 A time value of type time_t. Description The type time_t is defined in the header file as follows: typedef unsigned long int time_t Return Value n time2 - time1 in seconds expressed as a double. REF-120 dirname _________________________________________________________________ dirname Reports the parent directory name of a file path name. Format #include char *dirname (char *path); Function Variants This function also has variants named _dirname32 and _ dirname64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument path The file path name. Description This function takes a pointer to a character string that contains a UNIX path name and returns a pointer to a string that is a path name of the parent directory of that file. Trailing '/' (slash) characters in the path are not counted as part of the path. The dirname function returns a pointer to the string "." (dot), when the path argument: o Does not contain a '/' (slash). o Is a NULL pointer. o Points to an empty string. The dirname function can modify the string pointed to by the path argument. The dirname and basename functions together yield a complete path name. The expression dirname(path) obtains the path name of the directory where basename(path) is found. REF-121 dirname See also basename in this section. Return Values x A pointer to a string that is the parent directory of the path argument. "." The path argument: o Does not contain a '/' (slash). o Is a NULL pointer. o Points to an empty string. Example Using the dirname function, the following example reads a path name, changes the current working directory to the parent directory, and opens a file. char path [MAXPATHLEN], *pathcopy; int fd; fgets(path, MAXPATHLEN, stdin); pathcopy = strdup(path); chdir(dirname(pathcopy)); fd = open(basename(path), O_RDONLY); REF-122 div _________________________________________________________________ div Returns the quotient and the remainder after the division of its arguments. Format #include div_t div (int numer, int denom); Arguments numer A numerator of type int. denom A denominator of type int. Description The type div_t is defined in the standard header file as follows: typedef struct { int quot, rem; } div_t; REF-123 dlclose _________________________________________________________________ dlclose Deallocates the address space for a shared library. Format #include void dlclose (void *handle); Arguments handle Pointer to the shared library. Description The dlclose function deallocates the address space allocated by the Compaq C RTL for the handle. There is no way on OpenVMS systems to "unload" a shareable image dynamically loaded by the LIB$FIND_IMAGE_SYMBOL routine, which is the routine called by the dlsym function. In other words, there is no way on OpenVMS systems to release the address space occupied by the shareable image brought into memory by dlsym. REF-124 dlerror _________________________________________________________________ dlerror Returns a string describing the last error that occurred from a call to dlopen, dlclose, or dlsym. Format #include char *dlerror (void); Description Return Values x A string describing the last error that occurred from a call to dlopen, dlclose, or dlsym. REF-125 dlopen _________________________________________________________________ dlopen Provides an interface to the dynamic library loader to allow shareable images to be loaded and called at run time. Format #include void *dlopen (char *pathname, int mode); Arguments pathname The name of the shareable image. This name is saved for subsequent use by the dlsym function. mode This parameter is ignored on OpenVMS systems. Description This function provides an interface to the dynamic library loader to allow shareable images to be loaded and called at run time. The dlopen function does not load a shareable image but rather saves its pathname argument for subsequent use by the dlsym function. dlsym is the function that actually loads the shareable image through a call to LIB$FIND_IMAGE_ SYMBOL. The pathname argument of the dlopen function must be the name of the shareable image. This name is passed as-is by the dlsym function to the LIB$FIND_IMAGE_SYMBOL routine as the filename argument. No image-name argument is specified in the call to LIB$FIND_IMAGE_SYMBOL, so default file specification of SYS$SHARE:.EXE is applied to the image name. The dlopen function returns a handle that is used by a dlsym or dlclose call. If an error occurs, a NULL pointer is returned. REF-126 dlopen Return Values x A handle to be used by a dlsym or dlclose call. NULL Indicates an error. REF-127 dlsym _________________________________________________________________ dlsym Returns the address of the symbol name found in a shareable image. Format #include void *dlsym (void *handle, char *name); Arguments handle Pointer to the shareable image. Description The dlsym function returns the address of the symbol name found in the shareable image corresponding to handle. If the symbol is not found, a NULL pointer is returned. Return Values x Address of the symbol name found. NULL Indicates that the symbol was not found. REF-128 drand48 _________________________________________________________________ drand48 Generates uniformly distributed pseudorandom number sequences. Returns 48-bit, nonnegative, double-precision floating-point values. Format #include double drand48 (void); Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. It returns non-negative, double-precision, floating-point values uniformly distributed over the range of y values such that 0.0 y < 1.0. Before you call drand48, use either srand48, seed48, or lcong48 to initialize the random number generator. You must initalize prior to invoking the drand48 function because it stores the last 48-bit Xi generated into an internal buffer. (Although it is not recommended, constant default initializer values are supplied automatically if the drand48, lrand48, or mrand48 functions are called without first calling an initialization function.) The drand48 function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke lcong48, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 REF-129 drand48 The values returned by drand48 are computed by first generating the next 48-bit Xi in the sequence. Then the appropriate bits, according to the type of returned data item, are copied from the high-order (most significant) bits of Xi and transformed into the returned value. See also srand48, seed48, lcong48, lrand48, and mrand48 in this section. Return Values n A nonnegative, double-precision, floating-point value. REF-130 dup, dup2 _________________________________________________________________ dup, dup2 Allocate a new descriptor that refers to a file specified by a file descriptor returned by open, creat, or pipe. Format #include int dup (int file_desc1); int dup2 (int file_desc1, int file_desc2); Arguments file_desc1 The file descriptor being duplicated. file_desc2 The new file descriptor to be assigned to the file designated by file_desc1. Description The dup function causes a previously unallocated descriptor to refer to its argument, while the dup2 function causes its second argument to refer to the same file as its first argument. The argument file_desc1 is invalid if it does not describe an open file; file_desc2 is invalid if the new file descriptor cannot be allocated. If file_desc2 is connected to an open file, that file is closed. Return Values n The new file descriptor. -1 Indicates that an invalid argument was passed to the function. REF-131 [no]echo _________________________________________________________________ [no]echo Set the terminal so that characters may or may not be echoed on the terminal screen. This mode of single- character input is only supported with Curses. Format #include void echo (void); void noecho (void); Description The noecho function may be helpful when accepting input from the terminal screen with wgetch and wgetstr; it prevents the input characters from being written onto the screen. REF-132 ecvt _________________________________________________________________ ecvt Converts its argument to a null-terminated string of ASCII digits and returns the address of the string. The string is stored in a thread-specific memory location created by the Compaq C RTL. Format #include char *ecvt (double value, int ndigits, int *decpt, int *sign); Arguments value An object of type double that is converted to a null- terminated string of ASCII digits. ndigits The number of ASCII digits to be used in the converted string. decpt The position of the decimal point relative to the first character in the returned string. A negative int value means that the decimal point is decpt number of spaces to the left of the returned digits, (the spaces being filled with zeros). A 0 value means that the decimal point is immediately to the left of the first digit in the returned string. sign An integer value that indicates whether the value argument is positive or negative. If value is negative, the function places a nonzero value at the address specified by sign. Otherwise, the function assigns 0 to the address specified by sign. REF-133 ecvt Description This function converts value to a null-terminated string of length ndigits, and returns a pointer to it. The resulting low-order digit is rounded to the correct digit for outputting ndigits digits in C E-format. The decpt argument is assigned the position of the decimal point relative to the first character in the string. Repeated calls to the ecvt function overwrite any existing string. The ecvt, fcvt, and gcvt functions represent the following special values specified in the IEEE Standard for floating- point arithmetic: ___________________________________________________________ Value___________Representation_____________________________ Quiet NaN NaNQ Signalling NaN NaNS +Infinity Infinity -Infinity_______-Infinity__________________________________ The sign associated with each of these values is stored into the sign argument. In IEEE floating-point representation, a value of 0 (zero) can be positive or negative, as set by the sign argument. See also gcvt and fcvt in this section. Return Value x The value of the converted string. REF-134 endwin _________________________________________________________________ endwin Clears the terminal screen and frees any virtual memory allocated to Curses data structures. Format #include void endwin (void); Description A program that calls Curses functions must call the endwin function before exiting to restore the previous environment of the terminal screen. REF-135 erand48 _________________________________________________________________ erand48 Generate uniformly distributed pseudorandom number sequences. Returns 48-bit nonnegative, double-precision, floating-point values. Format #include double erand48 (unsigned short int xsubi[3]); Argument xsubi An array of three short int, which form a 48-bit integer when concatentated together. Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. It returns nonnegative, double-precision, floating-point values uniformly distributed over the range of y values, such that, 0.0 y < 1.0. The erand48 function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 The erand48 function requires that the calling program pass an array as the xsubi argument. For the first call, the array must be initialized to the value of the pseudorandom number sequence. Unlike the drand48 function, it is not REF-136 erand48 necessary to call an initialization function prior to the first call. By using different arguments, the erand48 function allows separate modules of a large program to generate several independent sequences of pseudorandom numbers; for example, the sequence of numbers that one module generates does not depend upon how many times the function is called by other modules. Return Values n A nonnegative, double-precision, floating-point value. REF-137 [w]erase _________________________________________________________________ [w]erase Erase the window by painting it with blanks. The erase function acts on the stdscr window. Format #include int erase(); int werase (WINDOW *win); Argument win A pointer to the window. Description Both the erase and werase functions leave the cursor at the current position on the terminal screen after completion; they do not return the cursor to the home coordinates of (0,0). Return Values OK Indicates success. ERR Indicates an error. REF-138 execl _________________________________________________________________ execl Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execl (const char *file_spec, const char *arg0, . . . , (char *)0); (ISO POSIX-1) int execl (char *file_spec, . . . ); (Compatability) Arguments file_spec The full file specification of a new image to be activated in the child process. arg0, ... A sequence of pointers to null-terminated character strings. If the POSIX-1 format is used, at least one argument must be present and must point to a string that is the same as the new process file name (or its last component). (This pointer can also be the NULL pointer, but then execle would accomplish nothing.) The last pointer must be the NULL pointer. This is also the convention if the compatibility format is used. Description To understand how the exec functions operate, consider how the OpenVMS system calls any Compaq C program, as shown in the following syntax: int main (int argc, char *argv[], char *envp[]); The identifier argc is the argument count; argv is an array of argument strings. The first member of the array (argv[0]) contains the name of the image. The arguments are placed in subsequent elements of the array. The last element of the array is always the NULL pointer. REF-139 execl An exec function calls a child process in the same way that the run-time system calls any other Compaq C program. The exec functions pass the name of the image to be activated in the child; this value is placed in argv[0]. However, the functions differ in the way they pass arguments and environment information to the child: o Arguments can be passed in separate character strings (execl, execle, and execlp) or in an array of character strings (execv, execve, and execvp). o The environment can be explicitly passed in an array (execle and execve) or taken from the parent's environment (execl, execv, execlp, and execvp). If vfork was called before invoking an exec function, then when the exec function completes, control is returned to the parent process at the point of the vfork call. If vfork was not called, the exec function waits until the child has completed execution and then exits the parent process. See vfork in this section and Chapter 5 for more information. Return Value -1 Indicates failure. REF-140 execle _________________________________________________________________ execle Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execle (char *file_spec, char *arg0, . . . , (char *)0, char *envp[]); (ISO POSIX-1) int execle (char *file_spec, . . . ); (Compatability) Arguments file_spec The full file specification of a new image to be activated in the child process. arg0, ... A sequence of pointers to null-terminated character strings. If the POSIX-1 format is used, at least one argument must be present and must point to a string that is the same as the new process file name (or its last component). (This pointer can also be the NULL pointer, but then execle would accomplish nothing.) The last pointer must be the NULL pointer. This is also the convention if the compatibility format is used. envp An array of strings that specifies the program's environment. Each string in envp has the following form: name = value The name can be one of the following names and the value is a null-terminated string to be associated with the name: o HOME-Your login directory o TERM-The type of terminal being used o PATH-The default device and directory REF-141 execle o USER-The name of the user who initiated the process The last element in envp must be the NULL pointer. When the operating system executes the program, it places a copy of the current environment vector (envp) in the external variable environ. Description See execl in this section for a description of how the exec functions operate. Return Value -1 Indicates failure. REF-142 execlp _________________________________________________________________ execlp Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execlp (const char *file_name, const char *arg0, . . . , (char *)0); (ISO POSIX-1) int execlp (char *file_name, . . . ); (Compatability) Arguments file_name The file name of a new image to be activated in the child process. The device and directory specification for the file is obtained by searching the environment name VAXC$PATH. argn A sequence of pointers to null-terminated character strings. By convention, at least one argument must be present and must point to a string that is the same as the new process file name (or its last component). . . . A sequence of pointers to strings. At least one pointer must exist to terminate the list. This pointer must be the NULL pointer. Description See execl in this section for a description of how the exec functions operate. Return Value -1 Indicates failure. REF-143 execv _________________________________________________________________ execv Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execv (char *file_spec, char *argv[]); Arguments file_spec The full file specification of a new image to be activated in the child process. argv An array of pointers to null-terminated character strings. These strings constitute the argument list available to the new process. By convention, argv[0] must point to a string that is the same as the new process file name (or its last component). argv is terminated by a NULL pointer. Description See execl in this section for a description of how the exec functions operate. Return Value -1 Indicates failure. REF-144 execve _________________________________________________________________ execve Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execve (const char *file_spec, char *argv[], char *envp[]); Arguments file_spec The full file specification of a new image to be activated in the child process. argv An array of pointers to null-terminated character strings. These strings constitute the argument list available to the new process. By convention, argv[0] must point to a string that is the same as the new process file name (or its last component). argv is terminated by a NULL pointer. envp An array of strings that specifies the program's environment. Each string in envp has the following form: name = value The name can be one of the following names and the value is a null-terminated string to be associated with the name: o HOME-Your login directory o TERM-The type of terminal being used o PATH-The default device and directory o USER-The name of the user who initiated the process The last element in envp must be the NULL pointer. When the operating system executes the program, it places a copy of the current environment vector (envp) in the external variable environ. REF-145 execve Description See execl in this section for a description of how the exec functions operate. Return Value -1 Indicates failure. REF-146 execvp _________________________________________________________________ execvp Passes the name of an image to be activated in a child process. This function is nonreentrant. Format #include int execvp (const char *file_name, char *argv[]); Arguments file_name The file name of a new image to be activated in the child process. The device and directory specification for the file is obtained by searching the environment name VAXC$PATH. argv An array of pointers to null-terminated character strings. These strings constitute the argument list available to the new process. By convention, argv[0] must point to a string that is the same as the new process file name (or its last component). argv is terminated by a NULL pointer. Description See execl in this section for a description of how the exec functions operate. Return Value -1 Indicates failure. REF-147 exit, _exit _________________________________________________________________ exit, _exit Terminate execution of the program from which they are called. These functions are nonreentrant. Format #include void exit (int status); #include void _exit (int status); Argument status A status value of EXIT_SUCCESS (0), EXIT_FAILURE (1), or a number from 2 to 255: o A status value of 0 or EXIT_SUCCESS is translated to the OpenVMS SS$_NORMAL status code to return the OpenVMS success value. o A status value of 1 or EXIT_FAILURE is translated to an error-level exit status. The status value is passed to the parent process. o Any other status value is left the same. To use these status values as described, include and compile with the _POSIX_EXIT feature-test macro set (either with /DEFINE=_POSIX_EXIT or with #define _POSIX_ EXIT at the top of your file, before any file inclusions). This behavior is available only on OpenVMS Version 7.0 and higher systems. Description If the process was invoked by the DIGITAL Command Language (DCL), the status is interpreted by DCL and a message is displayed. REF-148 exit, _exit If the process was a child process created using vfork or an exec function, then the child process exits and control returns to the parent. The two functions are identical; the _exit function is retained for reasons of compatibility with VAX C. The exit and _exit functions make use of the $EXIT system service. If your process is being invoked by the RUN command using any of the hibernation and scheduled wakeup qualifiers, the process might not correctly return to hibernation state when an exit or _exit call is made. ________________________ Note ________________________ EXIT_SUCCESS and EXIT_FAILURE are portable across any ANSI C compiler to indicate success or failure. On OpenVMS systems, they are mapped to OpenVMS condition codes with the severity set to success or failure, respectively. Values in the range of 2 to 255 can be used by a child process to communicate a small amount of data to the parent. The parent retreives this data using the wait, wait3, wait4, or waitpid functions. ______________________________________________________ REF-149 exp _________________________________________________________________ exp Returns the base e raised to the power of the argument. Format #include double exp (double x); Argument x A real value. Description If an overflow occurs, the exp function returns the largest possible floating-point value and sets errno to ERANGE. The constant HUGE_VAL is defined in the header file to be the largest possible floating-point value. Return Value x The base e raised to the power of the argument. HUGE_VAL Indicates overflow; errno is set to ERANGE. REF-150 fabs _________________________________________________________________ fabs Returns the absolute value of a floating-point value. Format #include double fabs (double x); Argument x A real value. Return Value x The absolute value of the argument. REF-151 fchown _________________________________________________________________ fchown Changes the owner and group of a file. Format #include int fchown (int fildes, uid_t owner, gid_t group); Arguments fildes An open file descriptor. owner A user ID corresponding to the new owner of the file. group A group ID corresponding to the group of the file. Description The fchown function has the same effect as chown except that the file whose owner and group are to be changed is specified by the file descriptor fildes. Return Values 0 Indicates success. REF-152 fchown -1 Indicates failure. The function sets errno to one of the following values: The fchown function will fail if: o EBADF - The fildes argument is not an open file descriptor. o EPERM - The effective user ID does not match the owner of the file, or the process does not have appropriate privilege. o EROFS - The file referred to by fildes resides on a read-only file system. The fchown function may fail if: o EINVAL - The owner or group ID is not a value supported by the implementation. o EIO - A physical I/O error has occurred. o EINTR - The fchown function was interrupted by a signal that was caught. REF-153 fclose _________________________________________________________________ fclose Closes a file by flushing any buffers associated with the file control block and freeing the file control block and buffers previously associated with the file pointer. Format #include int fclose (FILE *file_ptr); Argument file_ptr A pointer to the file to be closed. Description When a program terminates normally, the fclose function is automatically called for all open files. The fclose function tries to write buffered data by using an implicit call to fflush. If the write fails (because the disk is full or the user's quota is exceeded, for example), fclose continues executing. It closes the VMS channel, deallocates any buffers, and releases the memory associated with the file descriptor (or FILE pointer). Any buffered data is lost, and the file descriptor (or FILE pointer) no longer refers to the file. If your program needs to recover from errors when flushing buffered data, it should make an explicit call to fsync (or fflush) before calling fclose. Return Values 0 Indicates success. EOF Indicates that the file control block is not associated with an open file. REF-154 fcntl _________________________________________________________________ fcntl Performs controlling operations on an open file. Format #include #include #include int fcntl (int file_desc, int request [, int file_desc2]); Arguments file_desc An open file descriptor obtained from a successful open, fcntl, or pipe function. request The operation to be performed. file_desc2 A variable that depends on the value of the request parameter. Description The fcntl function performs controlling operations on the open file specified by the file_desc parameter. The values for the request parameter are defined in the header file , and include the following: REF-155 fcntl F_DUPFD Returns a new file descriptor that is the lowest numbered available (that is, not already open) file descriptor greater than or equal to the third argument (file_desc2) taken as an integer of type int. The new file descriptor refers to the same file as the original file descriptor (file_ desc). The FD_CLOEXEC flag associated with the new file descriptor is cleared to keep the file open across calls to one of the exec functions. The following two calls are equivalent: fid = dup(file_desc); fid = fcntl(file_desc, F_DUPFD, 0); The following call fid = dup2(file_desc, file_desc2); is similar (but not equivalent) to: close(file_desc2); fid = fcntl(file_desc, F_DUPFD, file_desc2); F_GETFD Gets the value of the close-on-exec flag associated with the file descriptor file_ desc. File descriptor flags are associated with a single file descriptor and do not affect other file descriptors that refer to the same file. The file_desc2 parameter should not be specified. REF-156 fcntl F_SETFD Sets the close-on-exec flag associated with file_desc to the value of the third argument, taken as type int: If the third argument is 0 (zero), the file remains open across the exec functions, which means that a child process spawned by the exec function inherits this file descriptor from the parent. If the third argument is FD_CLOEXEC, the file is closed on successful execution of the next exec function, which means that the child process spawned by the exec function will not inherit this file descriptor from the parent. Return Values n Upon successful completion, the value returned depends on the value of the request parameter as follows: o F_DUPFD - Returns a new file descriptor. o F_GETFD - Returns FD_CLOEXEC or 0 (zero). o F_SETFD - Returns a value other than -1. REF-157 fcntl -1 Indicates that an error occurred. The function sets errno to the following value: o EBADF - The file_desc parameter is not a valid open file descriptor and the argument parameter file descriptor is negative or greater than or equal to the per-process limit. o EFAULT - The argument parameter is an invalid address. o EINVAL - The request parameter is F_DUPFD and the argument parameter is negative or greater than or equal to OPEN_MAX. Either the OPEN_MAX value or the per-process soft descriptor limit is checked. An illegal value was provided for the request parameter. o EMFILE - The request parameter is F_DUPFD and too many or OPEN_MAX file descriptors are currently open in the calling process, or no file descriptors greater than or equal to argument are available. Either the OPEN_MAX value or the per-process soft descriptor limit is checked. o ENOMEM - The system was unable to allocate memory for the requested file descriptor. REF-158 fcvt _________________________________________________________________ fcvt Converts its argument to a null-terminated string of ASCII digits and returns the address of the string. The string is stored in a thread-specific location created by the Compaq C RTL. Format #include char *fcvt (double value, int ndigits, int *decpt, int *sign); Arguments value An object of type double that is converted to a null- terminated string of ASCII digits. ndigits The number of ASCII digits after the decimal point to be used in the converted string. decpt The position of the decimal point relative to the first character in the returned string. The returned string does not contain the actual decimal point. A negative int value means that the decimal point is decpt number of spaces to the left of the returned digits (the spaces are filled with zeros). A 0 value means that the decimal point is immediately to the left of the first digit in the returned string. sign An integer value that indicates whether the value argument is positive or negative. If value is negative, the fcvt function places a nonzero value at the address specified by sign. Otherwise, the functions assign 0 to the address specified by sign. REF-159 fcvt Description This function converts value to a null-terminated string and returns a pointer to it. The resulting low-order digit is rounded to the correct digit for outputting ndigits digits in C F-format. The decpt argument is assigned the position of the decimal point relative to the first character in the string. In C F-format, ndigits is the number of digits desired after the decimal point. Very large numbers produce a very long string of digits before the decimal point, and ndigit of digits after the decimal point. For large numbers, it is preferable to use the gcvt or ecvt function so that E-format is used. Repeated calls to the fcvt function overwrite any existing string. The ecvt, fcvt, and gcvt functions represent the following special values specified in the IEEE Standard for floating- point arithmetic: ___________________________________________________________ Value___________Representation_____________________________ Quiet NaN NaNQ Signalling NaN NaNS +Infinity Infinity -Infinity_______-Infinity__________________________________ The sign associated with each of these values is stored into the sign argument. In IEEE floating-point representation, a value of 0 (zero) can be positive or negative, as set by the sign argument. See also gcvt and ecvt in this section. Return Value x A pointer to the converted string. REF-160 fdopen _________________________________________________________________ fdopen Associates a file pointer with a file descriptor returned by an open, creat, dup, dup2, or pipe function. Format #include FILE *fdopen (int file_desc, char *a_mode); Arguments file_desc The file descriptor returned by open, creat, dup, dup2, or pipe. a_mode The access mode indicator. See the fopen function in this section for a description. Note that the access mode specified must agree with the mode used to open the file originally. This includes binary/text access mode ("b" mode on fdopen and the "ctx=bin" option on creat or open). Description This function allows you to access a file, originally opened by one of the UNIX I/O functions, with Standard I/O functions. Ordinarily, a file can be accessed by either a file descriptor or by a file pointer, but not both, depending on the way you open it. For more information, see Chapters 1 and 2. Return Values pointer Indicates that the operation has succeeded. NULL Indicates that an error has occurred. REF-161 feof _________________________________________________________________ feof Tests a file to see if the end-of-file has been reached. Format #include int feof (FILE *file_ptr); Argument file_ptr A file pointer. Return Values nonzero integer Indicates that the end-of-file has been reached. 0 Indicates that the end-of-file has not been reached. REF-162 ferror _________________________________________________________________ ferror Returns a nonzero integer if an error occurred while reading or writing a file. Format #include int ferror (FILE *file_ptr); Argument file_ptr A file pointer. Description A call to ferror continues to return a nonzero integer until the file is closed or until clearerr is called. Return Values 0 Indicates success. nonzero integer Indicates that an error has occurred. REF-163 fflush _________________________________________________________________ fflush Writes out any buffered information for the specified file. Format #include int fflush (FILE *file_ptr); Argument file_ptr A file pointer. If this argument is a NULL pointer, all buffers associated with all currently open files are flushed. Description The output files are normally buffered only if they are not directed to a terminal, except for stderr, which is not buffered by default. The fflush function flushes the Compaq C RTL buffers. However, RMS has its own buffers. The fflush function does not guarantee that the file will be written to disk. (See the description of fsync for a way to flush buffers to disk.) If the file pointed to by file_ptr was opened in record mode and if there is unwritten data in the buffer, then fflush always generates a record. Return Values 0 Indicates that the operation is successful. EOF Indicates that the buffered data cannot be written to the file, or that the file control block is not associated with an output file. REF-164 ffs _________________________________________________________________ ffs Finds the index of the first bit set in a string. Format #include int ffs (int iteger); Arguments integer The integer to be examined for the first bit set. Description This function finds the first bit set (beginning with the least significant bit) and returns the index of that bit. Bits are numbered starting at 1 (the least significant bit). Return Values x The index of the first bit set. 0 If index is 0. REF-165 fgetc _________________________________________________________________ fgetc Returns the next character from a specified file. Format #include int fgetc (FILE *file_ptr); Argument file_ptr A pointer to the file to be accessed. Description See the getc macro in this section. Return Values x The returned character. EOF Indicates the end-of-file or an error. REF-166 fgetname _________________________________________________________________ fgetname Returns the file specification associated with a file pointer. Format #include char *fgetname (FILE *file_ptr, char *buffer, . . . ); Function Variants This function also has variants named _fgetname32 and _ fgetname64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments file_ptr A file pointer. buffer A pointer to a character string that is large enough to hold the file specification. . . . An optional additional argument that can be either 1 or 0. If you specify 1, the fgetname function returns the file specification in OpenVMS format. If you specify 0, fgetname returns the file specification in UNIX style format. If you do not specify this argument, fgetname returns the file name according to your current command language interpreter. For more information about UNIX style file specifications, see Section 1.4.3. Description This function places the file specification at the address given in the buffer. The buffer should be an array large enough to contain a fully qualified file specification (the maximum length is 256 characters). REF-167 fgetname Return Values n The address of the buffer. 0 Indicates an error. Restriction This function is specific to the Compaq C RTL and is not portable. REF-168 fgetpos _________________________________________________________________ fgetpos Stores the current file position for a given file. Format #include int fgetpos (FILE *stream, fpos_t *pos); Arguments stream A file pointer. pos A pointer to an implementation-defined structure. The fgetpos function fills this structure with information that can be used on subsequent calls to fsetpos. Description This function stores the current value of the file position indicator for the stream pointed to by stream into the object pointed to by pos. Return Values 0 Indicates successful completion. -1 Indicates that there are errors. Example #include #include REF-169 fgetpos main() { FILE *fp; int stat, i; int character; char ch, c_ptr[130], d_ptr[130]; fpos_t posit; /* Open a file for writing. */ if ((fp = fopen("file.dat", "w+")) == NULL) { perror("open"); exit(1); } /* Get the beginning position in the file. */ if (fgetpos(fp, &posit) != 0) perror("fgetpos"); /* Write some data to the file. */ if (fprintf(fp, "this is a test\n") == 0) { perror("fprintf"); exit(1); } /* Set the file position back to the beginning. */ if (fsetpos(fp, &posit) != 0) perror("fsetpos"); fgets(c_ptr, 130, fp); puts(c_ ptr); /* Should be "this is a test." */ /* Close the file. */ if (fclose(fp) != 0) { perror("close"); exit(1); } } REF-170 fgets _________________________________________________________________ fgets Reads a line from the specified file, up to one less than the specified maximum number of characters or up to and including the new-line character, whichever comes first. The function stores the string in str. Format #include char *fgets (char *str, int maxchar, FILE *file_ptr); Function Variants This function also has variants named _fgets32 and _fgets64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Arguments str A pointer to a character string that is large enough to hold the information fetched from the file. maxchar The maximum number of characters to fetch. file_ptr A file pointer. Description This function terminates the line with a null character (\0). Unlike gets, fgets places the new-line character that terminates the input line into the user buffer if more than maxchar characters have not already been fetched. When the file pointed to by file_ptr is opened in record mode, fgets treats the end of a record the same as a new- line character, so it reads up to and including a new-line character or to the end of the record. REF-171 fgets Return Values x Pointer to str. NULL Indicates the end-of-file or an error. The contents of str are undefined if a read error occurs. Example #include #include #include main() { FILE *fp; char c_ptr[130]; /* Create a dummy data file */ if ((fp = fopen("file.dat", "w+")) == NULL) { perror("open"); exit(1); } fprintf(fp, "this is a test\n") ; fclose(fp) ; /* Open a file with some data -"this is a test" */ if ((fp = fopen("file.dat", "r+")) == NULL) { perror("open error") ; exit(1); } fgets(c_ptr, 130, fp); puts(c_ptr); /* Display what fgets got. */ fclose(fp); delete("file.dat") ; } REF-172 fgetwc _________________________________________________________________ fgetwc Reads the next character from a specified file, and converts it to a wide-character code. Format #include wint_t fgetwc (FILE *file_ptr); Arguments file_ptr A pointer to the file to be accessed. Description Upon successful completion, the fgetwc function returns the wide-character code read from the file pointed to by file_ptr and converted to type wint_t. If the file is at end-of-file, the end-of-file indicator is set, and WEOF is returned. If an I/O read error occurred, then the error indicator is set, and WEOF is returned. Applications can use ferror or feof to distinguish between an error condition and an end-of-file condition. Return Values x The wide-character code of the character read. REF-173 fgetwc WEOF Indicates the end-of-file or an error. If a read error occurs, the function sets errno to one of the following: o EALREADY - An operation is already in progress on the same file. o EBADF - The file descriptor is not valid. o EILSEQ - Invalid character detected. REF-174 fgetws _________________________________________________________________ fgetws Reads a line of wide characters from a specified file. Format #include wchar_t *fgetws (wchar_t *wstr, int maxchar, FILE *file_ptr); Function Variants This function also has variants named _fgetws32 and _ fgetws64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr A pointer to a wide-character string large enough to hold the information fetched from the file. maxchar The maximum number of wide characters to fetch. file_ptr A file pointer. Description This function reads wide characters from the specified file and stores them in the array pointed to by wstr. The function reads up to maxchar-1 characters or until the newline character is read, converted, and transferred to wstr, or until an end-of-file condition is encountered. The function terminates the line with a null wide character. fgetws places the newline that terminates the input line into the user buffer, unless maxchar characters have already been fetched. REF-175 fgetws Return Values x Pointer to wstr. NULL Indicates the end-of-file or an error occurred. The contents of wstr are undefined if a read error occurs. If a read error occurs, the function sets errno. For a list of possible errno values, see fgetwc in this section. Example #include #include #include #include main() { wchar_t wstr[80], *ret; FILE *fp; /* Create a dummy data file */ if ((fp = fopen("file.dat", "w+")) == NULL) { perror("open"); exit(1); } fprintf(fp, "this is a test\n") ; fclose(fp) ; /* Open a test file containing : "this is a test" */ if ((fp = fopen("file.dat", "r")) == (FILE *) NULL) { perror("File open error"); exit(EXIT_FAILURE); } ret = fgetws(wstr, 80, fp); if (ret == (wchar_t *) NULL) { perror("fgetws failure"); exit(EXIT_FAILURE); } REF-176 fgetws fputws(wstr, stdout); fclose(fp); delete("file.dat"); } REF-177 fileno _________________________________________________________________ fileno Returns the file descriptor associated with the specified file pointer. Format #include int fileno (FILE *file_ptr); Argument file_ptr A file pointer. Description If you are using DEC C Version 5.2 or lower, undefine the fileno macro: #if defined(fileno) #undef fileno #endif Return Value x Integer file descriptor. -1 Indicates an error. REF-178 floor _________________________________________________________________ floor Returns (as a double) the largest integer that is less than or equal to its argument. Format #include double floor (double x); Argument x A real value. REF-179 fmod _________________________________________________________________ fmod Computes the floating-point remainder of the first argument divided by the second. If the second argument is 0, the function returns 0. Format #include double fmod (double x, double y); Arguments x A real value. y A real value. Return Values 0 Indicates that y is 0. x The value f, which has the same sign as the argument x, such that x == i * y + f for some integer i, where the magnitude of f is less than the magnitude of y. REF-180 fopen _________________________________________________________________ fopen Opens a file by returning the address of a FILE structure. Format #include FILE *fopen (const char *file_spec, const char *a_mode); (ANSI C) FILE *fopen (const char *file_spec, const char *a_mode, . . . ); (DEC C Extension) Arguments file_spec A character string containing a valid file specification. a_mode The access mode indicator. Use one of the following character strings: "r", "w", "a", "r+", "w+", "rb", "r+b", "rb+", "wb", "w+b", "wb+", "ab", "a+b", "ab+", or "a+". These access modes have the following effects: o "r" opens an existing file for reading. o "w" creates a new file, if necessary, and opens the file for writing. If the file exists, it creates a new file with the same name and a higher version number. o "a" opens the file for append access. An existing file is positioned at the end-of-file, and data is written there. If the file does not exist, the Compaq C RTL creates it. The update access modes allow a file to be opened for both reading and writing. When used with existing files, "r+" and "a+" differ only in the initial positioning within the file. The modes are as follows: o "r+" opens an existing file for read update access. It is opened for reading, positioned first at the beginning-of-file, but writing is also allowed. o "w+" opens a new file for write update access. REF-181 fopen o "a+" opens a file for append update access. The file is first positioned at the end-of-file (writing). If the file does not exist, the Compaq C RTL creates it. o "b" means binary access mode. In this case, no conversion of carriage-control information is attempted. . . . Optional file attribute arguments. The file attribute arguments are the same as those used in the creat function. For more information, see the creat function. Description If a version of the file exists, a new file created with fopen inherits certain attributes from the existing file unless those attributes are specified in the fopen call. The following attributes are inherited: Record format Maximum record size Carriage control File protection. If you specify a directory in the file name and it is a search list that contains an error, Compaq C for OpenVMS Systems interprets it as a file open error. The file control block can be freed with the fclose function, or by default on normal program termination. Return Values x File pointer. REF-182 fopen NULL Indicates an error. The constant NULL is defined in the header file to be the NULL pointer value. The function returns NULL to signal the following errors: o File protection violations o Attempts to open a nonexistent file for read access o Failure to open the specified file REF-183 fp_class, fp_classf, fp_classl (Alpha only) _________________________________________________________________ fp_class, fp_classf, fp_classl (Alpha only) Determine the class of IEEE floating-point values. Format #include int fp_class (double x); int fp_classf (float x); int fp_classl (long double x); Arguments x An IEEE floating-point number. Description These functions determine the class of the specified IEEE floating-point number, returning a constant from the header file. They never cause an exception, even for signaling NaNs (Not-a-Number). These functions implement the recommended class(x) function in the appendix of the IEEE 754-1985 standard for binary floating-point arithmetic. The constants in refer to the following classes of values: FP_SNAN Signaling NaN (Not-a-Number) FP_QNAN Quiet NaN FP_POS_INF +infinity FP_NEG_INF -infinity FP_POS_NORM positive normalized FP_NEG_NORM negative normalized FP_POS_DENORM positive denormalized FP_NEG_DENORM negative denormalized FP_POS_ZERO +0.0 (positive zero) FP_NEG_ZERO -0.0 (negative zero) REF-184 fp_class, fp_classf, fp_classl (Alpha only) Return Values x A constant from the header file. REF-185 fpathconf _________________________________________________________________ fpathconf Retrieves file implementation characteristics. Format #include long int fpathconf (int filedes, int name); Arguments filedes An open file descriptor. name The configuration attribute to query. If this attribute is not applicable to the file specified by the filesdes argument, fpathconf returns an error. Description This function allows an application to retrieve the characteristics of operations supported by the file system underlying the file named by the filesdes argument. Read, write, or execute permission of the named file is not required, but you must be able to search all directories in the path leading to the file. Symbolic values for the name argument are defined in the header file as follows: _PC_LINK_MAX The maximum number of links to the file. If the filedes argument refers to a directory, the value returned applies to the directory itself. _PC_MAX_CANON The maximum number of bytes in a canonical input line. This is applicable only to terminal devices. _PC_MAX_INPUT The number of types allowed in an input queue. This is applicable only to terminal devices. REF-186 fpathconf _PC_NAME_MAX Maximum number of bytes in a filename (not including a terminating null). The byte range value is between 13 and 255. This is applicable only to a directory file. The value returned applies to filenames within the directory. _PC_PATH_MAX Maximum number of bytes in a pathname (not including a terminating null). The value is never larger than 65,535. This is applicable only to a directory file. The value returned is the maximum length of a relative pathname when the specified directory is the working directory. _PC_PIPE_BUF Maximum number of bytes guaranteed to be written atomically. This is applicable only to a FIFO. The value returned applies to the referenced object. If the path argument refers to a directory, the value returned applies to any FIFO that exists or can be created within the directory. _PC_CHOWN_ The value returned applies to any files RESTRICTED (other than directories) that exist or can be created within the directory. This is applicable only to a directory file. _PC_NO_TRUNC Returns 1 if supplying a component name longer than allowed by NAME_MAX causes an error. Returns 0 (zero) if long component names are truncated. This is applicable only to a directory file. _PC_VDISABLE This is always 0 (zero); no disabling character is defined. This is applicable only to a terminal device. REF-187 fpathconf Return Values x The resultant value for the configuration attribute specified in the name argument. -1 Indicates an error; errno is set to one of the following values: o EINVAL - The name argument specifies an unknown or inapplicable characteristic. o EBADF - the filedes argument is not a valid file descriptor. REF-188 fprintf _________________________________________________________________ fprintf Performs formatted output to a specified file. Format #include int fprintf (FILE *file_ptr, const char *format_spec, . . . ); Arguments file_ptr A pointer to the file to which the output is directed. format_spec A pointer to a character string that contains the format specification. For more information on format specifications and conversion characters, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, the output sources can be omitted. Otherwise, the function calls must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Any excess output sources are ignored. Description An example of a conversion specification follows: #include main() { int temp = 4, temp2 = 17; REF-189 fprintf fprintf(stdout, "The answers are %d, and %d.", temp, temp2); } Sample output (to the stdout file) from the previous example is as follows: The answers are 4, and 17. For a complete description of the format specification and the output source, see Chapter 2. Return Values x The number of bytes written, excluding the null terminator. Negative value Indicates an error. The function sets errno to one of the following: o EILSEQ - Invalid character detected. o EINVAL - Insufficient arguments. o ENOMEM - Not enough memory available for conversion. o ERANGE - Floating-point calculations overflow. o EVMSERR - Non-translatable VMS error. vaxc$errno contains the VMS error code. This might indicate that conversion to a numeric value failed because of overflow. REF-190 fprintf The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Non-translatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-191 fputc _________________________________________________________________ fputc Writes a character to a specified file. Format #include int fputc (int character, FILE *file_ptr); Arguments character An object of type int. file_ptr A file pointer. Description This function writes a single character to a file and returns the character. See also putc in this section. Return Values x The character written to the file. Indicates success. EOF Indicates an output error. REF-192 fputs _________________________________________________________________ fputs Writes a character string to a file without copying the string's null terminator (\0). Format #include int fputs (const char *str, FILE *file_ptr); Arguments str A pointer to a character string. file_ptr A file pointer. Description See also puts in this section. Unlike puts, the fputs function does not append a new-line character to the output string. Return Values Nonnegative value Indicates success. EOF Indicates an error. REF-193 fputwc _________________________________________________________________ fputwc Converts a wide character to its corresponding multibyte value, and writes the result to a specified file. Format #include wint_t fputwc (wint_t wc, FILE *file_ptr); Arguments wc An object of type wint_t. file_ptr A file pointer. Description This function writes a wide character to a file and returns the character. See also putwc in this section. Return Values x The character written to the file. Indicates success. REF-194 fputwc WEOF Indicates an output error. The function sets errno to the following: o EILSEQ - Invalid wide-character code detected. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Non-translatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-195 fputws _________________________________________________________________ fputws Writes a wide-character string to a file without copying the null terminating character. Format #include int fputws (const wchar_t *wstr, FILE *file_ptr); Arguments wstr A pointer to a wide-character string. file_ptr A file pointer. Description The function converts the specified wide-character string to a multibyte character string and writes it to the specified file. The function does not append a terminating null byte corresponding to the null wide-character to the output string. Return Values Nonnegative value Indicates success. -1 Indicates an error. The function sets errno. For a list of the values see fputwc in this section. REF-196 fread _________________________________________________________________ fread Reads a specified number of items from the file. Format #include size_t fread (void *ptr, size_t size_of_item, size_t number_items, FILE *file_ptr); Arguments ptr A pointer to the location, within memory, where you place the information being read. The type of the object pointed to is determined by the type of the item being read. size_of_item The size of the items being read, in bytes. number_items The number of items to be read. file_ptr A pointer that indicates the file from which the items are to be read. Description The type size_t is defined in the header file as follows: typedef unsigned int size_t The reading begins at the current location in the file. The items read are placed in storage beginning at the location given by the first argument. You must also specify the size of an item, in bytes. If the file pointed to by file_ptr was opened in record mode, fread will read size_of_item multiplied by number_ items bytes from the file. That is, it does not necessarily read number_items records. REF-197 fread Return Values n The number of bytes read divided by size_of_item. 0 Indicates the end-of-file or an error. REF-198 free _________________________________________________________________ free Makes available for reallocation the area allocated by a previous calloc, malloc, or realloc call. Format #include void free (void *ptr); Argument ptr The address returned by a previous call to malloc, calloc, or realloc. If ptr is a NULL pointer, no action occurs. Description The ANSI C standard defines free as not returning a value; therefore, the function prototype for free is declared with a return type of void. However, since a free can fail, and since previous versions of the Compaq C RTL have declared free to return an int, the implementation of free does return 0 on success and -1 on failure. REF-199 freopen _________________________________________________________________ freopen Substitutes the file named by a file specification for the open file addressed by a file pointer. The latter file is closed. Format #include FILE *freopen (const char *file_spec, const char *a_mode, FILE *file_ptr, . . . ); Arguments file_spec A pointer to a string that contains a valid OpenVMS or UNIX style file specification. After the function call, the given file pointer is associated with this file. a_mode The access mode indicator. See the fopen function in this section for a description. file_ptr A file pointer. . . . Optional file attribute arguments. The file attribute arguments are the same as those used in the creat function. Description This function is typically used to associate one of the predefined names stdin, stdout, or stderr with a file. For more information about these predefined names, see Chapter 2. REF-200 freopen Return Values file_ptr The file pointer, if freopen is successful. NULL Indicates an error. REF-201 frexp _________________________________________________________________ frexp Calculates the fractional and exponent parts of a double value. Format #include double frexp (double value, int *eptr); Arguments value An object of type double. eptr A pointer to an int, to which frexp returns the exponent. Description This function converts value to the following form: value = fraction * (2exp) The fractional part is returned as the return value. The exponent is placed in the integer variable pointed to by eptr. Example #include main () { double val = 16.0, fraction; int exp; fraction = frexp(val, &exp); printf("fraction = %f\n",fraction); printf("exp = %d\n",exp); } REF-202 frexp In this example, frexp converts the value 16 to .5*2 5. The example produces the following output: fraction = 0.500000 exp = 5 Return Value x The fractional part of the double value. REF-203 fscanf _________________________________________________________________ fscanf Performs formatted input from a specified file, interpreting it according to the format specification. Format #include int fscanf (FILE *file_ptr, const char *format_spec, . . . ); Arguments file_ptr A pointer to the file that provides input text. format_spec A pointer to a character string that contains the format specification. For more information on conversion characters, see Chapter 2. . . . Optional expressions whose results correspond to conversion specifications given in the format specification. If no conversion specifications are given, you can omit the input pointers. Otherwise, the function calls must have exactly as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. REF-204 fscanf Description An example of a conversion specification follows: #include main () { int temp, temp2; fscanf(stdin, "%d %d", &temp, &temp2); printf("The answers are %d, and %d.", temp, temp2); } Consider a file, designated by stdin, with the following contents: 4 17 The example conversion specification produces the following result: The answers are 4, and 17. For a complete description of the format specification and the input pointers, see Chapter 2. Return Values x The number of successfully matched and assigned input items. REF-205 fscanf EOF Indicates that the end-of-file was encountered or a read error occurred. If a read error occurs, the function sets errno to one of the following: o EILSEQ - Invalid character detected. o EVMSERR - Non-translatable VMS error. vaxc$errno contains the VMS error code. This can indicate that conversion to a numeric value failed due to overflow. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o EVMSERR - Non-translatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-206 fseek _________________________________________________________________ fseek Positions the file to the specified byte offset in the file. Format #include int fseek (FILE *file_ptr, long int offset, int direction); Arguments file_ptr A file pointer. offset The offset, specified in bytes. direction An integer indicating the position to which the offset is added to calculate the new position. The new position is the beginning of the file if direction is SEEK_SET, the current value of the file position indicator if direction is SEEK_CUR, or end-of-file if direction is SEEK_END. Description This function can position fixed-length record-access file with no carriage control or a stream-access file on any byte offset, but can position all other files only on record boundaries. The available Standard I/O functions position a variable- length or VFC record file at its first byte, at the end- of-file, or on a record boundary. Therefore, the arguments given to fseek must specify any of the following: o The beginning or end of the file o A 0 offset from the current position (an arbitrary record boundary) o The position returned by a previous, valid ftell call REF-207 fseek See the fgetpos and fsetpos functions for a portable way to seek to arbitrary locations with these types of record files. _______________________ CAUTION _______________________ If, while accessing a stream file, you seek beyond the end-of-file and then write to the file, the fseek function creates a hole by filling the skipped bytes with zeros. In general, for record files, fseek should only be directed to an absolute position that was returned by a previous valid call to ftell, or to the beginning or end of a file. If a call to fseek does not satisfy these conditions, the results are unpredictable. ______________________________________________________ See also open, creat, dup, dup2, and lseek in this section. Return Values 0 Indicates successful seeks. -1 Indicates improper seeks. REF-208 fsetpos _________________________________________________________________ fsetpos Sets the file position indicator for a given file. Format #include int fsetpos (FILE *stream, const fpos_t *pos); Arguments stream A file pointer. pos A pointer to an implementation-defined structure. The fgetpos function fills this structure with information that can be used on subsequent calls to fsetpos. Description Call the fgetpos function before using the fsetpos function. Return Values 0 Indicates success. -1 Indicates an error. REF-209 fstat _________________________________________________________________ fstat Accesses information about the file specified by the file descriptor. Format #include int fstat (int file_desc, struct stat *buffer); Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Arguments file_desc A file descriptor. buffer A pointer to a structure of type stat_t, which is defined in the header file. The argument receives information about that particular file. The members of the structure pointed to by buffer are as follows: ___________________________________________________________ Member______Type____________Definition_____________________ st_dev dev_t Pointer to a physical device name st_ino[3] ino_t Three words to receive the file ID st_mode mode_t File "mode" (prot, dir, . . . ) st_nlink nlink_t For UNIX system compatibility only st_uid uid_t Owner user ID st_gid gid_t Group member: from st_uid REF-210 fstat ___________________________________________________________ Member______Type____________Definition_____________________ st_rdev dev_t UNIX system compatibility - always 0 st_size off_t File size, in bytes st_atime time_t File access time; always the same as st_mtime st_mtime time_t Last modification time st_ctime time_t File creation time st_fab_rfm char Record format st_fab_rat char Record attributes st_fab_fsz char Fixed header size st_fab_mrs__unsigned________Record_size____________________ The types dev_t, ino_t, off_t, mode_t, nlink_t, uid_t, gid_ t, and time_t, are defined in the header file. However, when compiling for compatibility (/DEFINE=_DECC_ V4_SOURCE), only dev_t, ino_t, and off_t are defined. As of OpenVMS Version 7.0, times are given in seconds since the Epoch (00:00:00 GMT, January 1, 1970). The st_mode structure member is the status information mode and is defined in the header file. The st_mode bits follow: ___________________________________________________________ Bits_____Constant__Definition______________________________ 0170000 S_IFMT Type of file 0040000 S_IFDIR Directory 0020000 S_IFCHR Character special 0060000 S_IFBLK Block special 0100000 S_IFREG Regular 0030000 S_IFMPC Multiplexed char special 0070000 S_IFMPB Multiplexed block special 0004000 S_ISUID Set user ID on execution 0002000 S_ISGID Set group ID on execution 0001000 S_ISVTX Save swapped text even after use REF-211 fstat ___________________________________________________________ Bits_____Constant__Definition______________________________ 0000400 S_IREAD Read permission, owner 0000200 S_IWRITE Write permission, owner 0000100__S_IEXEC___Execute/search_permission,_owner________ Description This function does not work on remote network files. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, the stat, fstat, utime, and utimes functions have been enhanced to take advantage of the new file-system support for POSIX-compliant file timestamps. This support is available only on ODS-5 devices on OpenVMS Alpha systems beginning with a version of OpenVMS Alpha after Version 7.3. Before this change, the stat and fstat functions were setting the values of the st_ctime, st_mtime, and st_ atime fields based on the following file attributes: st_ctime - ATR$C_CREDATE (file creation time) st_mtime - ATR$C_REVDATE (file revision time) st_atime - was always set to st_mtime because no support for file access time was available Also, for the file-modification time, utime and utimes were modifying the ATR$C_REVDATE file attribute, and ignoring the file-access-time argument. After the change, for a file on an ODS-5 device, the stat and fstat functions set the values of the st_ ctime, st_mtime, and st_atime fields based on the following new file attributes: st_ctime - ATR$C_ATTDATE (last attribute modification time) st_mtime - ATR$C_MODDATE (last data modification time) REF-212 fstat st_atime - ATR$C_ACCDATE (last access time) If ATR$C_ACCDATE is zero, as on an ODS-2 device, the stat and fstat functions set st_atime to st_mtime. For the file-modification time, the utime and utimes functions modify both the ATR$C_REVDATE and ATR$C_MODDATE file attributes. For the file-access time, these functions modify the ATR$C_ACCDATE file attribute. Setting the ATR$C_MODDATE and ATR$C_ACCDATE file attributes on an ODS-2 device has no effect. For compatibility, the old behavior of stat, fstat, utime and utimes remains the default, regardless of the kind of device. The new behavior must be explicitly enabled by defining the DECC$EFS_FILE_TIMESTAMPS logical name to "ENABLE" before invoking the application. Setting this logical does not affect the behavior of stat, fstat, utime and utimes for files on an ODS-2 device. ______________________________________________________ Return Values 0 Indicates successful completion. -1 Indicates an error other than a protection violation. -2 Indicates a protection violation. REF-213 fsync _________________________________________________________________ fsync Flushes data all the way to the disk. Format #include int fsync (int fd); Argument fd A file descriptor corresponding to an open file. Description This function behaves much like the fflush function. The primary difference between the two is that fsync flushes data all the way to the disk while fflush flushes data only as far as the underlying RMS buffers. Also, with fflush, you can flush all buffers at once; with fsync you cannot. Return Values 0 Indicates successful completion. -1 Indicates an error. REF-214 ftell _________________________________________________________________ ftell Returns the current byte offset to the specified stream file. Format #include long int ftell (FILE *file_ptr); Argument file_ptr A file pointer. Description This function measures the byte offset from the beginning of the file. For variable-length files, VFC files, or any file with carriage-control attributes, it the file is opened in record mode, then ftell returns the starting position of the current record, not the current byte offset. When using record files, the ftell function ignores any characters that have been pushed back using either ungetc or ungetwc. This behavior does not occur if stream files are being used. For a portable way to measure the exact offset for any type of file, see the fgetpos function. Return Values n The current offset. EOF Indicates an error. REF-215 ftime _________________________________________________________________ ftime Returns the elapsed time since 00:00:00, January 1, 1970, in the structure pointed at by timeptr. Format #include int ftime (struct timeb *timeptr); Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Argument timeptr A pointer to the structure timeb_t. Description The typedef timeb_t refers to the following structure defined in the header file: typedef struct timeb { time_t time; unsigned short millitm; short timezone; short dstflag; }; The member time gives the time in seconds. The member millitm gives the fractional time in milliseconds. After a call to ftime, the timezone and dstflag members of the timeb structure have the values of the global variables timezone and dstflag, respectively. See the description REF-216 ftime of the tzset function for timezone and dstflag global variables. Return Values 0 Successful execution. The timeb_t structure is filled in. -1 Indicates an error. Failure might indicate that the system's time- differential factor (that is, the difference between the system time and UTC time) is not set correctly. If the value of the SYS$TIMEZONE_ DIFFERENTIAL logical is wrong, the function fails with errno set to EINVAL. REF-217 ftruncate _________________________________________________________________ ftruncate Truncates a file to a specified length. Format #include int ftruncate (int filedes, off_t length); Arguments filedes The descriptor of a file that must be open for writing. length The new length of the file in bytes. Description This function truncates a file at the specified position. For record files, the position must be a record boundary. Also, the files must be local, regular files. If the file was previously larger than length, extra data is lost. If the file was previously shorter than length, bytes between the old and new lengths are read as zeros. Return Values 0 Indicates success. -1 An error occurred; errno is set to indicate the error. REF-218 ftw _________________________________________________________________ ftw Walks a file tree. Format #include int ftw (const char *path, int(*function)(const char *, const struct stat *,int), int depth); Arguments path The directory hierarchy to be searched. function The function to be invoked for each file in the directory hierarchy. depth The maximum number of directory streams or file descriptors, or both, available for use by ftw. This argument should be in the range of 1 to OPEN_MAX. Description This function recursively searches the directory hierarchy that descends from the directory specified by the path argument. For each file in the hierarchy, ftw calls the function specified by the function argument, passes it a pointer to a null-terminated character string containing the name of the file, a pointer to a stat structure containing information about the file, and an integer. The integer identifies the file type. Possible values, defined in are: FTW_F Regular file. FTW_D Directory. REF-219 ftw FTW_DNR Directory that cannot be read. FTW_NS A file on which stat could not successfully be executed. If the integer is FTW_DNR, then the files and subdirectories contained in that directory are not processed. If the integer is FTW_NS, then the stat structure contents are meaningless. For example, a file in a directory for which you have read permission but not execute (search) permission can cause the function argument to pass FTW_NS. The ftw function finishes processing a directory before processing any of its files or subdirectories. The ftw function continues the search until: o The directory hierarchy specified by the path argument is completed. o An invocation of the function specified by the function argument returns a nonzero value. o An error (such as an I/O error) is detected within the ftw function. Because the ftw function is recursive, it is possible for it to terminate with a memory fault because of stack overflow when applied to very deep file structures. The ftw function uses the malloc function to allocate dynamic storage during its operation. If ftw is forcibly terminated, as with a call to longjmp from the function pointed to by the function argument, ftw has no chance to free that storage. It remains allocated. A safe way to handle interrupts is to store the fact that an interrupt has occurred, and arrange to have the function specified by the function argument return a nonzero value the next time it is called. ________________________ Note ________________________ The ftw function is reentrant; make sure that the function supplied as argument function is also REF-220 ftw reentrant. ______________________________________________________ See malloc, longjump, lstat, and stat in this section. Return Values 0 Indicates success. x Indicates that the function specified by the function argument stops its search, and returns the value that was returned by the function. -1 Indicates an error; errno is set to one of the following values: o EACCES - Search permission is denied for any component of the path argument or read permission is denied for the path argument. o ENAMETOOLONG - The length of the path string exceeds PATH_MAX, or a pathname component is longer than NAME_MAX while [_POSIX_NO_TRUNC] is in effect. o ENOENT - The path argument points to the name of a file that does not exist or points to an empty string. o ENOMEM - There is insufficient memory for this operation. Also, if the function pointed to by the function argument encounters an error, errno can be set accordingly. REF-221 fwait _________________________________________________________________ fwait Waits for I/O on a specific file to complete. Format #include int fwait (FILE *fp); Argument fp A file pointer corresponding to an open file. Description This function is used primarily to wait for completion of pending asynchronous I/O. Return Values 0 Indicates successful completion. -1 Indicates an error. REF-222 fwide _________________________________________________________________ fwide Determines and sets the orientation of a stream. Format #include int fwide (FILE *stream, int mode); Arguments stream A file pointer. mode A value that specifies the desired orientation of the stream. Description This function determines the orientation of the stream pointed to by stream and sets the orientation of a non- oriented stream according to the mode argument in the following way: ___________________________________________________________ If the mode argument_is________Then_the_fwide_function_________________ greater than zero makes the stream wide-oriented. less than zero makes the stream byte-oriented. zero does not alter the orientation of the ___________________stream._________________________________ If the orientation of the stream has already been set, fwide does not alter it. Because no error status is defined for fwide, the calling application should check errno if fwide returns a 0. REF-223 fwide Return Values > 0 After the call, the stream is wide- oriented. < 0 After the call, the stream is byte- oriented. 0 After the call, the stream has no orientation or a stream argument is invalid; the function sets errno. REF-224 fwprintf _________________________________________________________________ fwprintf Writes output to the stream under control of the wide- character format string. Format #include int fwprintf (FILE *stream, const wchar_t *format, . . . ); Arguments stream A file pointer. format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, the output sources can be omitted. Otherwise, the function calls must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Any excess output sources are ignored. REF-225 fwprintf Description This function writes output to the stream pointed to by stream under control of the wide-character string pointed to by format, which specifies how to convert subsequent arguments to output. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated, but are otherwise ignored. The fwprintf function returns when it encounters the end of the format string. The format argument is composed of zero or more directives that include: o Ordinary wide characters (not the percent sign (%)) o Conversion specifications Return Values n The number of wide characters written. REF-226 fwprintf Negative value Indicates an error. The function sets errno to one of the following: o EILSEQ - Invalid character detected. o EINVAL - Insufficient arguments. o ENOMEM - Not enough memory available for conversion. o ERANGE - Floating-point calculations overflow. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This might indicate that conversion to a numeric value failed because of overflow. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-227 fwprintf Example The following example shows how to print a date and time in the form "Sunday, July 3, 10:02", followed by to five decimal places: #include #include #include /* . . . */ wchar_t *weekday, *month; /* pointers to wide-character strings */ int day, hours, min; fwprintf(stdout, L"%ls, %ls %d, %.2d:%.2d\n", weekday, month, day, hour, min); fwprintf(stdout, L"pi = %.5f\n", 4 * atan(1.0)); REF-228 fwrite _________________________________________________________________ fwrite Writes a specified number of items to the file. Format #include size_t fwrite (const void *ptr, size_t size_of_item, size_t number_items, FILE *file_ptr); Arguments ptr A pointer to the memory location from which information is being written. The type of the object pointed to is determined by the type of the item being written. size_of_item The size, in bytes, of the items being written. number_items The number of items to be written. file_ptr A file pointer that indicates the file to which the items are being written. Description The type size_t is defined in the header file as follows: typedef unsigned int size_t The writing begins at the current location in the file. The items are written from storage beginning at the location given by the first argument. You must also specify the size of an item, in bytes. If the file pointed to by file_ptr is a record file, the fwrite function outputs at least number_items records, each of length size_of_item. REF-229 fwrite Return Value x The number of items written. The number of records written depends upon the maximum record size of the file. REF-230 fwscanf _________________________________________________________________ fwscanf Reads input from the stream under control of the wide- character format string. Format #include int fwscanf (FILE *stream, const wchar_t *format, . . . ); Arguments stream A file pointer. format A pointer to a wide-character string containing the format specification. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose results correspond to conversion specifications given in the format specification. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. If no conversion specifications are given, you can omit the input pointers. Otherwise, the function calls must have exactly as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. REF-231 fwscanf Description This function reads input from the stream pointed to by stream under the control of the wide-character string pointed to by format. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated, but otherwise ignored. The format is composed of zero or more directives that include: o One or more white-space wide characters. o An ordinary wide character (neither a percent (%)) nor a white-space wide character). o Conversion specifications. Each conversion specification is introduced by the wide character %. If the stream pointed to by the stream argument has no orientation, fwscanf makes the stream wide-oriented. Return Values n The number of input items assigned, sometimes fewer than provided for, or even zero, in the event of an early matching failure. EOF Indicates an error; input failure occurs before any conversion. REF-232 gcvt _________________________________________________________________ gcvt Converts its argument to a null-terminated string of ASCII digits and returns the address of the string. Format #include char *gcvt (double value, int ndigit, char *buffer); Function Variants This function also has variants named _gcvt32 and _gcvt64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Arguments value An object of type double that is converted to a null- terminated string of ASCII digits. ndigit The number of ASCII digits to use in the converted string. If ndigit is less than 6, the value of 6 is used. buffer A storage location to hold the converted string. Description This function places the converted string in a buffer and returns the address of the buffer. If possible, gcvt produces ndigit significant digits in F-format, or if not possible, in E-format. Trailing zeros are suppressed. The ecvt, fcvt, and gcvt functions represent the following special values specified in the IEEE Standard for floating- point arithmetic: REF-233 gcvt ___________________________________________________________ Value___________Representation_____________________________ Quiet NaN NaNQ Signalling NaN NaNS +Infinity Infinity -Infinity_______-Infinity__________________________________ The sign associated with each of these values is stored into the sign argument. In IEEE floating-point representation, a value of 0 (zero) can be positive or negative, as set by the sign argument. See also fcvt and ecvt in this section. Return Value x The address of the buffer. REF-234 getc _________________________________________________________________ getc The getc macro returns the next character from a specified file. Format #include int getc (FILE *file_ptr); Argument file_ptr A pointer to the file to be accessed. Description Since getc is a macro, a file pointer argument with side effects (for example, getc (*f++)) might be evaluated incorrectly. In such a case, use the fgetc function instead. See the fgetc function in this section. Return Values n The returned character. EOF Indicates the end-of-file or an error. REF-235 [w]getch _________________________________________________________________ [w]getch Get a character from the terminal screen and echo it on the specified window. The getch function echos the character on stdscr. Format #include char getch(); char wgetch (WINDOW *win); Argument win A pointer to the window. Description The getch and wgetch functions refresh the specified window before fetching a character. For more information, see the scrollok function in this section. Return Values x The returned character. ERR Indicates that the function makes the screen scroll illegally. REF-236 getchar _________________________________________________________________ getchar Reads a single character from the standard input (stdin). Format #include int getchar (void); Description The getchar function is identical to fgetc(stdin). Return Values x The next character from stdin, converted to int. EOF Indicates the end-of-file or an error. REF-237 getclock _________________________________________________________________ getclock Gets the current value of the system-wide clock. Format #include int getclock (int clktyp, struct timespec *tp); Arguments clktyp The type of system-wide clock. tp Pointer to a timespec structure space where the current value of the system-wide clock is stored. Description This function sets the current value of the clock specified by clktyp into the location pointed to by tp. The clktyp argument is given as a symbolic constant name, as defined in the header file. Only the TIMEOFDAY symbolic constant, which specifies the normal time-of-day clock to access for system-wide time, is supported. For the clock specified by TIMEOFDAY, the value returned by this function is the elapsed time since the Epoch. The Epoch is referenced to 00:00:00 UTC (Coordinated Universal Time) 1 Jan 1970. The getclock function returns a timespec structure, which is defined in the header file as follows: struct timespec { unsigned long tv_sec /* Elapsed time in seconds since the Epoch*/ long tv_nsec /* Elapsed time as a fraction of a second */ /* since the Epoch (expressed in nanoseconds */ }; REF-238 getclock Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EINVAL - The clktyp argument does not specify a known system-wide clock. Or, the value of SYS$TIMEZONE_ DIFFERENTIAL logical is wrong. o EIO - An error occurred when the system-wide clock specified by the clktyp argument was accessed. REF-239 getcwd _________________________________________________________________ getcwd Returns a pointer to the file specification for the current working directory. Format #include char *getcwd (char *buffer, size_t size); (ISO POSIX-1) char *getcwd (char *buffer, unsigned int size, . . . ); (DEC C Extension) Function Variants This function also has variants named _getcwd32 and _ getcwd64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments buffer Pointer to a character string large enough to hold the directory specification. If buffer is a NULL pointer, getcwd obtains size bytes of space using malloc. In this case, you can use the pointer returned by getcwd as the argument in a subsequent call to free. size The length of the directory specification to be returned. . . . An optional argument that can be either 1 or 0. If you specify 1, the getcwd function returns the directory specification in OpenVMS format. If you specify 0, getcwd returns the directory specification (path name) in UNIX style format. If you do not specify this argument, getcwd returns the file name according to your current command- language interpreter. For more information about UNIX style directory specifications, see Section 1.4.3. REF-240 getcwd Return Values x A pointer to the file specification. NULL Indicates an error. REF-241 getdtablesize _________________________________________________________________ getdtablesize Gets the total number of file descriptors that a process can have open simultaneously. Format #include int getdtablesize (void); Description This function returns the total number of file descriptors that a process can have open simultaneously. Each process is limited to a fixed number of open file descriptors. The number of file descriptors that a process can have open is the minumum of the following: o Compaq C RTL open file limit-65535 on OpenVMS Alpha; 2048 on OpenVMS VAX. o SYSGEN CHANNELCNT parameter-permanent I/O channel count. o Process open file quota FILLM parameter-number of open files that can be opened by a process at one time. Return Values x The number of file descriptors that a process can have open simultaneously. -1 Indicates an error. REF-242 getegid _________________________________________________________________ getegid Returns, in OpenVMS terms, the group number from the user identification code (UIC). For example, if the UIC is [313,031], 313 is the group number. Format #include gid_t getegid (void); Description In Compaq C for OpenVMS Systems, the getgid and getegid functions both return the group number from the current UIC. See also geteuid and getuid in this section. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ Return Value x The group number from the UIC. REF-243 getenv _________________________________________________________________ getenv Searches the environment array for the current process and returns the value associated with a specified environment name. Format #include char *getenv (const char *name); Argument name One of the following values: o HOME-Your login directory o TERM-The type of terminal being used o PATH-The default device and directory o USER-The name of the user who initiated the process o Logical name or CLI symbolic name o An environment variable set with setenv or putenv. The case of the specified name is important. Description In certain situations, this function attempts to perform a logical name translation on the user-specified argument: 1. If the argument to getenv does not match any of the environment strings present in your environment array, getenv attempts to translate your argument as a logical name by searching the logical name tables indicated by the LNM$FILE_DEV logical, as is done for file processing. getenv first does a case-sensitive lookup. If that fails, it does a case-insensitive lookup. In most instances, logical names are defined in uppercase, but getenv can also find logical names that include lowercase letters. REF-244 getenv getenv does not perform iterative logical name translation. 2. If no logical name exists, getenv attempts to translate the argument string as a command-language interpreter (CLI) symbol. If it succeeds, it returns the translated symbol text. If it fails, the return value is NULL. getenv does not perform iterative CLI translation. If your CLI is the DEC/Shell, the function does not attempt a logical name translation since Shell environment symbols are implemented as DCL symbols. ________________________ Note ________________________ In OpenVMS Version 7.1, a cache of VMS environment variables (that is, logical names and DCL symbols) has been added to the getenv function to avoid the library making repeated calls to translate a logical name or to obtain the value of a DCL symbol. By default, the cache is disabled. If your application does not need to track changes in OpenVMS environment variables that can occur during its execution, the cache can be enabled by setting the DECC$ENABLE_GETENV_ CACHE logical before invoking the application (any equivalence string). ______________________________________________________ Return Values x Pointer to an array containing the translated symbol. An equivalence name is returned at index zero. NULL Indicates that the translation failed. REF-245 geteuid _________________________________________________________________ geteuid Returns, in OpenVMS terms, the member number from the user identification code (UIC). For example, if the UIC is [313,031], 031 is the member number. Format #include uid_t geteuid (void); Description In Compaq C for OpenVMS Systems, getuid and geteuid perform the same function. For programs compiled with the _VMS_V6_SOURCE feature- test macro or programs that do not include the header file, the getuid and geteuid functions return the member number of the OpenVMS UIC. For example, if the UIC is [313,31], then the member number, 31, is returned. For programs compiled without the _VMS_V6_SOURCE feature- test macro that do include the header file, the full UIC is returned. For example, if the UIC is [313, 31] then 20512799 (31 + 313 * 65536) is returned. See the getegid or getgid functions in this section for the functions that return the group number. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": REF-246 geteuid $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ Return Value x The member number from the current UIC. REF-247 getgid _________________________________________________________________ getgid Returns, in OpenVMS terms, the group number from the user identification code (UIC). For example, if the UIC is [313,031], 313 is the group number. Format #include gid_t getgid (void); Description In Compaq C for OpenVMS Systems, the getgid and getegid functions both return the group number from the current UIC. Similarly, getuid and geteuid both return the member number from the current UIC. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ Return Value x The group number from the current UIC. REF-248 getitimer _________________________________________________________________ getitimer Returns the value of interval timers. Format #include int getitimer (int which, struct itimerval *value); Arguments which The type of interval timer. The Compaq C RTL supports only ITIMER_REAL. value Pointer to an itimerval structure whose members specify a timer interval and the time left to the end of the interval. Description This function returns the current value for the timer specified by the which argument in the structure pointed to by value. A timer value is defined by the itimerval structure: struct itimerval { struct timeval it_interval; struct timeval it_value; }; The following table lists the values for the itimerval structure members: ___________________________________________________________ itimerval Member Value_________________Meaning______________________________ it_interval = 0 Disables a timer after its next expiration Assumes it_value is nonzero. REF-249 getitimer ___________________________________________________________ itimerval Member Value_________________Meaning______________________________ it_interval = Specifies a value used in reloading nonzero it_value when the timer expires. it_value = 0 Disables a timer. it_value = nonzero Indicates the time to the next timer ______________________expiration.__________________________ Time values smaller than the resolution of the system clock are rounded up to this resolution. The Compaq C RTL provides each process with one interval timer, defined in the header file as ITIMER_REAL. This timer decrements in real time and delivers a SIGALRM signal when the timer expires. Return Values 0 Indicates success. -1 Indicates an error; errno is set to EINVAL (The value argument specified a time that was too large to handle.) REF-250 getlogin _________________________________________________________________ getlogin Gets the login name. Format #include char *getlogin (void); Description The getlogin function returns the login name of the user associated with the current session. Return Values x A pointer to a null-terminated string in a static buffer. NULL Indicates an error. Login name is not set. REF-251 getname _________________________________________________________________ getname Returns the file specification associated with a file descriptor. Format #include char *getname (int file_desc, char *buffer, . . . ); Function Variants This function also has variants named _getname32 and _ getname64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments file_desc A file descriptor. buffer A pointer to a character string that is large enough to hold the file specification. . . . An optional argument that can be either 1 or 0. If you specify 1, the getname function returns the file specification in OpenVMS format. If you specify 0, the getname function returns the file specification in UNIX style format. If you do not specify this argument, the getname function returns the file name according to your current command-language interpreter (CLI). For more information about UNIX style file specifications, see Section 1.4.3. REF-252 getname Description This function places the file specification into the area pointed to by buffer and returns that address. The area pointed to by buffer should be an array large enough to contain a fully qualified file specification (the maximum length is 256 characters). Return Values x The address passed in the buffer argument. 0 Indicates an error. REF-253 getopt _________________________________________________________________ getopt A command-line parser that can be used by applications that follow Unix command-line conventions. Format #include (X/Open, POSIX-1) #include (X/Open, POSIX-2) int getopt (int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; Arguments argc The argument count as passed to main. argv The argument array as passed to main. optstring A string of recognized option characters. If a character is followed by a colon, the option takes an argument. Description The variable optind is the index of the next element of the argv vector to be processed. It is initialized to 1 by the system, and it is updated by getopt when it finishes with each element of argv. When an element of argv contains multiple option characters, it is unspecified how getopt determines which options have already been processed. The getopt function returns the next option character (if one is found) from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt sets the variable optarg to point to the option-argument as follows: REF-254 getopt o If the option was the last character in the string pointed to by an element of argv, then optarg contains the next element of argv, and optind is incremented by 2. If the resulting value of optind is not less than argc, getopt returns an error, indicating a missing option-argument. o Otherwise, optarg points to the string following the option character in that element of argv, and optind is incremented by 1. If one of the following is true, getopt returns -1 without changing optind: argv[optind] is a NULL pointer *argv[optind] is not the character - argv[optind] points to the string "-" If argv[optind] points to the string "- -" getopt returns -1 after incrementing optind. If getopt encounters an option character not contained in optstring, the question-mark character (?) is returned. If getopt detects a missing argument, the colon character (:) is returned if the first character of optstring is a colon; otherwise a question-mark character is returned. In either of the previous two cases, getopt sets the variable optopt to the option character that caused the error. If the application has not set the variable opterr to 0 and the first character of optstring is not a colon, getopt also prints a diagnostic message to stderr. REF-255 getopt Return Values x The next option character specified on the command line. A colon is returned if getopt detects a missing argument and the first character of optstring is a colon. A question mark is returned if getopt encounters an option character not in optstring or detects a missing argument and the first character of optstring is not a colon. -1 When all command-line options are parsed. Example The following example shows how you might process the arguments for a utility that can take the mutually exclusive options a and b and the options f and o, both of which require arguments: #include int main (int argc, char *argv[ ]) { int c; int bflg, aflg, errflg; char *ifile; char *ofile; extern char *optarg; extern int optind, optopt; . . . while ((c = getopt(argc, argv, ":abf:o:)) != -1) { REF-256 getopt switch (c) { case 'a': if (bflg) errflg++; else aflg++; break; case 'b': if (aflg) errflg++; else { bflg++; bproc(); } break; case 'f': ifile = optarg; break; case 'o': ofile = optarg; break; case ':': /* -f or -o without operand */ fprintf (stderr, "Option -%c requires an operand\n"' optopt); errflg++; break; case '?': fprintf (stderr, "Unrecognized option -%c\n"' optopt); errflg++; } } if (errflg) { fprintf (stderr, "usage: ..."); exit(2); } for ( ; optind < argc; optind++) { if (access(argv[optind], R_OK)) { . . . } REF-257 getopt This sample code accepts any of the following as equivalent: cmd -ao arg path path cmd -a -o arg path path cmd -o arg -a path path cmd -a -o arg -- path path cmd -a -oarg path path cmd -aoarg path path REF-258 getpagesize _________________________________________________________________ getpagesize Gets the system page size. Format #include int getpagesize (void); Description This function returns the number of bytes in a page. The system page size is useful for specifying arguments to memory management system calls. The page size is a system page size and is not necessarily the same as the underlying hardware page size. Return Values x Always indicates success. Returns the number of bytes in a page. REF-259 getpid _________________________________________________________________ getpid Returns the process ID of the current process. Format #include pid_t getpid (void); Return Value x The process ID of the current process. REF-260 getppid _________________________________________________________________ getppid Returns the parent process ID of the calling process. Format #include pid_t getppid (void); Return Values x The parent process ID. 0 Indicates that the calling process does not have a parent process. REF-261 getpwnam _________________________________________________________________ getpwnam Accesses user-name information in the user database. Format #include struct passwd *getpwnam (const char name); Arguments name The name of the user for which the attributes are to be read. Description This function returns the first user entry in the database with the pw_name member of the passwd structure that matches the name argument. The passwd structure is defined in the header file as follows: pw_name The user's login name. pw_uid The numerical user ID. pw_gid The numerical group ID. pw_dir The home directory of the user. pw_shell The initial program for the user. ________________________ Note ________________________ All information generated by the getpwnam function is stored in a static area and is overwritten on subsequent calls to the function. ______________________________________________________ REF-262 getpwnam Return Values x A pointer to a valid password structure. NULL An error occurred. errno is set to indicate the error. REF-263 getpwuid _________________________________________________________________ getpwuid Accesses user-ID information in the rights database. Format #include struct passwd *getpwuid (uid_t uid); Arguments uid The ID of the user for which the attributes are to be read. Description This function accesses the identifier names of all identifiers in the rights database. It returns the first user entry in the rights database with a pw_uid member of the passwd structure that matches the uid argument. The passwd structure is defined in the header file as follows: pw_name The user's login name. pw_uid The numerical user ID. pw_gid The numerical group ID. pw_dir The home directory of the user. pw_shell The initial program for the user. To check for error situations, applications should set errno to zero before calling getpwuid. If errno is non-zero on return, then an error occurred. ________________________ Note ________________________ All information generated by the getpwuid function is stored in a per-thread static area and is overwritten on subsequent calls to the function. ______________________________________________________ REF-264 getpwuid Return Values x A pointer to a valid password structure. NULL An error occurred. errno is set to indicate the error. REF-265 gets _________________________________________________________________ gets Reads a line from the standard input (stdin). Format #include char *gets (char *str); Function Variants This function also has variants named _gets32 and _gets64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Argument str A pointer to a character string that is large enough to hold the information fetched from stdin. Description The new-line character (\n) that ends the line is replaced by the function with an ASCII null character (\0). When stdin is opened in record mode, gets treats the end of a record the same as a new-line character and, therefore, reads up to and including a new-line character or to the end of the record. Return Values x A pointer to the str argument. REF-266 gets NULL Indicates that an error has occurred or that the end-of-file was encountered before a new-line character was encountered. The contents of str are undefined if a read error occurs. REF-267 [w]getstr _________________________________________________________________ [w]getstr Get a string from the terminal screen, store it in the variable str, and echo it on the specified window. The getstr function works on the stdscr window. Format #include int getstr (char *str); int wgetstr (WINDOW *win, char *str); Arguments win A pointer to the window. str Must be large enough to hold the character string fetched from the window. Description The getstr and wgetstr functions refresh the specified window before fetching a string. The new-line terminator is stripped from the fetched string. For more information, see the scrollok function in this section. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. REF-268 gettimeofday _________________________________________________________________ gettimeofday Gets date and time. Format #include int gettimeofday (struct timeval *tp, void *tpz); Arguments tp Pointer to a timeval structure, defined in the header file. tpz A NULL pointer. If this argument is not a NULL pointer, it is ignored. Description This function gets the current time (expressed as seconds and microseconds) since 00::00 Coordinated Universal Time, January 1, 1970. The current time is stored in the timeval structure pointed to by the tp argument. The tzp argument is intended to hold time-zone information set by the kernel. However, because the OpenVMS kernel does not set time-zone information, the tzp argument should be NULL. If it is not NULL, it is ignored. This function is supported for compatibility with BSD programs. If the value of the SYS$TIMEZONE_DIFFERENTIAL logical is wrong, the function fails with errno set to EINVAL. Return Values 0 Indicates success. -1 An error occurred. errno is set to indicate the error. REF-269 getuid _________________________________________________________________ getuid Returns, in OpenVMS terms, the member number from the user identification code (UIC). For example, if the UIC is [313,031], 031 is the member number. Format #include uid_t getuid (void); Description In Compaq C for OpenVMS Systems, getuid and geteuid perform the same function. For programs compiled with the _VMS_V6_SOURCE feature- test macro or programs that do not include the header file, the getuid and geteuid functions return the member number of the OpenVMS UIC. For example, if the UIC is [313,31], then the member number, 31, is returned. For programs compiled without the _VMS_V6_SOURCE feature- test macro that do include the header file, the full UIC is returned. For example, if the UIC is [313, 31] then 20512799 (31 + 313 * 65536) is returned. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ REF-270 getuid Return Value x The member number from the current UIC, or the full UIC. See description. REF-271 getw _________________________________________________________________ getw Returns characters from a specified file. Format #include int getw (FILE *file_ptr); Argument file_ptr A pointer to the file to be accessed. Description This function returns the next four characters from the specified input file as an int. Return Values x The next four characters, in an int. EOF Indicates that the end-of-file was encountered during the retrieval of any of the four characters and all four characters were lost. Since EOF is an acceptable integer, use feof and ferror to check the success of the function. REF-272 getwc _________________________________________________________________ getwc Reads the next character from a specified file, and converts it to a wide-character code. Format #include wint_t getwc (FILE *file_ptr); Arguments file_ptr A pointer to the file to be accessed. Description Since getwc is implemented as a macro, a file pointer argument with side effects (for example getwc (*f++)) might be evaluated incorrectly. In such a case, use the fgetwc function instead. See the fgetwc function in this section. Return Values n The returned character. WEOF Indicates the end-of-file or an error. If an error occurs, the function sets errno. For a list of the values set by this function, see fgetwc in this section. REF-273 getwchar _________________________________________________________________ getwchar Reads a single wide character from the standard input (stdin). Format #include wint_t getwchar (void); Description The getwchar function is identical to fgetwc(stdin). Return Values x The next character from stdin, converted to wint_t. WEOF Indicates the end-of-file or an error. If an error occurs, the function sets errno. For a list of the values set by this function, see fgetwc in this section. REF-274 getyx _________________________________________________________________ getyx Puts the (y,x) coordinates of the current cursor position on win in the variables y and x. Format #include getyx (WINDOW *win, int y, int x); Arguments win Must be a pointer to the window. y Must be a valid lvalue. x Must be a valid lvalue. REF-275 gmtime, gmtime_r _________________________________________________________________ gmtime, gmtime_r Converts time units to the broken-down UTC time. Format #include struct tm *gmtime (const time_t *timer); struct tm *gmtime_r (const time_t *timer, struct tm *result); (ISO POSIX-1) Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Arguments timer Points to a variable that specifies a time value in seconds since the Epoch. result A pointer to a tm structure where the result is stored. The tm structure is defined in the header, and is also shown in Table REF-4 in the description of localtime. Description The gmtime and gmtime_r functions convert the time (in seconds since the Epoch) pointed to by timer into a broken- down time, expressed as Coordinated Universal Time (UTC), and store it in a tm structure. The difference between the gmtime_r and gmtime functions is that the former puts the result into a user-specified tm structure where the result is stored. The latter puts the result into thread-specific static memory allocated by the Compaq C RTL, and which is overwritten by subsequent calls to gmtime; you must make a copy if you want to save it. REF-276 gmtime, gmtime_r On success, gmtime returns a pointer to the tm structure; gmtime_r returns its second argument. On failure, these functions return the NULL pointer. ________________________ Note ________________________ Generally speaking, UTC-based time functions can affect in-memory time-zone information, which is process-wide data. However, if the system time zone remains the same during the execution of the application (which is the common case) and the cache of timezone files is enabled (which is the default), then the _r variant of the time functions asctime_r, ctime_r, gmtime_r and localtime_r, is both thread-safe and AST-reentrant. If, however, the system time zone can change during the execution of the application or the cache of timezone files is not enabled, then both variants of the UTC-based time functions belong to the third class of functions, which are neither thread-safe nor AST-reentrant. ______________________________________________________ Return Values x Pointer to a tm structure. NULL Indicates an error; errno is set to one of the following values: o EINVAL - The timer argument is NULL. REF-277 gsignal _________________________________________________________________ gsignal Generates a specified software signal, which invokes the action routine established by a signal, ssignal, or sigvec function. Format #include int gsignal (int sig [, int sigcode]); Arguments sig The signal to be generated. sigcode An optional signal code. For example, signal SIGFPE- the arithmetic trap signal-has 10 different codes, each representing a different type of arithmetic trap. The signal codes can be represented by mnemonics or numbers. The arithmetic trap codes are represented by the numbers 1 to 10, but the SIGILL codes are represented by the numbers 0 to 2. The code values are defined in the header file. See Tables 4-4 and 4-5 for a list of signal mnemonics, codes, and corresponding OpenVMS exceptions. Description Calling this function has one of the following results: o If gsignal specifies a sig argument that is outside the range defined in the header file, then gsignal returns 0 and sets errno to EINVAL. o If signal, ssignal, or sigvec establishes SIG_DFL (default action) for the signal, then gsignal does not return. The image is exited with the OpenVMS error code corresponding to the signal. REF-278 gsignal o If signal, ssignal, or sigvec establishes SIG_IGN (ignore signal) as the action for the signal, then gsignal returns its argument, sig. o signal, ssignal, or sigvec must be used to establish an action routine for the signal. That function is called and its return value is returned by gsignal. See also raise, signal, ssignal, and sigvec in this section. See Chapter 4 for more information. Return Values 0 Indicates a sig argument that is outside the range defined in the header file; errno is set to EINVAL. sig Indicates that SIG_IGN (ignore signal) has been established as the action for the signal. x Indicates that signal, ssignal, or sigvec has established an action function for the signal. That function is called, and its return value is returned by gsignal. REF-279 hypot _________________________________________________________________ hypot Returns the square root of the sum of the squares of two arguments: sqrt(x[2] + y[2]) Format #include double hypot (double x, double y); Arguments x A real value. y A real value. Description On overflow, the return value is undefined. REF-280 iconv _________________________________________________________________ iconv Converts characters coded in one codeset to characters coded in another codeset. Format #include size_t iconv (iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft); Arguments cd A conversion descriptor. This is returned by a successful call to iconv_open. inbuf A pointer to a variable that points to the first character in the input buffer. inbytesleft Initially, this argument is a pointer to a variable that indicates the number of bytes to the end of the input buffer (inbuf). When the conversion is completed, the variable indicates the number of bytes in inbuf not converted. outbuf A pointer to a variable that points to the first available byte in the output buffer. The output buffer contains the converted characters. outbytesleft Initially, this argument is a pointer to a variable that indicates the number of bytes to the end of the output buffer (outbuf). When the conversion is completed, the variable indicates the number of bytes left in outbuf. REF-281 iconv Description This function converts characters in the buffer pointed to by inbuf to characters in another code set. The resulting characters are stored in the buffer pointed to by outbuf. The conversion type is specified by the conversion descriptor cd. This descriptor is returned from a successful call to iconv_open. If an invalid character is found in the input buffer, the conversion stops after the last successful conversion. The variable pointed to by inbytesleft is updated to reflect the number of bytes in the input buffer that are not converted. The variable pointed to by outbytesleft is updated to reflect the number of bytes remaining in the output buffer. Return Values x Number of non-identical conversions performed. Indicates successful conversion. In most cases 0 is returned. (size_t) -1 Indicates an error condition. The function sets errno to one of the following: o EBADF - The cd argument is not a valid conversion descriptor. o EILSEQ - The conversion stops when an invalid character detected. o E2BIG - The conversion stops because of insufficient space in the output buffer. o EINVAL - The conversion stops because of an incomplete character at the end of the input buffer. REF-282 iconv_close _________________________________________________________________ iconv_close Deallocates a specified conversion descriptor and the resources allocated to the descriptor. Format #include int iconv_close (iconv_t cd); Arguments cd The conversion descriptor to be deallocated. A conversion descriptor is returned by a successful call to iconv_open. Return Values 0 Indicates that the conversion descriptor was successfully deallocated. -1 Indicates an error occurred. The function sets errno to one of the following: o EBADF - The cd argument is not a valid conversion descriptor. o EVMSERR - Non-translatable VMS error occur. vaxc$errno contains the VMS error code. REF-283 iconv_open _________________________________________________________________ iconv_open Allocates a conversion descriptor for a specified codeset conversion. Format #include iconv_t iconv_open (const char *tocode, const char *fromcode); Arguments tocode The name of the codeset to which characters are converted. fromcode The name of the source codeset. See Chapter 10 for information on obtaining a list of currently available codesets or for details on adding new codesets. Return Values x A conversion descriptor. Indicates the call was successful. This descriptor is used in subsequent calls to iconv REF-284 iconv_open (iconv_t) -1 Indicates an error occurred. The function sets errno to one of the following: o EMFILE - The process does not have enough I/O channels to open a file. o ENOMEM - Insufficient space is available. o EINVAL - The conversion specified by fromcode and tocode is not supported. o EVMSERR - Nontranslatable VMS error occur. vaxc$errno contains the VMS error code. A value of SS$_BADCHKSUM in vaxc$errno indicates that a conversion table file was found, but its contents is corrupted. A value of SS$_ IDMISMATCH in vaxc$errno indicates that the conversion table file version does not match the version of the C Run-Time Library. Example #include #include #include int main() { /* Declare variables to be used */ char fromcodeset[30]; char tocodeset[30]; int iconv_opened; iconv_t iconv_ struct; /* Iconv descriptor */ /* Initialize variables */ REF-285 iconv_open sprintf(fromcodeset, "DECHANYU"); sprintf(tocodeset, "EUCTW"); iconv_opened = FALSE; /* Attempt to create a conversion descriptor for the */ /* codesets specified. If the return value from */ /* iconv_ open is -1 then an error has occurred. */ /* Check the value of errno. */ if ((iconv_struct = iconv_ open(tocodeset, fromcodeset)) == (iconv_t) - 1) { /* Check the value of errno */ switch (errno) { case EMFILE: case ENFILE: printf("Too many iconv conversion files open\n"); break; case ENOMEM: printf("Not enough memory\n"); break; case EINVAL: printf("Unsupported conversion\n"); break; default: printf("Unexpected error from iconv_ open\n"); break; } } else /* Successfully allocated a conversion descriptor */ iconv_opened = TRUE; /* Was a conversion descriptor allocated */ if (iconv_opened) { REF-286 iconv_open /* Attempt to deallocate the conversion descriptor. */ /* If iconv_close returns - 1 then an error has */ /* occurred. */ if (iconv_close(iconv_struct) == -1) { /* An error occurred. Check the value of errno */ switch (errno) { case EBADF: printf("Conversion descriptor is invalid\n"); break; default: printf("Unexpected error from iconv_ close\n"); break; } } } return (EXIT_FAILURE); } REF-287 [w]inch _________________________________________________________________ [w]inch Return the character at the current cursor position on the specified window without making changes to the window. The inch function acts on the stdscr window. Format #include char inch(); char winch (WINDOW *win); Argument win A pointer to the window. Return Values x The returned character. ERR Indicates an input error. REF-288 index _________________________________________________________________ index Search for a character in a string. Format #include char *index (const char *s, int c); Function Variants This function also has variants named _index32 and _index64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Arguments s The string to search. c The character to search for. Description The index function is identical to the strchr function, and is provided for compatibility with some UNIX implementations. REF-289 initscr _________________________________________________________________ initscr Initializes the terminal-type data and all screen functions. You must call initscr before using any of the curses functions. Format #include void initscr (void); Description The OpenVMS Curses version of this function clears the screen before doing the initialization. The BSD-based Curses version does not. REF-290 initstate _________________________________________________________________ initstate Initializes random number generators. Format #include char *initstate (unsigned int seed, char *state, int size); Arguments seed An initial seed value. state Pointer to an array of state information. size The size of the state information array. Description This function initializes random number generators. It lets you initialize for future use, a state array passed as an argument. The size in bytes of the state array is used by the initstate function to decide how sophisticated a random number generator to use; the larger the state array, the more random the numbers. Values for the amount of state information are 8, 32, 64, 128, and 256 bytes. Amounts less than 8 bytes generate an error, while other amounts are rounded down to the nearest known value. The seed argument specifies a starting point for the random number sequence and provides for restarting at the same point. The initstate function returns a pointer to the previous state information array. REF-291 initstate Once you initialize a state, the setstate function allows rapid switching between states. The array defined by the state argument is used for further random number generation until the initstate function is called or the setstate function is called again. The setstate function returns a pointer to the previous state array. After initialization, you can restart a state array at a different point in one of two ways: o Use the initstate function with the desired seed argument, state array, and size of the array. o Use the setstate function with the desired state, followed by the srandom function with the desired seed. The advantage of using both functions is that you do not have to save the state array size once you initialize it. See also setstate, srandom, and random, in this section. Return Values x A pointer to the previous state array information. 0 Indicates an error. Call made with less than 8 bytes of state information. Further specified in the global errno. REF-292 [w]insch _________________________________________________________________ [w]insch Insert a character at the current cursor position in the specified window. The insch function acts on the stdscr window. Format #include int insch (char ch); int winsch (WINDOW *win, char ch); Arguments win A pointer to the window. ch The character to be inserted. Description After the character is inserted, each character on the line shifts to the right, and the last character in the line is deleted. For more information, see the scrollok function in this section. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. REF-293 [w]insertln _________________________________________________________________ [w]insertln Insert a line above the line containing the current cursor position. The insertln function acts on the stdscr window. Format #include int insertln(); int winsertln (WINDOW *win); Argument win A pointer to the window. Description The current line and every line below it shifts down, and the bottom line disappears. The inserted line is blank and the current (y,x) coordinates remain the same. For more information, see the scrollok function in this section. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. REF-294 [w]insstr _________________________________________________________________ [w]insstr Insert a string at the current cursor position in the specified window. The insstr function acts on the stdscr window. Format #include int insstr (char *str); int winsstr (WINDOW *win, char *str); Arguments win A pointer to the window. str A pointer to the string to be inserted. Description Each character after the string shifts to the right, and the last character disappears. These functions are specific to Compaq C for OpenVMS Systems and are not portable. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. For more information, see the scrollok function in this section. REF-295 isalnum _________________________________________________________________ isalnum Indicates if a character is classed either as alphabetic or as a digit in the program's current locale. Format #include int isalnum (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If alphanumeric. 0 If not alphanumeric. REF-296 isalpha _________________________________________________________________ isalpha Indicates if a character is classed as an alphabetic character in the program's current locale. Format #include int isalpha (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If alphabetic. 0 If not alphabetic. REF-297 isapipe _________________________________________________________________ isapipe Indicates if a specified file descriptor is associated with a pipe. Format #include int isapipe (int file_desc); Argument file_desc A file descriptor. Description For more information about pipes, see Chapter 5. Return Values 1 Indicates an association with a pipe. 0 Indicates no association with a pipe. -1 Indicates an error (for example, if the file descriptor is not associated with an open file). REF-298 isascii _________________________________________________________________ isascii Indicates if a character is an ASCII character. Format #include int isascii (int character); Argument character An object of type char. Return Values nonzero If ASCII. 0 If not ASCII. REF-299 isatty _________________________________________________________________ isatty Indicates if a specified file descriptor is associated with a terminal. Format #include int isatty (int file_desc); Argument file_desc A file descriptor. Return Values 1 If the file descriptor is associated with a terminal. 0 If the file descriptor is not associated with a terminal. -1 Indicates an error (for example, if the file descriptor is not associated with an open file). REF-300 iscntrl _________________________________________________________________ iscntrl Indicates if a character is classed as a control character in the program's current locale. Format #include int iscntrl (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a control character. zero If not a control character. REF-301 isdigit _________________________________________________________________ isdigit Indicates if a character is classed as a digit in the program's current locale. Format #include int isdigit (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a decimal digit. 0 If not a decimal digit. REF-302 isgraph _________________________________________________________________ isgraph Indicates if a character is classed as a graphic character in the program's current locale. Format #include int isgraph (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a graphic character. 0 If not a graphic character. REF-303 islower _________________________________________________________________ islower Indicates if a character is classed as a lowercase character in the program's current locale. Format #include int islower (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a lowercase alphabetic character. 0 If not a lowercase alphabetic character. REF-304 isprint _________________________________________________________________ isprint Indicates if a character is classed as a printing character in the program's current locale. Format #include int isprint (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a printing character. 0 If not a printing character. REF-305 ispunct _________________________________________________________________ ispunct Indicates if a character is classed as a punctuation character in the program's current locale. Format #include int ispunct (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a punctuation character. 0 If not a punctuation character. REF-306 isspace _________________________________________________________________ isspace Indicates if a character is classed as white space in the program's current locale; that is, if it is an ASCII space, tab (horizontal or vertical), carriage-return, form-feed, or new-line character. Format #include int isspace (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a white-space character. 0 If not a white-space character. REF-307 isupper _________________________________________________________________ isupper Indicates if a character is classed as an uppercase character in the program's current locale. Format #include int isupper (int character); Argument character An object of type int. The value of character must be representable as an unsigned char or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If an uppercase alphabetic character. 0 If not an uppercase alphabetic character. REF-308 iswalnum _________________________________________________________________ iswalnum Indicates if a wide character is classed either as alphabetic or as a digit in the program's current locale. Format #include (ISO C) #include (XPG4) int iswalnum (wint_t wc); Arguments wc An object of type wint_t. The value of character must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If alphanumeric. 0 If not alphanumeric. REF-309 iswalpha _________________________________________________________________ iswalpha Indicates if a wide character is classed as an alphabetic character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswalpha (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If alphabetic. 0 If not alphabetic. REF-310 iswcntrl _________________________________________________________________ iswcntrl Indicates if a wide character is classed as a control character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswcntrl (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a control character. 0 If not a control character. REF-311 iswctype _________________________________________________________________ iswctype Indicates if a wide character has a specified property. Format #include (ISO C) #include (XPG4) int iswctype (wint_t wc, wctype_t wc_prop); Arguments wc An object of type wint_t. The value of wc must be representable as a valid wide-character code in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. wc_prop A valid property name in the current locale. This is set up by calling the wctype function. Description This function tests whether wc has the character-class property wc_prop. Set wc_prop by calling the wctype function. See also wctype in this section. Return Values nonzero If the character has the property wc_prop. 0 If the character does not have the property wc_prop. REF-312 iswctype Example #include #include #include #include #include #include /* This test will set up the "upper" character class using */ /* wctype() and then verify whether the characters 'a' and 'A' */ /* are members of this class */ #include main() { wchar_t w_char1, w_char2; wctype_t ret_val; char *char1 = "a"; char *char2 = "A"; ret_val = wctype("upper"); /* Convert char1 to wide-character format - w_ char1 */ if (mbtowc(&w_char1, char1, 1) == -1) { perror("mbtowc"); exit(EXIT_FAILURE); } if (iswctype((wint_t) w_char1, ret_val)) printf("[%C] is a member of the character class upper\n", w_char1); else printf("[%C] is not a member of the character class upper\n", w_char1); /* Convert char2 to wide-character format - w_ char2 */ REF-313 iswctype if (mbtowc(&w_char2, char2, 1) == -1) { perror("mbtowc"); exit(EXIT_FAILURE); } if (iswctype((wint_t) w_char2, ret_val)) printf("[%C] is a member of the character class upper\n", w_char2); else printf("[%C] is not a member of the character class upper\n", w_char2); } Running the example program produces the following result: [a] is not a member of the character class upper [A] is a member of the character class upper REF-314 iswdigit _________________________________________________________________ iswdigit Indicates if a wide character is classed as a digit in the program's current locale. Format #include (ISO C) #include (XPG4) int iswdigit (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a decimal digit. 0 If not a decimal digit. REF-315 iswgraph _________________________________________________________________ iswgraph Indicates if a wide character is classed as a graphic character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswgraph (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a graphic character. 0 If not a graphic character. REF-316 iswlower _________________________________________________________________ iswlower Indicates if a wide character is classed as a lowercase character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswlower (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a lowercase character. 0 If not a lowercase character. REF-317 iswprint _________________________________________________________________ iswprint Indicates if a wide character is classed as a printing character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswprint (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a printing character. 0 If not a printing character. REF-318 iswpunct _________________________________________________________________ iswpunct Indicates if a wide character is classed as a punctuation character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswpunct (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a punctuation character. 0 If not a punctuation character. REF-319 iswspace _________________________________________________________________ iswspace Indicates if a wide character is classed as a space character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswspace (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a whitespace character. 0 If not a whitespace character. REF-320 iswupper _________________________________________________________________ iswupper Indicates if a wide character is classed as an uppercase character in the program's current locale. Format #include (ISO C) #include (XPG4) int iswupper (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If an uppercase character. 0 If not an uppercase character. REF-321 iswxdigit _________________________________________________________________ iswxdigit Indicates if a wide character is a hexadecimal digit (0 to 9, A to F, or a to f) in the program's current locale. Format #include (ISO C) #include (XPG4) int iswxdigit (wint_t wc); Arguments wc An object of type wint_t. The value of wc must be representable as a wchar_t in the current locale, or must equal the value of the macro WEOF. If it has any other value, the behavior is undefined. Return Values nonzero If a hexadecimal digit. 0 If not a hexadecimal digit. REF-322 isxdigit _________________________________________________________________ isxdigit Indicates if a character is a hexadecimal digit (0 to 9, A to F, or a to f) in the program's current locale. Format #include int isxdigit (int character); Argument character An object of type int. The value of character must be representable as an unsigned char in the current locale, or must equal the value of the macro EOF. If it has any other value, the behavior is undefined. Return Values nonzero If a hexadecimal digit. 0 If not a hexadecimal digit. REF-323 jrand48 _________________________________________________________________ jrand48 Generate uniformly distributed pseudorandom number sequences. Returns 48-bit signed, long integers. Format #include long int jrand48 (unsigned short int xsubi[3]); Arguments xsubi An array of three short int that form a 48-bit integer when concatentated together. Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. The function returns signed long integers uniformly distributed over the range of y values, such that -231 y < 231. The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 The jrand48 function requires that the calling program pass an array as the xsubi argument, which for the first call must be initialized to the initial value of the pseudorandom number sequence. Unlike the drand48 function, it is not necessary to call an initialization function prior to the first call. REF-324 jrand48 By using different arguments, jrand48 allows separate modules of a large program to generate several independent sequences of pseudorandom numbers. For example, the sequence of numbers that one module generates does not depend upon how many times the function is called by other modules. Return Values n Signed, long integers uniformly distributed over the range -231 y < 231. REF-325 kill _________________________________________________________________ kill Sends a signal to the process specified by a process ID. Format #include int kill (int pid, int sig); Arguments pid The process ID. sig The signal code. Description This function is restricted to C and C++ programs that include the main function. The kill function sends a signal to a process, as if the process had called raise. If the signal is not trapped or ignored by the target program, the program exits. OpenVMS VAX and Alpha implement different rules about what process you are allowed to send signals to. A program always has privileges to send a signal to a child started with vfork/exec. For other processes, the results are determined by the OpenVMS security model for your system. Because of an OpenVMS restriction, the kill function cannot deliver a signal to a target process that runs an image installed with privileges. Unless you have system privileges, the sending and receiving processes must have the same user identification code (UIC). On OpenVMS systems before Version 7.0, kill treats a signal value of 0 as if SIGKILL were specified. REF-326 kill For OpenVMS Version 7.0 and higher systems, if you include and compile with the _POSIX_EXIT feature-test macro set, then: o If the signal value is 0, kill validates the process ID but does not send any signals. o If the process ID is not valid, kill returns -1 and sets errno to ESRCH. Return Values 0 Indicates that kill was successfully queued. -1 Indicates errors. The receiving process may have a different UIC and you are not a system user, or the receiving process does not exist. REF-327 labs _________________________________________________________________ labs Returns the absolute value of an integer as a long int. Format #include long int labs (long int j); Argument j A value of type long int. REF-328 lcong48 _________________________________________________________________ lcong48 Initializes a 48-bit uniformly distributed pseudorandom number sequences. Format #include void lcong48 (unsigned short int param[7]); Arguments param An array that in turn specifies the initial Xi, the multiplier value a, and the addend value c. Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. You can use lcong48 to initialize the random number generator before you call any of the following functions: drand48 lrand48 mrand48 The lcong48 function specifies the initial Xi value, the multiplier value a, and the addend value c. The param array elements specify the following: param[0-2] Xi param[3-5] Multiplier a value param[6] 16-bit addend c value After lcong48 has been called, a subsequent call to either srand48 or seed48 restores the standard a and c as specified previously. The lcong48 function does not return a value. REF-329 lcong48 See also drand48, lrand48, mrand48, srand48, and seed48 in this section. REF-330 ldexp _________________________________________________________________ ldexp Returns its first argument multiplied by 2 raised to the power of its second argument; that is, x(2n). Format #include double ldexp (double x, int n); Arguments x n A base value of type double that is to be multiplied by 2 . n The integer exponent value to which 2 is raised. Return Values x(2n) The first argument multiplied by 2 raised to the power of the second argument. 0 Indicates underflow; errno is set to ERANGE. HUGE_VAL Indicates overflow; errno is set to ERANGE. REF-331 ldiv _________________________________________________________________ ldiv Returns the quotient and the remainder after the division of its arguments. Format #include ldiv_t ldiv (long int numer, long int denom); Arguments numer A numerator of type long int. denom A denominator of type long int. Description The type ldiv_t is defined in the header file as follows: typedef struct { long quot, rem; } ldiv_t; See also div in this section. REF-332 leaveok _________________________________________________________________ leaveok Signals Curses to leave the cursor at the current coordinates after an update to the window. Format #include leaveok (WINDOW *win, bool boolf); Arguments win A pointer to the window. boolf A Boolean TRUE or FALSE value. If boolf is TRUE, the cursor remains in place after the last update and the coordinate setting on win changes accordingly. If boolf is FALSE, the cursor moves to the currently specified (y,x) coordinates of win. Description This function defaults to moving the cursor to the current coordinates of win. The bool type is defined in the header file as follows: #define bool int REF-333 link _________________________________________________________________ link Creates a new link (directory entry) for an existing file. Format #include link (const char *path1, const char *path2); Arguments path1 Pointer to a path name naming an existing file. path2 Pointer to a path name naming the new directory entry to be created. Description The link function atomically creates a new link for the existing file, and the link count of the file is incremented by one. The link function can be used on directory files. If link fails, no link is created and the link count of the file remains unchanged. Return Values 0 Successful completion. REF-334 link -1 Indicates an error. The function sets errno to one of the following values: o EEXIST - The link named by path2 exists. o EFTYPE - Wildcards appear in either path1 or path2. o EINVAL - One or both arguments specify a syntactically invalid path name. o ENAMETOOLONG - The length of path1 or path2 exceeds {PATH_MAX}, or a path name component is longer than {NAME_MAX}. o EXDEV - The link named by path2 and the file named by path1 are on different devices. REF-335 localeconv _________________________________________________________________ localeconv Sets the members of a structure of type struct lconv with values appropriate for formatting numeric quantities according to the rules of the current locale. Format #include struct lconv *localeconv (void); Description This function returns a pointer to the lconv structure defined in the header file. This structure should not be modified by the program. It is overwritten by calls to localeconv, or by calls to the setlocale function that change the LC_NUMERIC, LC_MONETARY, or LC_ ALL categories. The members of the structure are: ___________________________________________________________ Member________________Description__________________________ char *decimal_point The radix character char *thousands_sep The character used to separate groups of digits char *grouping The string that defines how digits are grouped in non-monetary values. char *int_curr_ The international currency symbol symbol char *currency_ The local currency symbol symbol char *mon_decimal_ The radix character used to format point monetary values char *mon_thousands_ The character used to separate groups sep of digits in monetary values char *mon_grouping The string that defines how digits are grouped in a monetary value REF-336 localeconv ___________________________________________________________ Member________________Description__________________________ char *positive_sign The string used to indicate a non- negative monetary value char *negative_sign The string used to indicate a negative monetary value char int_frac_digits The number of digits displayed after the radix character in a monetary value formatted with the international currency symbol. char frac_digits The number of digits displayed after the radix character in a monetary value char p_cs_precedes For positive monetary values, this is set to 1 if the local or international currency symbol precedes the number, and it is set to 0 if the symbol succeeds the number. char p_sep_by_space For positive monetary values, this is set to 0 if there is no space between the currency symbol and the number. It is set to 1 if there is a space, and it is set to 2 if there is a space between the symbol and the sign string. char n_cs_precedes For negative monetary values, this is set to 1 if the local or international currency symbol precedes the number, and it is set to 0 if the symbol succeeds the number. char n_sep_by_space For negative monetary values, this is set to 0 if there is no space between the currency symbol and the number. It is set to 1 if there is a space, and it is set to 2 if there is a space between the symbol and the sign string. char p_sign_posn An integer used to indicate where the positive_sign string should be placed for a non-negative monetary quantity. REF-337 localeconv ___________________________________________________________ Member________________Description__________________________ char n_sign_posn An integer used to indicate where the negative_sign string should be placed ______________________for_a_negative_monetary_quantity.____ Members of the structure of type char* are pointers to strings, any of which (except decimal_point) can point to "", indicating that the associated value is not available in the current locale or is zero length. Members of the structure of type char are positive numbers, any of which can be CHAR_MAX, indicating that the associated value is not available in the current locale. CHAR_MAX is defined in the header file. Be aware that the value of the CHAR_MAX macro in the header depends on whether the program is compiled with the /UNSIGNED_CHAR qualifier: o Use the CHAR_MAX macro as an indicator of a non- available value in the current locale only if the program is compiled without /UNSIGNED_CHAR (/NOUNSIGNED_ CHAR is the default). o If the program is compiled with /UNSIGNED_CHAR, use the SCHAR_MAX macro instead of the CHAR_MAX macro. In /NOUNSIGNED_CHAR mode, the values of CHAR_MAX and SCHAR_ MAX are the same; therefore, comparison with SCHAR_MAX gives correct results regardless of the /[NO]UNSIGNED_CHAR mode used. The members grouping and mon_grouping point to a string that defines the size of each group of digits when formatting a number. Each group size is separated by a semicolon (;). For example, if grouping points to the string 5;3 and the thousands_sep character is a comma (,), the number 123450000 would be formatted as 1,234,50000. The elements of grouping and mon_grouping are interpreted as follows: ___________________________________________________________ Value_______Interpretation_________________________________ CHAR_MAX No further grouping is performed. REF-338 localeconv ___________________________________________________________ Value_______Interpretation_________________________________ 0 The previous element is to be used repeatedly for the remainder of the digits. other The integer value is 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 values of p_sign_posn and n_sign_posn are interpreted as follows: ___________________________________________________________ Value_____Interpretation___________________________________ 0 Parentheses surround the number and currency symbol. 1 The sign string precedes the number and currency symbol. 2 The sign string succeeds the number and currency symbol. 3 The sign string immediately precedes the number and currency symbol. 4 The sign string immediately succeeds the number __________and_currency_symbol._____________________________ Return Value x Pointer to the lconv structure. Example #include #include #include #include #include /* The following test program will set up the British English */ /* locale, and then extract the International Currency symbol */ /* and the International Fractional Digits fields for this */ /* locale and print them. */ REF-339 localeconv int main() { /* Declare variables */ char *return_val; struct lconv *lconv_ptr; /* Load a locale */ return_val = (char *) setlocale(LC_ALL, "en_ GB.iso8859-1"); /* Did the locale load successfully? */ if (return_val == NULL) { /* It failed to load the locale */ printf("ERROR : The locale is unknown"); exit(EXIT_FAILURE); } /* Get the lconv structure from the locale */ lconv_ptr = (struct lconv *) localeconv(); /* Compare the international currency symbol string with an */ /* empty string. If they are equal, then the international */ /* currency symbol is not defined in the locale. */ if (strcmp(lconv_ptr->int_curr_symbol, "")) { printf("International Currency Symbol = %s\n", lconv_ptr->int_curr_symbol); } else { printf("International Currency Symbol ="); printf("[Not available in this locale]\n"); } /* Compare International Fractional Digits with CHAR_ MAX. */ /* If they are equal, then International Fractional Digits */ /* are not defined in this locale. */ if ((unsigned char) (lconv_ptr->int_frac_ REF-340 localeconv digits) != CHAR_MAX) { printf("International Fractional Digits = %d\n", lconv_ptr->int_frac_digits); } else { printf("International Fractional Digits ="); printf("[Not available in this locale]\n"); } } Running the example program produces the following result: International Currency Symbol = GBP International Fractional Digits = 2 REF-341 localtime, localtime_r _________________________________________________________________ localtime, localtime_r Converts a time value to broken-down local time. Format #include struct tm *localtime (const time_t *timer); struct tm *localtime_r (const time_t *timer, struct tm *result); (ISO POSIX-1) Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Argument timer A pointer to a time in seconds since the Epoch. You can generate this time by using the time function or you can supply a time. result A pointer to a tm structure where the result is stored. The tm structure is defined in the header file, and is also shown in Table REF-4. Description The localtime and localtime_r functions convert the time (in seconds since the Epoch) pointed to by timer into a broken-down time, expressed as a local time, and store it in a tm structure. The difference between the localtime_r and localtime functions is that the former stores the result into a user- specified tm structure. The latter stores the result into thread-specific static memory allocated by the Compaq C REF-342 localtime, localtime_r RTL, and which is overwritten by subsequent calls to localtime; you must make a copy if you want to save it. On success, localtime returns a pointer to the tm structure; localtime_r returns its second argument. On failure, these functions return the NULL pointer. The tm structure is defined in the header file and described in Table REF-4. Table_REF-4_tm_Structure___________________________________ int tm_sec; Seconds after the minute (0-60) int tm_min; Minutes after the hour (0-59) int tm_hour; Hours since midnight (0-23) int tm_mday; Day of the month (1-31) int tm_mon; Months since January (1-11) int tm_year; Years since 1900 int tm_wday; Days since Sunday (0-6) int tm_yday; Days since January 1 (0-365) int tm_isdst; Daylight Savings Time flag o tm_isdst = 0 for Standard Time o tm_isdst = 1 for Daylight Time long tm_ Seconds east of Greenwich (Negative values gmtoff;[1] indicate seconds west of Greenwich) char *tm_ Time zone string, for example "GMT" zone;[1] [1]This_field_is_an_extention_to_the_ANSI_C_tm_structure.__ It is present unless you compile your program with /STANDARD=ANSI89 or with _DECC_V4_SOURCE defined. ___________________________________________________________ The type time_t is defined in the header file as follows: typedef long int time_t ________________________ Note ________________________ Generally speaking, UTC-based time functions can affect in-memory time-zone information, which is REF-343 localtime, localtime_r process-wide data. However, if the system time zone remains the same during the execution of the application (which is the common case) and the cache of timezone files is enabled (which is the default), then the _r variant of the time functions asctime_r, ctime_r, gmtime_r and localtime_r, is both thread-safe and AST-reentrant. If, however, the system time zone can change during the execution of the application or the cache of timezone files is not enabled, then both variants of the UTC-based time functions belong to the third class of functions, which are neither thread-safe nor AST-reentrant. ______________________________________________________ Return Value x Pointer to a tm structure. NULL Indicates failure. REF-344 log, log10 _________________________________________________________________ log, log10 Return the logarithm of their arguments. Format #include double log (double x); double log10 (double x); Argument x A real number of type double. Description The log function performs a natural (base e) logarithm. The log10 functions performs a base 10 logarithm. Return Values x The logarithm of the argument (in the appropriate base). -HUGE_VAL Indicates that the argument is 0 or negative; errno is set to ERANGE. REF-345 longjmp _________________________________________________________________ longjmp Provides a way to transfer control from a nested series of function invocations back to a predefined point without returning normally; that is, by not using a series of return statements. The longjmp function restores the context of the environment buffer. Format #include void longjmp (jmp_buf env, int value); Arguments env The environment buffer, which must be an array of integers long enough to hold the register context of the calling function. The type jmp_buf is defined in the header file. The contents of the general-purpose registers, including the program counter (PC), are stored in the buffer. value Passed from longjmp to setjmp, and then becomes the subsequent return value of the setjmp call. If value is passed as 0, it is converted to 1. Description When setjmp is first called, it returns the value 0. If longjmp is then called, naming the same environment as the call to setjmp, control is returned to the setjmp call as if it had returned normally a second time. The return value of setjmp in this second return is the value you supply in the longjmp call. To preserve the true value of setjmp, the function calling setjmp must not be called again until the associated longjmp is called. REF-346 longjmp The setjmp function preserves the hardware general purpose registers, and the longjmp function restores them. After a longjmp, all variables have their values as of the time of the longjmp except for local automatic variables not marked volatile. These variables have indeterminate values. The setjmp and longjmp functions rely on the OpenVMS condition-handling facility to effect a nonlocal goto with a signal handler. The longjmp function is implemented by generating a Compaq C RTL specified signal and allowing the OpenVMS condition-handling facility to unwind back to the desired destination. The Compaq C RTL must be in control of signal handling for any Compaq C image. For Compaq C to be in control of signal handling, you must establish all exception handlers through a call to the VAXC$ESTABLISH function (rather than LIB$ESTABLISH). See Section 4.2.5 and the VAXC$ESTABLISH function in this section for more information. ________________________ Note ________________________ There are Alpha specific, non-standard decc$setjmp and decc$fast_longjmp functions. To use these non-standard functions instead of the standard ones, a program must be compiled with __FAST_SETJMP or __UNIX_SETJMP macros defined. Unlike the standard longjmp function, the decc$fast_ longjmp function does not convert its second argument from 0 to 1. After a call to decc$fast_longjmp, a corresponding setjmp function returns with the exact value of the second argument specified in the decc$fast_longjmp call. ______________________________________________________ Restrictions You cannot invoke the longjmp function from a OpenVMS condition handler. However, you may invoke longjmp from a signal handler that has been established for any signal supported by the Compaq C RTL, subject to the following nesting restrictions: o The longjmp function will not work if invoked from nested signal handlers. The result of the longjmp REF-347 longjmp function, when invoked from a signal handler that has been entered as a result of an exception generated in another signal handler, is undefined. o Do not invoke the setjmp function from a signal handler unless the associated longjmp is to be issued before the handling of that signal is completed. o Do not invoke the longjmp function from within an exit handler (established with atexit or SYS$DCLEXH). Exit handlers are invoked after image tear-down, so the destination address of the longjmp no longer exists. o Invoking longjmp from within a signal handler to return to the main thread of execution might leave your program in an inconsistent state. Possible side effects include the inability to perform I/O or to receive any more UNIX signals. REF-348 longname _________________________________________________________________ longname Returns the full name of the terminal. Format #include void longname (char *termbuf, char *name); Function Variants This function also has variants named _longname32 and _ longname64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments termbuf A string containing the name of the terminal. name A character-string buffer with a minimum length of 64 characters. Description The terminal name is in a readable format so that you can double-check to be sure that Curses has correctly identified your terminal. The dummy argument termbuf is required for UNIX software compatibility and serves no function in the OpenVMS environment. If portability is a concern, you must write a set of dummy routines to perform the functionality provided by the database termcap in the UNIX system environment. REF-349 lrand48 _________________________________________________________________ lrand48 Generates uniformly distributed pseudorandom number sequences. Returns 48-bit signed long integers. Format #include long int lrand48 (void); Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. It returns nonnegative, long integers uniformly distributed over the range of y values such that 0 y < 231. Before you call the lrand48 function use either srand48, seed48, or lcong48 to initialize the random number generator. You must initialize prior to invoking the lrand48 function, because it stores the last 48-bit Xi generated into an internal buffer. (Although it is not recommended, constant default initializer values are supplied automatically if the drand48, lrand48, or mrand48 functions are called without first calling an initialization function.) The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 REF-350 lrand48 The value returned by the lrand48 function is computed by first generating the next 48-bit Xi in the sequence. Then the appropriate bits, according to the type of data item to be returned, are copied from the high-order (most significant) bits of Xi and transformed into the returned value. See also drand48, lcong48, mrand48, seed48, and srand48 in this section. Return Values n Signed nonnegative long integers uniformly distributed over the range 0 y < 231. REF-351 lseek _________________________________________________________________ lseek Positions a file to an arbitrary byte position and returns the new position as an int. Format #include off_t lseek (int file_desc, off_t offset, int direction); Arguments file_desc An integer returned by open, creat, dup, or dup2. offset The offset, specified in bytes. direction An integer indicating whether the offset is to be measured forward from the beginning of the file (direction=SEEK_ SET), forward from the current position (direction=SEEK_ CUR), or backward from the end of the file (direction=SEEK_ END). Description This function can position fixed-length record-access file with no carriage control or a stream-access file on any byte offset, but can position all other files only on record boundaries. The available Standard I/O functions position a record file at its first byte, at the end-of-file, or on a record boundary. Therefore, the arguments given to lseek must specify either the beginning or end of the file, a 0 offset from the current position (an arbitrary record boundary), or the position returned by a previous, valid lseek call. For a portable way to position an arbitrary byte location with any type of file, see the fgetpos and fsetpos functions in this section. REF-352 lseek _______________________ CAUTION _______________________ If, while accessing a stream file, you seek beyond the end-of-file and then write to the file, the lseek function creates a hole by filling the skipped bytes with zeros. In general, for record files, lseek should only be directed to an absolute position that was returned by a previous valid call to lseek or to the beginning or end of a file. If a call to lseek does not satisfy these conditions, the results are unpredictable. ______________________________________________________ See also open, creat, dup, dup2, and fseek in this section. Return Values x The new file position. -1 Indicates that the file descriptor is undefined, or a seek was attempted before the beginning of the file. REF-353 lwait _________________________________________________________________ lwait Waits for I/O on a specific file to complete. Format #include int lwait (int fd); Argument fd A file descriptor corresponding to an open file. Description This function is used primarily to wait for completion of pending asynchronous I/O. Return Values 0 Indicates successful completion. -1 Indicates an error. REF-354 malloc _________________________________________________________________ malloc Allocates an area of memory. These functions are AST- reentrant. Format #include void *malloc (size_t size); Function Variants This function also has variants named _malloc32 and _ malloc64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument size The total number of bytes to be allocated. Description This function allocates a contiguous area of memory whose size, in bytes, is supplied as an argument. The space is not initialized. ________________________ Note ________________________ The malloc routines call the system routine LIB$VM_ MALLOC. Because LIB$VM_MALLOC is designed as a general purpose routine to allocate memory, it is called upon in a wide array of scenarios to allocate and reallocate blocks efficiently. The most common usage is the management of smaller blocks of memory, and the most important aspect of memory allocation under these circumstances is efficiency. LIB$VM_MALLOC makes use of its own free space to satisfy requests, once the heap storage is consumed by splitting large blocks and merging adjacent blocks. Memory can still become fragmented, leaving unused REF-355 malloc blocks. Once heap storage is consumed, LIB$VM_ MALLOC manages its own free space and merged blocks to satisfy requests, but varying sizes of memory allocations can cause blocks to be left unused. Because LIB$VM_MALLOC cannot be made to satisfy all situations in the best possible manner, you should perform your own memory management if you have special memory usage needs. This assures the best use of memory for your particular application. The OpenVMS Programming Concepts Manual explains the several memory allocation routines that are available. They are grouped into 3 levels of hierarchy: 1. At the highest level are the RTL Heap Management Routines LIB$GET_VM and LIB$FREE_VM, which provide a mechanism for allocating and freeing blocks of memory of arbitrary size. Also at this level are the routines based on the concept of zones, such as LIB$CREATE_VM_ZONE, and so on. 2. At the next level are the RTL Page Management routines LIB$GET_VM_PAGE and LIB$FREE_VM_PAGE, which allocate a specified number of contiguous pages. 3. At the lowest level are the Memory Management System Services such as $CRETVA and $EXPREG that provide extensive control over address space allocation. Note that at this level, you must manage the allocation precisely. ______________________________________________________ Return Values x The address of the first byte, which is aligned on a quadword boundary. NULL Indicates that the function is unable to allocate enough memory. errno is set to ENOMEM. REF-356 mblen _________________________________________________________________ mblen Determines the number of bytes comprising a multibyte character. Format #include int mblen (const char *s, size_t n); Arguments s A pointer to the multibyte character. n The maximum number of bytes that comprise the multibyte character. Description If the character is n bytes or less, this function returns the number of bytes comprising the multibyte character pointed to by s. If the character is greater than n bytes, the function returns -1 to indicate an error. This function is affected by the LC_CTYPE category of the program's current locale. Return Values x The number of bytes that comprise the multibyte character, if the next n or fewer bytes form a valid character. 0 If s is NULL or a pointer to the NULL character. -1 Indicates an error occurred. The function sets errno to EILSEQ - Invalid character detected. REF-357 mbrlen _________________________________________________________________ mbrlen Determines the number of bytes comprising a multibyte character. Format #include size_t mbrlen (const char *s, size_t n, mbstate_t *ps); Arguments s A pointer to a multibyte character. n The maximum number of bytes that comprise the multibyte character. ps A pointer to the mbstate_t object. If a NULL pointer is specified, the function uses its internal mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. Description The mbrlen function is equivalent to the call: mbrtowc(NULL, s, n, ps != NULL ? ps : &internal) Where internal is the mbstate_t object for the mbrlen function. If the multibyte character pointed to by s is of n bytes or less, the function returns the number of bytes comprising the character (including any shift sequences). If either an encoding error occurs or the next n bytes contribute to an incomplete but potentially valid multibyte character, the function returns -1 or -2, respectively. See also mbrtowc in this section. REF-358 mbrlen Return Values x The number of bytes comprising the multibyte character. 0 Indicates that s is a NULL pointer or a pointer to a null byte. -1 Indicates an encoding error, in which case the next n or fewer bytes do not contribute to a complete and valid multibyte character. errno is set to EILSEQ; the conversion state is undefined. -2 Indicates an incomplete but potentially valid multibyte character (all n bytes have been processed). REF-359 mbrtowc _________________________________________________________________ mbrtowc Converts a multibyte character to its wide-character representation. Format #include size_t mbrtowc (wchar_t *pwc, const char *s, size_t n, mbstate_t *ps); Arguments pwc A pointer to the resulting wide-character code. s A pointer to a multibyte character. n The maximum number of bytes that comprise the multibyte character. ps A pointer to the mbstate_t object. If a NULL pointer is specified, the function uses its internal mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. Description If s is a NULL pointer, mbrtowc is equivalent to the call: mbrtowc(NULL, "", 1, ps) In this case, the values of pwc and n are ignored. If s is not a NULL pointer, mbrtowc inspects at most n bytes beginning with the byte pointed to by s to determine the number of bytes needed to complete the next multibyte character (including any shift sequences). REF-360 mbrtowc If the function determines that the next multibyte character is completed, it determines the value of the corresponding wide character and then, if pwc is not a NULL pointer, stores that value in the object pointed to by pwc. If the corresponding wide character is the null wide character, the resulting state described is the initial conversion state. If mbrtowc is called as a counting function, which means that pwc is a NULL pointer and s is neither a NULL pointer nor a pointer to a null byte, the value of the internal mbstate_t object will remain unchanged. Return Values x The number of bytes comprising the multibyte character. 0 The next n or fewer bytes complete the multibyte character that corresponds to the null wide character (which is the value stored if pwc is not a NULL pointer). The wide-character code corresponding to a null byte is zero. -1 Indicates an encoding error. The next n or fewer bytes do not contribute to a complete and valid multibyte character. errno is set to EILSEQ. The conversion state is undefined. -2 Indicates an incomplete but potentially valid multibyte character (all n bytes have been processed). REF-361 mbstowcs _________________________________________________________________ mbstowcs Converts a sequence of multibyte characters into a sequence of corresponding wide-character codes. Format #include size_t mbstowcs (wchar_t *pwcs, const char *s, size_t n); Arguments pwcs A pointer to the array containing the resulting sequence of wide-character codes. s A pointer to the array of multibyte characters. n The maximum number of wide-character codes that can be stored in the array pointed to by pwcs. Description This function converts a sequence of multibyte characters from the array pointed to by s to a sequence of wide- character codes that are stored into the array pointed to by pwcs, up to a maximum of n codes. This function is affected by the LC_CTYPE category of the program's current locale. If copying takes place between objects that overlap, the behavior is undefined. REF-362 mbstowcs Return Values x The number of array elements modified or required, not included any terminating zero code. The array will not be zero-terminated if the value returned is n. If pwcs is the NULL pointer, mbstowcs returns the number of elements required for the wide-character array. (size_t) -1 Indicates that an error occurred. The function sets errno to EILSEQ - Invalid character detected. REF-363 mbtowc _________________________________________________________________ mbtowc Converts a multibyte character to its wide-character equivalent. Format #include int mbtowc (wchar_t *pwc, const char *s, size_t n); Arguments pwc A pointer to the resulting wide-character code. s A pointer to the multibyte character. n The maximum number of bytes that comprise the next multibyte character. Description If the character is n or fewer bytes, this function converts the multibyte character pointed to by s to its wide-character equivalent. If the character is invalid or greater than n bytes, the function returns -1 to indicate an error. If pwc is a NULL pointer and s is not a null pointer, the function determines the number of bytes that constitute the multibyte character pointed to by s (regardless of the value of n). This function is affected by the LC_CTYPE category of the program's current locale. REF-364 mbtowc Return Values x The number of bytes that comprise the valid character pointed to by s. 0 If s is either a NULL pointer or a pointer to the null byte. -1 Indicates an error occurred. The function sets errno to EILSEQ - Invalid character detected. REF-365 mbsinit _________________________________________________________________ mbsinit Determines whether an mbstate_t object decribes an initial conversion state. Format #include int mbsinit (const mbstate_t *ps); Arguments ps A pointer to the mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. Description If ps is not a NULL pointer, this function determines whether the mbstate_t object pointed to by ps describes an initial conversion state. A zero mbstate_t object always describes an initial conversion state. Return Values nonzero The ps argument is a NULL pointer, or the mbstate_t object pointed to by ps describes an initial conversion state. 0 The mbstate_t object pointed to by ps does not describe an initial conversion state. REF-366 mbsrtowcs _________________________________________________________________ mbsrtowcs Converts a sequence of multibyte characters to a sequence of corresponding wide-character codes. Format #include size_t mbsrtowcs (wchar_t *dst, const char **src, size_t len, mbstate_t *ps); Function Variants This function also has variants named _mbsrtowcs32 and _ mbsrtowcs64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dst A pointer to the destination array containing the resulting sequence of wide-character codes. src An address of the pointer to an array containing a sequence of multibyte characters to be converted. len The maximum number of wide character codes that can be stored in the array pointed to by dst. ps A pointer to the mbstate_t object. If a NULL pointer is specified, the function uses its internal mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. REF-367 mbsrtowcs Description This function converts a sequence of multibyte characters, beginning in the conversion state described by the object pointed to by ps, from the array indirectly pointed to by src, into a sequence of corresponding wide characters. If dst is not a NULL pointer, the converted characters are stored into the array pointed to by dst. Conversion continues up to and including a terminating null character, which is also stored. Conversion stops earlier for one of the following reasons: o A sequence of bytes is encountered that does not form a valid multibyte character. o If dst is not a NULL pointer, when len codes have been stored into the array pointed to by dst. If dst is not a NULL pointer, the pointer object pointed to by src is assigned either a NULL pointer, (if the conversion stopped because of reaching a terminating null wide character) or the address just beyond the last multibyte character converted (if any). If conversion stopped because of reaching a terminating null wide character, the resulting state described is the initial conversion state. Return Values n The number of multibyte characters successfully converted, sequence, not including the terminating null (if any). -1 Indicates an error. A sequence of bytes that do not form valid multibyte character was encountered. errno is set to EILSEQ; the conversion state is undefined. REF-368 memccpy _________________________________________________________________ memccpy Copies characters sequentially between strings in memory areas. Format #include void *memccpy (void *dest, void *source, int c, size_t n); Function Variants This function also has variants named _memccpy32 and _ memccpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest A pointer to the location of a destination string. source A pointer to the location of a source string. c A character that you want to search for. n The number of charcter you want to copy. Description This function operates on strings in memory areas. A memory area is a group of contiguous characters bound by a count and not terminated by a null character. The function does not check for overflow of the receiving memory area. The memccpy function is defined in the header file. The memccpy function sequentially copies characters from the location pointed to by source into the location pointed to by dest until one of the following occurs: REF-369 memccpy o The character specified by c (converted to an unsigned char) is copied. o The number of characters specified by n is copied. Return Values x A pointer to the character following the character specified by c in the string pointed to by dest. NULL Indicates an error. The character c is not found after scanning n characters in the string. REF-370 memchr _________________________________________________________________ memchr Locates the first occurrence of the specified byte within the initial size bytes of a given object. Format #include void *memchr (const void *s1, int c, size_t size); Function Variants This function also has variants named _memchr32 and _ memchr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s1 A pointer to the object to be searched. c The byte value to be located. size The length of the object to be searched. If size is zero, memchr returns NULL. Description Unlike strchr, the memchr function does not stop when it encounters a null character. Return Values pointer A pointer to the first occurrence of the byte. NULL Indicates that the specified byte does not occur in the object. REF-371 memcmp _________________________________________________________________ memcmp Compares two objects, byte by byte. The compare operation starts with the first byte in each object. Format #include int memcmp (const void *s1, const void *s2, size_t size); Arguments s1 A pointer to the first object. s2 A pointer to the second object. size The length of the objects to be compared. If size is zero, the two objects are considered equal. Description This function uses native byte comparison. The sign of the value returned is determined by the sign of the difference between the values of the first pair of unlike bytes in the objects being compared. Unlike the strcmp function, the memcmp function does not stop when a null character is encountered. Return Value x An integer less than, equal to, or greater than 0, depending on whether the lexical value of the first object is less than, equal to, or greater than that of the second object. REF-372 memcpy _________________________________________________________________ memcpy Copies a specified number of bytes from one object to another. Format #include void *memcpy (void *dest, const void *source, size_t size); Function Variants This function also has variants named _memcpy32 and _ memcpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest A pointer to the destination object. source A pointer to the source object. size The length of the object to be copied. Description This function copies size bytes from the object pointed to by source to the object pointed to by dest; it does not check for the overflow of the receiving memory area (dest). Unlike the strcpy function, the memcpy function does not stop when a null character is encountered. Return Value x The value of dest. REF-373 memmove _________________________________________________________________ memmove Copies a specified number of bytes from one object to another. Format #include void *memmove (void *dest, const void *source, size_t size); Function Variants This function also has variants named _memmove32 and _ memmove64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest A pointer to the destination object. source A pointer to the source object. size The length of the object to be copied. Description In Compaq C for OpenVMS Systems, memmove and memcpy perform the same function. Programs that require portability should use memmove if the area pointed at by dest could overlap the area pointed at by source. Return Value x The value of dest. REF-374 memmove Example #include #include main() { char pdest[14] = "hello there"; char *psource = "you are there"; memmove(pdest, psource, 7); printf("%s\n", pdest); } This example produces the following output: you are there REF-375 memset _________________________________________________________________ memset Sets a specified number of bytes in a given object to a given value. Format #include void *memset (void *s, int value, size_t size); Function Variants This function also has variants named _memset32 and _ memset64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s An array pointer. value The value to be placed in s. size The number of bytes to be placed in s. Description This function copies value (converted to an unsigned char) into each of the first size characters of the object pointed to by s. This function returns s. It does not check for the overflow of the receiving memory area pointed to by s. Return Value x The value of s. REF-376 mkdir _________________________________________________________________ mkdir Creates a directory. Format #include int mkdir (const char *dir_spec, mode_t mode); (ISO POSIX-1) int mkdir (const char *dir_spec, mode_t mode, . . . ); (DEC C Extension) Arguments dir_spec A valid OpenVMS or UNIX style directory specification that may contain a device name. For example: DBA0:[BAY.WINDOWS] /* OpenVMS */ /dba0/bay/windows /* UNIX style */ This specification cannot contain a node name, file name, file extension, file version, or a wildcard character. The same restriction applies to the UNIX style directory specifications. For more information about the restrictions on UNIX style specifications, see Chapter 1. mode A file protection. See the chmod function in this section for information about the specific file protections. The file protection of the new directory is derived from the mode argument, the process's file protection mask (see the umask function), and the parent-directory default protections. In a manner consistent with the OpenVMS behavior for creating directories, mkdir never applies delete access to the directory. An application that needs to set delete access should use an explicit call to chmod to set write permission. REF-377 mkdir See the Description section of this function for more information about how the file protection is set for the newly created directory. . . . Represents the following optional arguments. These arguments have fixed position in the argument list, and cannot be arbitrarily placed. unsigned int uic The user identification code (UIC) that identifies the owner of the created directory. If this argument is 0, the Compaq C RTL gives the created directory the UIC of the parent directory. If this argument is not specified, the Compaq C RTL gives the created directory your UIC. This optional argument is specific to the Compaq C RTL and is not portable. unsigned short max_versions The maximum number of file versions to be retained in the created directory. The system automatically purges the directory keeping, at most, max_versions number of every file. If this argument is 0, the Compaq C RTL does not place a limit on the maximum number of file versions. If this argument is not specified, the Compaq C RTL gives the created directory the default version limit of the parent directory. This optional argument is specific to the Compaq C RTL and is not portable. unsigned short r_v_number The volume (device) on which to place the created directory if the device is part of a volume set. If this argument is not specified, the Compaq C RTL arbitrarily places the created directory within the volume set. This optional argument is specific to the Compaq C RTL and is not portable. REF-378 mkdir Description If dir_spec specifies a path that includes directories, which do not exist, intermediate directories are also created. This differs from the behavior of the UNIX system where these intermediate directories must exist and will not be created. If you do not specify any optional arguments, the Compaq C RTL gives the directory your UIC and the default version limit of the parent directory, and arbitrarily places the directory within the volume set. You cannot get the default behavior for the uic or max_versions arguments if you specify any arguments after them. ________________________ Note ________________________ The way to create files with OpenVMS RMS default protections using the UNIX system-call functions umask, mkdir, creat, and open is to call mkdir, creat, and open with a file-protection mode argument of 0777 in a program that never specifically calls umask. These default protections include correctly establishing protections based on ACLs, previous versions of files, and so on. In programs that do vfork/exec calls, the new process image inherits whether umask has ever been called or not from the calling process image. The umask setting and whether the umask function has ever been called are both inherited attributes. ______________________________________________________ The file protection supplied by the mode argument is modified by the process's file protection mask in such a way that the file protection for the new directory is set to the bitwise AND of the mode argument and the complement of the file protection mask. Default file protections are supplied to the new directory from the parent-directory such that if a protection value bit in the new directory is zero, then the value of this bit is inherited from the parent-directory. However, bits in the parent directory's file protection that indicate REF-379 mkdir delete access do not cause corresponding bits to be set in the new directory's file protection. Return Values 0 Indicates success. -1 Indicates failure. Examples 1. umask (0002); /* turn world write access off */ mkdir ("sys$disk:[.parentdir.childdir]", 0222); /* turn write access on */ Parent directory file protection: System:RWD, Owner:RWD, Group:R, World:R The file protection derived from the combination of the mode argument and the file protection mask set by umask is (0222) & ~(0002), which is 0220. When the parent directory defaults are applied to this protection, the protection for the new directory becomes: File protection: System:RWD, Owner:RWD, Group:RWD, World:R 2. umask (0000); mkdir ("sys$disk:[.parentdir.childdir]", 0444); /* turn read access on */ Parent directory file protection: System:RWD, Owner:RWD, Group:RWD, World:RWD The file protection derived from the combination of the mode argument and the file protection mask set by umask is (0444) & ~(0000) which is 0444. When the parent directory defaults are applied to this protection, the protection for the new directory is: File protection: System:RW, Owner:RW, Group:RW, World:RW Note that delete access is not inherited. REF-380 mkstemp _________________________________________________________________ mkstemp Constructs a unique filename. Format #include int mkstemp (char *template); Arguments template A pointer to a string that is replaced with a unique filename. The string in the template argument must be a filename with six trailing Xs. Description This function replaces the six trailing Xs of the string pointed to by template with a unique set of characters, and returns a file descriptor for the file open for reading and writing. The string pointed to by template should look like a file name with six trailing X's. The mkstemp function replaces each X with a character from the portable file-name character set, making sure not to duplicate an existing file name. If the string pointed to by template does not contain six trailing Xs, -1 is returned. Return Values x An open file descriptor. -1 Indicates an error. (The string pointed to by template does not contain six trailing Xs.) REF-381 mktemp _________________________________________________________________ mktemp Creates a unique file name from a template. Format #include char *mktemp (char *template); Function Variants This function also has variants named _mktemp32 and _ mktemp64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument template A pointer to a buffer containing a user-defined template. You supply the template in the form, namXXXXXX. The six trailing Xs are replaced by a unique series of characters. You may supply the first three characters. Because the template argument is overwritten, do not specify a string literal (const object). Description The use of mktemp is not recommended for new applications. See the tmpnam and mkstemp functions for the preferable alternatives. Return Value x A pointer to the template, with the template modified to contain the created file name. If this value is a pointer to a null string, it indicates that a unique file name cannot be created. REF-382 mktime _________________________________________________________________ mktime Converts a local-time structure into time since the Epoch. Format #include time_t mktime (struct tm *timeptr); Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Argument timeptr A pointer to the local time structure. Description This function converts the local-time structure, pointed to by timeptr, to a time in seconds since the Epoch in the same manner as the values returned by the time function. If the local time cannot be encoded, then mktime returns the value (time_t)(-1). The time_t type is defined in the header file as follows: typedef unsigned long int time_t; Local time-zone information is set as if mktime called tzset. If the tm_isdst field in the local-time structure pointed to by timeptr is positive, mktime initially presumes that Daylight Savings Time (DST) is in effect for the specified time. If tm_isdst is 0, mktime initially presumes that DST is not in effect. REF-383 mktime If tm_isdst is negative, mktime attempts to determine whether or not DST is in effect for the specified time. Return Values x The specified calendar time encoded as a value of type time_t. (time_t)(-1) If the local time cannot be encoded. Be aware that a return value of (time_t)(-1) can also represent the valid date: Sun Feb 7 06:28:15 2106. REF-384 mmap _________________________________________________________________ mmap Maps file system object into virtual memory. Format #include #include void mmap (void *addr, size_t len, int prot, int flags, int filedes, off_t off); (X/Open, POSIX-1) void mmap (void *addr, size_t len, int prot, int flags, int filedes, off_t off ...); (DEC C Extension) Function Variants This function also has variants named _mmap32 and _mmap64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Arguments addr The starting address of the new region (truncated to a page boundary). len The length in bytes of the new region (rounded up to a page boundary). prot Access permission, as defined in the header file. Specify either PROT_NONE, PROT_READ, or PROT_WRITE. flags Attributes of the mapped region as the results of a bitwise-inclusive OR operation on any combination of the following: o MAP_FILE or MAP_ANONYMOUS o MAP_VARIABLE or MAP_FIXED REF-385 mmap o MAP_SHARED or MAP_PRIVATE filedes The file that you want to map to the new mapped file region returned by the open function. off The offset into the file that gets mapped at address addr. . . . An optional integer specifying additional flags for the SYS$CRMPSC system service for MAP_SHARED. This optional argument (Compaq C Extension) of the mmap function was introduced in OpenVMS Version 7.2. Description This function creates a new mapped file region, a new private region, or a new shared memory region. Your application must ensure correct synchronization when using mmap in conjunction with any other file access method, such as read and write, and standard input/output. Before calling mmap, the calling application must also ensure that all bytes in the range [off, off+len] are written to the file (using the fsync function, for example). If this requirement is not met, mmap fails with errno set to ENXIO (No such device or address). The addr and len arguments specify the requested starting address and length in bytes for the new region. The address is a multiple of the page size returned by sysconf(_SC_ PAGE_SIZE). If the len argument is not a multiple of the page size returned by sysconf(_SC_PAGE_SIZE), then the result of any reference to an address between the end of the region and the end of the page containing the end of the region is undefined. The flags argument specifies attributes of the mapped region. Values for flags are constructed by a bitwise- inclusive OR operation on the flags from the following list of symbolic names defined in the header file: REF-386 mmap MAP_FILE Create a mapped file region. MAP_ANONYMOUS Create an unnamed memory region. MAP_VARIABLE Place region at the computed address. MAP_FIXED Place region at fixed address. MAP_SHARED Share changes. MAP_PRIVATE Changes are private. The MAP_FILE and MAP_ANONYMOUS flags control whether the region you want to map is a mapped file region or an anonymous shared memory region. One of these flags must be selected. If MAP_FILE is set in the flags argument: o A new mapped file region is created, mapping the file associated with the filedes argument. o The off argument specifies the file byte offset where the mapping starts. This offset must be a multiple of the page size returned by sysconf(_SC_PAGE_SIZE). o If the end of the mapped file region is beyond the end of the file, the result of any reference to an address in the mapped file region corresponding to an offset beyond the end of the file is unspecified. If MAP_ANONYMOUS is set in the flags argument: o A new memory region is created and initialized to all zeros. o If the filedes argument is not -1, the mmap function fails. The new region is placed at the requested address if the requested address is not null and it is possible to place the region at this address. When the requested address is null or the region cannot be placed at the requested address, the MAP_VARIABLE and MAP_FIXED flags control the placement of the region. One of these flags must be selected. REF-387 mmap If MAP_VARIABLE is set in the flags argument: o If the requested address is null or if it is not possible for the system to place the region at the requested address, the region is placed at an address selected by the system. If MAP_FIXED is set in the flags argument: o If the requested address is not null, the mmap function succeeds even if the requested address is already part of another region. (If the address is within an existing region, the effect on the pages within that region and within the area of the overlap produced by the two regions is the same as if they were unmapped. In other words, whatever is mapped between addr and addr + len is unmapped.) o If the requested address is null and MAP_FIXED is specified, the results are undefined. The MAP_PRIVATE and MAP_SHARED flags control the visibility of modifications to the mapped file or shared memory region. One of these flags must be selected. If MAP_SHARED is set in the flags argument: o If the region is a mapped region, modifications to the region are visible to other processes that mapped the same region using MAP_SHARED. o If the region is a mapped file region, modifications to the region are written to the file. (Note that the modifications are not immediately written to the file because of buffer cache delay; that is, the write to the file does not occur until there is a need to reuse the buffer cache. If the modifications must be written to the file immediately, use the msync function to ensure that this is done.) If MAP_PRIVATE is set in the flags argument: o Modifications to the mapped region by the calling process are not visible to other processes that mapped the same region using either MAP_PRIVATE or MAP_SHARED. o Modifications to the mapped region by the calling process are not written to the file. REF-388 mmap It is unspecified whether modifications by processes that mapped the region using MAP_SHARED are visible to other processes that mapped the same region using MAP_PRIVATE. The prot argument specifies access permissions for the mapped region. Specify one of the following: PROT_NONE No access PROT_READ Read-only PROT_WRITE Read/Write access After the successful completion of the mmap function, you can close the filedes argument without effect on the mapped region or on the contents of the mapped file. Each mapped region creates a file reference, similar to an open file descriptor, that prevents the file data from being deallocated. ________________________ Note ________________________ The following rules apply to OpenVMS specific file references: o Because of the additional file reference, if filedes is not opened for file sharing, mmap reopens it with file sharing enabled. o The additional file reference that remains for mapped regions implies that a later open, fopen, or create call to the file that is mapped must specify file sharing. ______________________________________________________ Modifications made to the file using the write function are visible to mapped regions, and modifications to a mapped region are visible with the read function. ________________________ Note ________________________ Beginning with OpenVMS Version 7.2, while processing a MAP_SHARED request, the mmap function constructs the flags argument of the SYS$CRMPSC service as a bitwise inclusive OR of those bits it sets by itself to fulfill the MAP_SHARED request and those bits specified by the caller in the optional argument. REF-389 mmap By default, for MAP_SHARED the mmap function creates a temporary group global section. The optional mmap argument provides the caller with direct access to the features of the SYS$CRMPSC system service. Using the optional argument, the caller can create, for example, a system global section (SEC$M_SYSGBL bit) or permanent global section (SEC$M_PERM bit). For example, to create a system permanent global section, the caller can specify (SEC$M_SYSGBL | SEC$M_PERM) in the optional argument. The mmap function does not check or set any privileges. So it is the responsibility of the caller to set appropriate privileges, such as SYSGBL privilege for SEC$M_SYSGBL, and PRMGBL for SEC$M_PERM, before calling mmap with the optional argument. ______________________________________________________ See also read, write, open, fopen, creat, and sysconf in this section. Return Values x The address where the mapping is placed. REF-390 mmap MAP_FAILED Indicates an error; errno is set to one of the following values: o EACCES - The file referred to by filedes is not open for read access, or the file is not open for write access and PROT_WRITE was set for a MAP_SHARED mapping operation. o EBADF - The filedes argument is not a valid file descriptor. o EINVAL -The flags or prot argument is invalid, or the addr argument or off argument is not a multiple of the page size returned by sysconf(_SC_PAGE_SIZE). Or MAP_ ANONYMOUS was specified in flags and filedes is not -1. o ENODEV - The file descriptor filedes refers to an object that cannot be mapped, such as a terminal. o ENOMEM - There is not enough address space to map len bytes. o ENXIO - The addresses specified by the range [off, off + len] are invalid for filedes. o EFAULT - The addr argument is an invalid address. REF-391 modf _________________________________________________________________ modf Returns the positive fractional part of its first argument and assigns the integer part, expressed as an object of type double, to the object whose address is specified by the second argument. Format #include double modf (double value, double *iptr); Arguments value Must be an object of type double. iptr A pointer to an object of type double. REF-392 [w]move _________________________________________________________________ [w]move Change the current cursor position on the specified window to the coordinates (y,x). The move function acts on the stdscr window. Format #include int move (int y, int x); int wmove (WINDOW *win, int y, int x); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. Description For more information, see the scrollok function in this section. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. REF-393 mprotect _________________________________________________________________ mprotect Modifies access protections of memory mapping. Format #include int mprotect (void *addr, size_t len, int prot); Arguments addr The address of the region that you want to modify. len The length in bytes of the region that you want to modify. prot Access permission, as defined in the header file. Specify either PROT_NONE, PROT_READ, or PROT_WRITE. Description This function modifies the access protection of a mapped file or shared memory region. The addr and len arguments specify the address and length in bytes of the region that you want to modify. The len argument must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE). If len is not a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE), the length of the region is rounded up to the next multiple of the page size. The prot argument specifies access permissions for the mapped region. Specify one of the following: PROT_NONE No access PROT_READ Read-only PROT_WRITE Read/Write access REF-394 mprotect The mprotect function does not modify the access permission of any region that lies outside of the specified region, except that the effect on addresses between the end of the region, and the end of the page containing the end of the region, is unspecified. If the mprotect function fails under a condition other than that specified by EINVAL, the access protection of some of the pages in the range [addr, addr + len] can change. Suppose the error occurs on some page at an addr2; mprotect can modify protections of all whole pages in the range [addr, addr2]. See also sysconf in this section. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EACCESS - The prot argument specifies a protection that conflicts with the access permission set for the underlying file. o EINVAL - The prot argument is invalid, or the addr argument is not a multiple of the page size as returned by sysconf(_SC_PAGE_ SIZE). o EFAULT - The range [addr, addr + len] includes an invalid address. REF-395 mrand48 _________________________________________________________________ mrand48 Generates uniformly distributed pseudorandom number sequences. Returns 48-bit signed long integers. Format #include long int mrand48 (void); Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. It returns signed long integers uniformly distributed over the range of y values such that -231 y < 231. Before you call the mrand48 function, use either srand48, seed48, or lcong48 to initialize the random number generator. You must initialize the mrand48 function prior to invoking it, because it stores the last 48- bit Xi generated into an internal buffer. (Although it is not recommended, constant default initializer values are supplied automatically if the drand48, lrand48, or mrand48 functions are called without first calling an initialization function.) The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 REF-396 mrand48 The values returned by the mrand48 function is computed by first generating the next 48-bit Xi in the sequence. Then the appropriate bits, according to the type of returned data item, are copied from the high-order (most significant) bits of Xi and transformed into the returned value. See also drand48, lrand48, lcong48, seed48, and srand48 in this section. Return Values n Returns signed long integers uniformly distributed over the range -231 y < 231. REF-397 msync _________________________________________________________________ msync Synchronizes a mapped file. Format #include int msync (void *addr, size_t len, int flags); Arguments addr The address of the region that you want to synchronize. len The length in bytes of the region that you want to synchronize. flags One of the following symbolic constants defined in the header file: MS_SYNC Synchronous cache flush MS_ASYNC Asynchronous cache flush MS_INVALIDATE Invalidate cashed pages Description This function controls the caching operations of a mapped file region. Use msync to: o Ensure that modified pages in the region transfer to the underlying storage device of the file. o Control the visibility of modifications with respect to file system operations. The addr and len arguments specify the region to be synchronized. The len argument must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE); otherwise, the length of the region is rounded up to the next multiple of the page size. REF-398 msync If the flags argument is set to: ___________________________________________________________ flags_Argument_____Then_the_msync_Function...______________ MS_SYNC Does not return until the system completes all I/O operations. MS_ASYNC Returns after the system schedules all I/O operations. MS_INVALIDATE Invalidates all cached copies of the pages. The operating system must obtain new copies of the pages from the file system the next time the application ___________________references_them.________________________ After a successful call to the msync function with the flags argument set to: o MS_SYNC - All previous modifications to the mapped region are visible to processes using the read argument. Previous modifications to the file using the write function are lost. o MS_INVALIDATE - All previous modifications to the file using the write function are visible to the mapped region. Previous direct modifications to the mapped region are lost. See also read, write, and sysconf in this section. Return Values 0 Indicates success. REF-399 msync -1 Indicates an error; errno is set to one of the following values: o EIO - An I/O error occurred while reading from or writing to the file system. o ENOMEM - The range specified by [addr, addr + len] is invalid for a process' address space, or the range specifies one or more unmapped pages. o EINVAL - The addr argument is not a multiple of the page size as returned by sysconf(_SC_PAGE_ SIZE). o EFAULT - The range [addr, addr + len] includes an invalid address. REF-400 munmap _________________________________________________________________ munmap Unmaps a mapped region. Format #include int munmap (void *addr, size_t len); Arguments addr The address of the region that you want to unmap. len The length in bytes of that region the you want to unmap. Description This function unmaps a mapped file or shared memory region. The addr and len arguments specify the address and length in bytes, respectively, of the region to be unmapped. The len argument must be a multiple of the page size as returned by sysconf(_SC_PAGE_SIZE); otherwise, the length of the region is rounded up to the next multiple of the page size. The result of using an address that lies in an unmapped region and not in any subsequently mapped region is undefined. See also sysconf in this section. Return Values 0 Indicates success. REF-401 munmap -1 Indicates an error; errno is set to one of the following values: o ENIVAL - The addr argument is not a multiple of the page size as returned by sysconf(_SC_PAGE_ SIZE). o EFAULT - The range [addr, addr + len] includes an invalid address. REF-402 mv[w]addch _________________________________________________________________ mv[w]addch Move the cursor to coordinates (y,x) and add a character to the specified window. Format #include int mvaddch (int y, int x, char ch); int mvwaddch (WINDOW *win, int y, int x, char ch); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. ch If this argument is a new-line character (\n), the mvaddch and mvwaddch functions clear the line to the end, and move the cursor to the next line at the same x coordinate. A carriage return (\r) moves the cursor to the beginning of the specified line. A tab (\t) moves the cursor to the next tabstop within the window. Description This routine performs the same function as mvwaddch, but on the stdscr window. When mvwaddch is used on a subwindow, it writes the character onto the underlying window as well. REF-403 mv[w]addch Return Values OK Indicates success. ERR Indicates that writing the character would cause the screen to scroll illegally. For more information, see the scrollok function in this section. REF-404 mv[w]addstr _________________________________________________________________ mv[w]addstr Move the cursor to coordinates (y,x) and add the specified string, to which str points, to the specified window. Format #include int mvaddstr (int y, int x, char *str); int mvwaddstr (WINDOW *win, int y, int x, char *str); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. str A pointer to the character string. Description This routine performs the same function as mvwaddstr, but on the stdscr window. When mvwaddstr is used on a subwindow, the string is written onto the underlying window as well. Return Values OK Indicates success. REF-405 mv[w]addstr ERR Indicates that the function causes the screen to scroll illegally, but it places as much of the string onto the window as possible. For more information, see the scrollok function in this section. REF-406 mvcur _________________________________________________________________ mvcur Moves the terminal's cursor from (lasty,lastx) to (newy,newx). Format #include int mvcur (int lasty, int lastx, int newy, int newx); Arguments lasty The cursor position. lastx The cursor position. newy The resulting cursor position. newx The resulting cursor position. Description In Compaq C for OpenVMS Systems, mvcur and move perform the same function. See also move in this section. Return Values OK Indicates success. ERR Indicates that moving the window put part or all of the window off the edge of the terminal screen. The terminal screen remains unaltered. REF-407 mv[w]delch _________________________________________________________________ mv[w]delch Move the cursor to coordinates (y,x) and delete the character on the specified window. The mvdelch function acts on the stdscr window. Format #include int mvdelch (int y, int x); int mvwdelch (WINDOW *win, int y, int x); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. Description Each of the following characters on the same line shifts to the left, and the last character becomes blank. Return Values OK Indicates success. ERR Indicates that deleting the character would cause the screen to scroll illegally. For more information, see the scrollok function in this section. REF-408 mv[w]getch _________________________________________________________________ mv[w]getch Move the cursor to coordinates (y,x), get a character from the terminal screen, and echo it on the specified window. The mvgetch function acts on the stdscr window. Format #include int mvgetch (int y, int x); int mvwgetch (WINDOW *win, int y, int x); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. Description The mvgetch and mvwgetch functions refresh the specified window before fetching the character. Return Values x The returned character. ERR Indicates that the function causes the screen to scroll illegally. For more information, see the scrollok function in this section. REF-409 mv[w]getstr _________________________________________________________________ mv[w]getstr Move the cursor to coordinates (y,x), get a string from the terminal screen, store it in the variable str which must be large enough to contain the string, and echo it on the specified window. The mvgetstr function acts on the stdscr window. Format #include int mvgetstr (int y, int x, char *str); int mvwgetstr (WINDOW *win, int y, int x, char *str); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. str The string that is displayed. Description The mvgetstr and mvwgetstr functions strip the new-line terminator (\n) from the string. Return Values OK Indicates success. ERR Indicates that the function causes the screen to scroll illegally. REF-410 mv[w]inch _________________________________________________________________ mv[w]inch Move the cursor to coordinates (y,x) and return the character on the specified window without making changes to the window. The mvinch function acts on the stdscr window. Format #include int mvinch (int y, int x); int mvwinch (WINDOW *win, int y, int x); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. Return Values x The returned character. ERR Indicates an input error. REF-411 mv[w]insch _________________________________________________________________ mv[w]insch Move the cursor to coordinates (y,x) and insert the character ch into the specified window. The mvinsch function acts on the stdscr window. Format #include int mvinsch (int y, int x, char ch); int mvwinsch (WINDOW *win, int y, int x, char ch); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. ch The character to be inserted at the window's coordinates. Description After the character is inserted, each character on the line shifts to the right, and the last character on the line is deleted. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. For more information, see the scrollok function in this section. REF-412 mv[w]insstr _________________________________________________________________ mv[w]insstr Move the cursor to coordinates (y,x) and insert the specified string into the specified window. The mvinsstr function acts on the stdscr window. Format #include int mvinsstr (int y, int x, char *str); int mvwinsstr (WINDOW *win, int y, int x, char *str); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. str The string that is displayed. Description Each character after the string shifts to the right, and the last character disappears. The mvinsstr and mvwinsstr functions are specific to Compaq C for OpenVMS Systems and are not portable. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally. For more information, see the scrollok function in this section. REF-413 mvwin _________________________________________________________________ mvwin Moves the starting position of the window to the specified (y,x) coordinates. Format #include mvwin (WINDOW *win, int y, int x); Arguments win A pointer to the window. y A window coordinate. x A window coordinate. Description When moving subwindows, the mvwin function does not rewrite the contents of the subwindow on the underlying window at the new position. If you write anything to the subwindow after the move, the function also writes to the underlying window. Return Values OK Indicates success. ERR Indicates that moving the window put part or all of the window off the edge of the terminal screen. The terminal screen remains unaltered. REF-414 newwin _________________________________________________________________ newwin Creates a new window with numlines lines and numcols columns starting at the coordinates (begin_y,begin_x) on the terminal screen. Format #include WINDOW *newwin (int numlines, int numcols, int begin_y, int begin_x); Arguments numlines If it is 0, the newwin function sets that dimension to LINES (begin_y). To get a new window of dimensions LINES by COLS, use the following line: newwin (0, 0, 0, 0) numcols If it is 0, the newwin function sets that dimension to COLS (begin_x). Thus, to get a new window of dimensions LINES by COLS, use the following line: newwin (0, 0, 0, 0) begin_y A window coordinate. begin_x A window coordinate. Return Values x The address of the allocated window. ERR Indicates an error. REF-415 nice _________________________________________________________________ nice Increases or decreases process priority relative to the process current priority by the amount of the argument. This function is nonreentrant. Format #include int nice (int increment); Argument increment As a positive argument, decreases priority; as a negative argument, increases priority. Issuing nice(0) restores the base priority. The resulting priority cannot be less than 1, or greater than the process's base priority. If it is, the nice function quietly does nothing. Description When a process calls the vfork function, the resulting child inherits the parent's priority. See also vfork in this section. Return Values 0 Indicates success. -1 Indicates failure. REF-416 [no]nl _________________________________________________________________ [no]nl The nl and nonl functions are provided only for UNIX software compatibility and have no function in the OpenVMS environment. Format #include void nl (void); void nonl (void); REF-417 nl_langinfo _________________________________________________________________ nl_langinfo Returns a pointer to a string that contains information obtained from the program's current locale. Format #include char *nl_langinfo (nl_item item); Arguments item The name of a constant that specifies the information required. These constants are defined in . The following constants are valid: ___________________________________________________________ Constant_______Category_______Description__________________ D_T_FMT LC_TIME String for formatting date and time D_FMT LC_TIME String for formatting date T_FMT LC_TIME String for formatting time T_FMT_AMPM LC_TIME Time format with AM/PM string AM_STR LC_TIME String that represents AM in 12-hour clock notation PM_STR LC_TIME String that represents PM in 12-hour clock notation DAY_1 LC_TIME The name of the first day of the week . . . DAY_7 LC_TIME The name of the seventh day of the week ABDAY_1 LC_TIME The abbreviated name of the first day of the week . . . REF-418 nl_langinfo ___________________________________________________________ Constant_______Category_______Description__________________ ABDAY_7 LC_TIME The abbreviated name of the seventh day of the week MON_1 LC_TIME The name of the first month in the year . . . MON_12 LC_TIME The name of the twelfth month in the year ABMON_1 LC_TIME The abbreviated name of the first month in the year . . . ABMON_12 LC_TIME The abbreviated name of the twelfth month in the year ERA LC_TIME Era description strings ERA_D_FMT LC_TIME Era date format string ERA_T_FMT LC_TIME Era time format ERA_D_T_FMT LC_TIME Era date and time format ALT_DIGITS LC_TIME Alternative symbols for digits RADIXCHAR LC_NUMERIC The radix character THOUSEP LC_NUMERIC The character used to separate groups of digits in non-monetary values YESEXP LC_MESSAGES The expression for affirmative responses to yes/no questions NOEXP LC_MESSAGES The expression for negative responses to yes/no questions REF-419 nl_langinfo ___________________________________________________________ Constant_______Category_______Description__________________ CRNCYSTR LC_MONETARY The currency symbol. It is preceded by one of the following: o A minus (-) if the symbol is to appear before the value o A plus (+) if the symbol is to appear after the value o A period (.) if the symbol replaces the radix character CODESET________LC_CTYPE_______Codeset_name_________________ Description If the current locale does not have language information defined, the function returns information from the C locale. The program should not modify the string returned by the function. This string might be overwritten by subsequent calls to nl_langinfo. If the setlocale function is called after a call to nl_ langinfo, then the pointer returned by the previous call to nl_langinfo will be unspecified. In this case, the nl_ langinfo function should be called again. Return Values x Pointer to the string containing the requested information. If item is invalid, the function returns an empty string. REF-420 nl_langinfo Example #include #include #include /* This test sets up the British English locale, and then inquires on the */ /* data and time format, first day of the week, and abbreviated first */ /* day of the week. */ #include #include int main() { char *return_val; char *nl_ptr; /* set the locale, with user supplied locale name */ return_val = setlocale(LC_ALL, "en_gb.iso8859-1"); if (return_val == NULL) { printf("ERROR : The locale is unknown"); exit(1); } printf("+------------------------------------------- ----------+\n"); /* Get the date and time format from the locale. */ printf("D_T_FMT = "); /* Compare the returned string from nl_ langinfo with an empty */ /* string. */ if (!strcmp((nl_ptr = (char *) nl_langinfo(D_T_ FMT)), "")) { /* The string returned was empty this could mean that either */ /* 1) The locale does not contain a value for this item */ /* 2) The value for this item is an empty string */ printf("nl_ langinfo returned an empty string\n"); } else { /* Display the date and time format */ REF-421 nl_langinfo printf("%s\n", nl_ptr); } /* Get the full name for the first day of the week from locale */ printf("DAY_1 = "); /* Compare the returned string from nl_ langinfo with an empty */ /* string. */ if (!strcmp((nl_ptr = (char *) nl_langinfo(DAY_ 1)), "")) { /* The string returned was empty this could mean that either */ /* 1) The locale does not contain a value for the first day of */ /* the week */ /* 2) The value for the first day of the week is an empty string */ printf("nl_ langinfo returned an empty string\n"); } else { /* Display the full name of the first day of the week */ printf("%s\n", nl_ptr); } /* Get the abbreviated name for the first day of the week from locale */ printf("ABDAY_1 = "); /* Compare the returned string from nl_ langinfo with an empty */ /* string. */ if (!strcmp((nl_ptr = (char *) nl_langinfo(ABDAY_ 1)), "")) { /* The string returned was empty this could mean that either */ /* 1) The locale does not contain a value for the first day of */ /* the week */ /* 2) The value for the first day of the week is an empty string */ printf("nl_ langinfo returned an empty string\n"); } else { /* Display the abbreviated name of the first day of the week */ REF-422 nl_langinfo printf("%s\n", nl_ptr); } } Running the example program produces the following result: +-----------------------------------------------------+ D_T_FMT = %a %e %b %H:%M:%S %Y DAY_1 = Sunday ABDAY_1 = Sun REF-423 nrand48 _________________________________________________________________ nrand48 Generates uniformly distributed pseudorandom number sequences. Returns 48-bit signed long integers. Format #include long int nrand48 (unsigned short int xsubi[3]); Arguments xsubi An array of three short int that, when concatentated together, form a 48-bit integer. Description This function generates pseudorandom numbers using the linear congruential algorithm and 48-bit integer arithmetic. The nrand48 function returns nonnegative, long integers uniformly distributed over the range of y values, such that 0 y < 231. The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 The nrand48 function requires that the calling program pass an array as the xsubi argument, which for the first call must be initialized to the initial value of the pseudorandom number sequence. Unlike the drand48 function, it is not necessary to call an initialization function prior to the first call. REF-424 nrand48 By using different arguments, the nrand48 function allows separate modules of a large program to generate several independent sequences of pseudorandom numbers. For example, the sequence of numbers that one module generates does not depend upon how many times the functions are called by other modules. Return Values n Returns nonnegative, long integers over the range 0 y < 231. REF-425 open _________________________________________________________________ open Opens a file for reading, writing, or editing. It positions the file at its beginning (byte 0). Format #include int open (const char *file_spec, int flags, mode_t mode); (ANSI C) int open (const char *file_spec, int flags, . . . ); (DEC C Extension) Arguments file_spec A null-terminated character string containing a valid file specification. If you specify a directory in the file_spec and it is a search list that contains an error, Compaq C interprets it as a file open error. flags The following values are defined in the header file: O_RDONLY Open for reading only O_WRONLY Open for writing only O_RDWR Open for reading and writing O_NDELAY Open for asynchronous input O_APPEND Append on each write O_CREAT Create a file if it does not exist O_TRUNC Create a new version of this file O_EXCL Error if attempting to create existing file These flags are set using the bitwise OR operator (|) to separate specified flags. Opening a file with O_APPEND causes each write on the file to be appended to the end. (In contrast, with the VAX C RTL the behavior of files opened in append mode was to start at EOF and, thereafter, write at the current file position.) REF-426 open If O_TRUNC is specified and the file exists, open creates a new file by incrementing the version number by 1, leaving the old version in existence. If O_CREAT is set and the named file does not exist, the Compaq C RTL creates it with any attributes specified in the fourth and subsequent arguments ( . . . ). If O_EXCL is set with O_CREAT and the named file exists, the attempted open returns an error. mode An unsigned value that specifies the file-protection mode. The compiler performs a bitwise AND operation on the mode and the complement of the current protection mode. You can construct modes by using the bitwise OR operator (|) to separate specified modes. The modes are: 0400 OWNER:READ 0200 OWNER:WRITE 0100 OWNER:EXECUTE 0040 GROUP:READ 0020 GROUP:WRITE 0010 GROUP:EXECUTE 0004 WORLD:READ 0002 WORLD:WRITE 0001 WORLD:EXECUTE The system is given the same access privileges as the owner. A WRITE privilege also implies a DELETE privilege. . . . Optional file attribute arguments. The file attribute arguments are the same as those used in the creat function. For more information, see the creat function. REF-427 open Description If a version of the file exists, a new file created with open inherits certain attributes from the existing file unless those attributes are specified in the open call. The following attributes are inherited: record format, maximum record size, carriage control, and file protection. ________________________ Notes ________________________ o If you intend to do random writing to a file, the file must be opened for update by specifying a flags value of O_RDWR. o To create files with OpenVMS RMS default protections by using the UNIX system-call functions umask, mkdir, creat, and open, call mkdir, creat, and open with a file-protection mode argument of 0777 in a program that never specifically calls umask. These default protections include correctly establishing protections based on ACLs, previous versions of files, and so on. In programs that do vfork/exec calls, the new process image inherits whether umask has ever been called or not from the calling process image. The umask setting and whether the umask function has ever been called are both inherited attributes. ______________________________________________________ See also creat, read, write, close, dup, dup2, and lseek in this section. Return Values x A nonnegative file descriptor number. -1 Indicates that the file does not exist, that it is protected against reading or writing, or that it cannot be opened for another reason. REF-428 open Example #include #include #include main() { int file, stat; int flags; flags = O_ RDWR; /* Open for read and write, */ /* with user default file protection, */ /* with max fixed record size of 2048, */ /* and a block size of 2048 bytes. */ file = open("file.dat", flags, 0, "rfm=fix", "mrs=2048", "bls=2048"); if (file == -1) perror("OPEN error"), exit(1); close(file); } REF-429 opendir _________________________________________________________________ opendir Opens a specified directory. Format #include DIR *opendir (const char *dir_name); Arguments dir_name The name of the directory to be opened. Description This function opens the directory specifed by dir_name and associates a directory stream with it. The directory stream is positioned at the first entry. The type DIR, defined in the header file, represents a directory stream. A directory stream is an ordered sequence of all the directory entries in a particular directory. The opendir function also returns a pointer to identify the directory stream in subsequent operations. The NULL pointer is returned when the directory named by dir_name cannot be accessed, or when not enough memory is available to hold the entire stream. ________________________ Note ________________________ An open directory must always be closed with the closedir function to ensure that the next attempt to open that directory is successful. The opendir function should be used with readdir, closedir, and rewinddir to examine the contents of the directory. ______________________________________________________ REF-430 opendir Example See the program example in the description of closedir. Return Values x A pointer to an object of type DIR. NULL Indicates an error; errno is set to one of the following values: o EACCES - Search permission is denied for any component of dir_ name or read permission is denied for dir_name. o ENAMETOOLONG - The length of the dir_name string exceeds PATH_MAX, or a pathname component is longer than NAME_MAX. o ENOENT - The dir_name argument points to the name of a file that does not exist, or is an empty string. REF-431 overlay _________________________________________________________________ overlay Nondestructively superimposes win1 on win2. The function writes the contents of win1 that will fit onto win2 beginning at the starting coordinates of both windows. Blanks on win1 leave the contents of the corresponding space on win2 unaltered. The overlay function copies as much of a window's box as possible. Format #include int overlay (WINDOW *win1, WINDOW *win2); Arguments win1 A pointer to the window. win2 A pointer to the window. Return Values OK Indicates success. ERR Indicates an error. REF-432 overwrite _________________________________________________________________ overwrite Destructively writes the contents of win1 on win2. Format #include int overwrite (WINDOW *win1, WINDOW *win2); Arguments win1 A pointer to the window. win2 A pointer to the window. Description This function writes the contents of win1 that will fit onto win2 beginning at the starting coordinates of both windows. Blanks on win1 are written on win2 as blanks. This function copies as much of a window's box as possible. Return Values OK Indicates success. ERR Indicates failure. REF-433 pathconf _________________________________________________________________ pathconf Retrieves file implementation characteristics. Format #include long int pathconf (const char *path, int name); Arguments path The pathname of a file or directory. name The configuration attribute to query. If this attribute is not applicable to the file specified by the path argument, the pathconf function returns an error. Description This function allows an application to determine the characteristics of operations supported by the file system underlying the file named by path. Read, write, or execute permission of the named file is not required, but you must be able to search all directories in the path leading to the file. Symbolic values for the name argument are defined in the header file, as follows: _PC_LINK_MAX The maximum number of links to the file. If the path argument refers to a directory, the value returned applies to the directory itself. _PC_MAX_CANON The maximum number of bytes in a canonical input line. This is applicable only to terminal devices. _PC_MAX_INPUT The number of types allowed in an input queue. This is applicable only to terminal devices. REF-434 pathconf _PC_NAME_MAX Maximum number of bytes in a filename (not including a terminating null). The byte range value is between 13 and 255. This is applicable only to a directory file. The value returned applies to filenames within the directory. _PC_PATH_MAX Maximum number of bytes in a pathname (not including a terminating null). The value is never larger than 65,535. This is applicable only to a directory file. The value returned is the maximum length of a relative pathname when the specified directory is the working directory. _PC_PIPE_BUF Maximum number of bytes guaranteed to be written atomically. This is applicable only to a FIFO. The value returned applies to the referenced object. If the path argument refers to a directory, the value returned applies to any FIFO that exists or can be created within the directory. _PC_CHOWN_ This is applicable only to a directory RESTRICTED file. The value returned applies to any files (other than directories) that exist or can be created within the directory. _PC_NO_TRUNC Returns 1 if supplying a component name longer than allowed by NAME_MAX causes an error. Returns 0 (zero) if long component names are truncated. This is applicable only to a directory file. _PC_VDISABLE This is always 0 (zero); no disabling character is defined. This is applicable only to a terminal device. REF-435 pathconf Return Values x Resultant value of the configuration attribute specified in name. -1 Indicates an error; errno is set to one of the following values: o EACCES - Search permission is denied for a component of the path prefix. o EINVAL - The name argument specifies an unknown or inapplicable characteristic. o EFAULT - The path argument is an invalid address. o ENAMETOOLONG - The length of the path string exceeds PATH_MAX or a pathname component is longer than NAME_MAX. o ENOENT - The named file does not exist or the path argument points to an empty string. o ENOTDI - A component of the path prefix is not a directory. REF-436 pause _________________________________________________________________ pause Suspends the calling process until delivery of a signal whose action is either to execute a signal-catching function or to terminate the process. Format #include int pause (void); Description This function suspends the calling process until delivery of a signal whose action is either to execute a signal- catching function or to terminate the process. If the action is to terminate the process, pause does not return. If the action is to execute a signal-catching function, pause returns after the signal-catching function returns. Return Value Since the pause function suspends process execution indefinitely unless interrupted by a signal, there is no successful completion return value. -1 In cases where pause returns, the return value is -1, and errno is set to EINTR. REF-437 pclose _________________________________________________________________ pclose Closes a pipe to a process. Format #include int pclose (FILE *stream); Arguments stream A pointer to a FILE structure for an open pipe returned by a previous call to the popen function. Description This function closes a pipe between the calling program and a shell command to be executed. Use pclose to close any stream you have opened with popen. The pclose function waits for the associated process to end, and then returns the exit status of the command. See the description of waitpid for information on interpreting the return value. See also popen in this section. Return Values x Exit status of child. -1 Indicates an error. The stream argument is not associated with a popen function. errno is set to one of the following: o ECHILD - cannot obtain the status of the child process. REF-438 perror _________________________________________________________________ perror Writes a short error message to stderr describing the current value of errno. Format #include void perror (const char *str); Argument str Usually the name of the program that caused the error. Description This function uses the error number in the external variable errno to retrieve the appropriate locale-dependent error message. The function writes out the message as follows: str (a user-supplied prefix to the error message), followed by a colon and a space, followed by the message itself, followed by a new-line character. See the description of errno in Chapter 4 for a list of possible errors. See also strerror in this section. Example #include #include main(argc, argv) int argc; char *argv[]; { FILE *fp; fp = fopen(argv[1], "r"); /* Open an input file. */ if (fp == NULL) { REF-439 perror /* If the fopen call failed, perror prints out a */ /* diagnostic: */ /* */ /* "open: " */ /* This error message provides a diagnostic explaining */ /* the cause of the failure. */ perror("open"); exit(EXIT_FAILURE); } else fclose(fd) ; } REF-440 pipe _________________________________________________________________ pipe Creates a temporary mailbox that can be used to read and write data between a parent and child process. The channels through which the processes communicate are called a pipe. Format #include int pipe (int array_fdscptr[2]); (ISO POSIX-1) int pipe (int array_fdscptr[2], . . . ); (DEC C Extension) Arguments array_fdscptr An array of file descriptors. A pipe is implemented as an array of file descriptors associated with a mailbox. These mailbox descriptors are special in that these are the only file descriptors which, when passed to the isapipe function, will return 1. The file descriptors are allocated in the following way: o The first available file descriptor is assigned to writing, and the next available file descriptor is assigned to reading. o The file descriptors are then placed in the array in reverse order; element 0 contains the file descriptor for reading, and element 1 contains the file descriptor for writing. . . . Represents two optional, positional arguments, flag and bufsize, which follow: flag An optional argument used as a bitmask. If either the O_NDELAY or O_NONBLOCK bit is set, the I/O operations to the mailbox through array_fdscptr file descriptors terminate immediately, rather than waiting for another process. REF-441 pipe If, for example, the O_NDELAY bit is set and the child issues a read request to the mailbox before the parent has put any data into it, the read terminates immediately with zero status. If neither the O_NDELAY nor O_NONBLOCK bit is set, the child will be waiting on the read until the parent writes any data into the mailbox. This is the default behavior if no flag argument is specified. The values of O_NDELAY and O_NONBLOCK are defined in the header file. Any other bits in the flag argument are ignored. You must specify this argument if the second optional, positional argument bufsize is specified. If the flag argument is needed only to allow specification of the bufsize argument, specify flag as zero. bufsize Optional argument of type int that specifies the size of the mailbox, in bytes. If you do not specify this argument, Compaq C for OpenVMS Systems creates a mailbox with a default size of 512 bytes. If you do specify this argument, be sure to precede it with a flag argument of 0. Description The mailbox used for the pipe is a temporary mailbox. The mailbox is not deleted until all processes that have open channels to that mailbox close those channels. The last process that closes a pipe writes a message to the mailbox, indicating the end-of-file. The mailbox is created by using the $CREMBX system service, specifying the following characteristics: o A maximum message length of 512 characters o A buffer quota of 512 characters o A protection mask granting all privileges to USER and GROUP and no privileges to SYSTEM or WORLD The buffer quota of 512 characters implies that you cannot write more than 512 characters to the mailbox before all or part of the mailbox is read. Since a mailbox record is slightly larger than the data part of the message that it contains, not all of the 512 characters can be used for REF-442 pipe message data. You can increase the size of the buffer by specifying an alternative size using the optional, third argument to the pipe function. A pipe under the OpenVMS system is a stream-oriented file with no carriage- control attributes. It is fully buffered by default in the Compaq C RTL. A mailbox used as a pipe is different than a mailbox created by the application. A mailbox created by the application defaults to a record-oriented file with carriage return, carriage control. Additionally, writing a zero-length record to a mailbox writes an EOF, as does each close of the mailbox. For a pipe, only the last close of a pipe writes an EOF. The pipe is created by the parent process before vfork and an exec function are called. By calling pipe first, the child inherits the open file descriptors for the pipe. You can then use the getname function to return the name of the mailbox associated with the pipe, if this information is desired. The mailbox name returned by getname has the format _MBAnnnn:, where nnnn is a unique number. Both the parent and the child need to know in advance which file descriptors will be allocated for the pipe. This information cannot be retrieved at run time. Therefore, it is important to understand how file descriptors are used in any Compaq C for OpenVMS program. For more information about file descriptors, see Chapter 2. File descriptors 0, 1, and 2 are open in a Compaq C for OpenVMS program for stdin (SYS$INPUT), stdout (SYS$OUTPUT), and stderr (SYS$ERROR), respectively. Therefore, if no other files are open when pipe is called, pipe assigns file descriptor 3 for writing and file descriptor 4 for reading. In the array returned by pipe, 4 is placed in element 0 and 3 is placed in element 1. If other files have been opened, pipe assigns the first available file descriptor for writing and the next available file descriptor for reading. In this case, the pipe does not necessarily use adjacent file descriptors. For example, assume that two files have been opened and assigned to file descriptors 3 and 4 and the first file is then closed. If pipe is called at this point, file descriptor 3 is assigned for writing and file descriptor REF-443 pipe 5 is assigned for reading. Element 0 of the array will contain 5 and element 1 will contain 3. In large applications that do large amounts of I/O, it gets more difficult to predict which file descriptors are going to be assigned to a pipe; and, unless the child knows which file descriptors are being used, it will not be able to read and write successfully from and to the pipe. One way to be sure that the correct file descriptors are being used is to use the following procedure: 1. Choose two descriptor numbers that will be known to both the parent and the child. The numbers should be high enough to account for any I/O that might be done before the pipe is created. 2. Call pipe in the parent at some point before calling an exec function. 3. In the parent, use dup2 to assign the file descriptors returned by pipe to the file descriptors you chose. This now reserves those file descriptors for the pipe; any subsequent I/O will not interfere with the pipe. You can read and write through the pipe using the UNIX I/O functions read and write, specifying the appropriate file descriptors. As an alternative, you can issue fdopen calls to associate file pointers with these file descriptors so that you can use the Standard I/O functions (fread and fwrite). Two separate file descriptors are used for reading from and writing to the pipe, but only one mailbox is used so some I/O synchronization is required. For example, assume that the parent writes a message to the pipe. If the parent is the first process to read from the pipe, then it will read its own message back as shown in Figure REF-1. REF-444 pipe Figure REF-1 Reading and Writing to a Pipe Return Values 0 Indicates success. -1 Indicates an error. REF-445 popen _________________________________________________________________ popen Initiates a pipe to a process. Format #include FILE *popen (const char *command, const char *type); Arguments command A pointer to a null-terminated string containing a shell command line. type A pointer to a null-terminated string containing an I/O mode. Because open files are shared, you can use a type r command as an input filter and a type w command as an output filter. Specify one of the following values for the type argument: o r - the calling program can read from the standard output of the command by reading from the returned file stream. o w - the calling program can write to the standard input of the command by writing to the returned file stream. Description This function creates a pipe between the calling program and a shell command awaiting execution. It returns a pointer to a FILE structure for the stream. ________________________ Note ________________________ When you use the popen function to invoke an output filter, beware of possible deadlock caused by output data remaining in the program buffer. You can avoid this by either using the setvbuf function to ensure that the output stream is unbuffered, or the fflush REF-446 popen function to ensure that all buffered data is flushed before calling the pclose function. ______________________________________________________ See also fflush, pclose, and setvbuf in this section. Return Values x A pointer to the FILE structure for the opened stream. NULL Indicates an error. Unable to create files or processes. REF-447 pow _________________________________________________________________ pow Returns the first argument raised to the power of the second argument. Format #include double pow (double base, double exp); Arguments base A value of type double that is to be raised to a power. exp The exponent to which the power base is to be raised. Description Both arguments must be double and the returned value is double. Return Values x The result of the first argument raised to the power of the second. 1.0 Indicates that the base is zero and the exponent is zero. HUGE_VAL Indicates that the result overflowed; errno is set to ERANGE. -HUGE_VAL Indicates that the base is zero and the exponent is negative; errno is set to EDOM. REF-448 pow Example #include #include #include main() { double x; errno = 0; x = pow(-3.0, 2.0); printf("%d, %f\n", errno, x); } This example program outputs the following: 0, 9.000000 REF-449 printf _________________________________________________________________ printf Performs formatted output from the standard output (stdout). See Chapter 2 for information on format specifiers. Format #include int printf (const char *format_spec, . . . ); Arguments format_spec Characters to be written literally to the output or converted as specified in the . . . arguments. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you may omit the output sources. Otherwise, the function call must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Excess output pointers, if any, are ignored. Return Values x The number of bytes written. Negative value Indicates that an output error occurred. The function sets errno. For a list of errno values set by this function, see fprintf in this section. REF-450 [w]printw _________________________________________________________________ [w]printw Perform a printf in the specified window, starting at the current position of the cursor. The printw function acts on the stdscr window. Format #include printw (char *format_spec, . . . ); int wprintw (WINDOW *win, char *format_spec, . . . ); Arguments win A pointer to the window. format_spec A pointer to the format specification string. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you may omit the output sources. Otherwise, the function call must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Excess output pointers, if any, are ignored. Description The formatting specification (format_spec) and the other arguments are identical to those used with the printf function. REF-451 [w]printw The printw and wprintw functions format and then print the resultant string to the window using the addstr function. For more information, see the printf and scrollok functions in this section. See Chapter 2 for information on format specifiers. Return Values OK Indicates success. ERR Indicates that the function makes the window scroll illegally. REF-452 putc _________________________________________________________________ putc The putc macro writes a single character to a specified file. Format #include int putc (int character, FILE *file_ptr); Arguments character An object of type int. file_ptr A file pointer. Description Since putc is a macro, a file pointer argument with side effects (for example, putc (ch, *f++)) might be evaluated incorrectly. In such a case, use the fputc function instead. See also fputc in this section. Return Values x The character written to the file. Indicates success. EOF Indicates output errors. REF-453 putchar _________________________________________________________________ putchar Writes a single character to the standard output (stdout) and returns the character. Format #include int putchar (int character); Argument character An object of type int. Description This function is identical to fputc (character, stdout). Return Values character Indicates success. EOF Indicates output errors. REF-454 putenv _________________________________________________________________ putenv Sets an environmental variable. Format #include int putenv (const char *string); Arguments string A pointer to a name=value string. Description This function sets the value of an environment variable by altering an existing variable or by creating a new one. The string argument points to a string of the form name=value, where name is the environment variable and value is the new value for it. The string pointed to by string becomes part of the environment, so altering the string changes the environment. When a new string-defining name is passed to putenv, the space used by string is no longer used. ________________________ Note ________________________ The putenv function manipulates the environment pointed to by the environ external variable, and can be used with getenv. However, the third argument to the main function (the environment pointer), is not changed. The putenv function uses the malloc function to enlarge the environment. A potential error is to call putenv with an automatic variable as the argument, then exit the calling function while string is still part of the environment. ______________________________________________________ REF-455 putenv Return Values 0 Indicates success. -1 Indicates an error. errno is set to ENOMEM-Not enough memory available to expand the environment list. Restriction This function cannot take a 64-bit address. See Section 1.8. REF-456 puts _________________________________________________________________ puts Writes a character string to the standard output (stdout) followed by a new-line character. Format #include int puts (const char *str); Argument str A pointer to a character string. Description This function does not copy the terminating null character to the output stream. Return Values Nonnegative value Indicates success. EOF Indicates output errors. REF-457 putw _________________________________________________________________ putw Writes characters to a specified file. Format #include int putw (int integer, FILE *file_ptr); Arguments integer An object of type int or long. file_ptr A file pointer. Description This function writes four characters to the output file as an int. No conversion is performed. Return Values integer Indicates success. EOF Indicates output errors. REF-458 putwc _________________________________________________________________ putwc Converts a wide character to its corresponding multibyte value, and writes the result to a specified file. Format #include wint_t putwc (wint_t wc, FILE *file_ptr); Arguments wc An object of type wint_t. file_ptr A file pointer. Description Since putwc might be implemented as a macro, a file pointer argument with side effects (for example putwc (wc, *f++)) might be evaluated incorrectly. In such a case, use the fputwc function instead. See also fputwc in this section. Return Values x The character written to the file. Indicates success. WEOF Indicates an output error. The function sets errno. For a list of the errno values set by this function, see fputwc in this section. REF-459 putwchar _________________________________________________________________ putwchar Writes a wide character to the standard output (stdout) and returns the character. Format #include wint_t putwchar (wint_t wc); Arguments wc An object of type wint_t. Description This function is identical to fputwc(wc, stdout). Return Values x The character written to the file. Indicates success. WEOF Indicates an output error. The function sets errno. For a list of the errno values set by this function, see fputwc in this section. REF-460 qabs, llabs (Alpha only) _________________________________________________________________ qabs, llabs (Alpha only) Returns the absolute value of an integer as an __int64. llabs is a synonym for qabs. Format #include __int64 qabs (__int64 j); __int64 llabs (__int64 j); Argument j A value of type __int64. REF-461 qdiv, lldiv (Alpha only) _________________________________________________________________ qdiv, lldiv (Alpha only) Returns the quotient and the remainder after the division of its arguments. lldiv is a synonym for qdiv. Format #include qdiv_t qdiv (__int64 numer, __int64 denom); lldiv_t lldiv (__int64 numer, __int64 denom); Arguments numer A numerator of type __int64. denom A denominator of type __int64. Description The types qdiv_t and lldiv_t are defined in the header file as follows: typedef struct { __int64 quot, rem; } qdiv_t, lldiv_t; REF-462 qsort _________________________________________________________________ qsort Sorts an array of objects in place. It implements the quick-sort algorithm. Format #include void qsort (void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void *)); Function Variants This function also has variants named _qsort32 and _qsort64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size- specific functions. Arguments base A pointer to the first member of the array. The pointer should be of type pointer-to-element and cast to type pointer-to-character. nmemb The number of objects in the array. size The size of an object, in bytes. compar A pointer to the comparison function. Description Two arguments are passed to the comparison function pointed to by compar. The two arguments point to the objects being compared. Depending on whether the first argument is less than, equal to, or greater than the second argument, the comparison function returns an integer less then, equal to, or greater than 0. REF-463 qsort The comparison function compar need not compare every byte, so arbitrary data might be contained in the objects in addition to the values being compared. The order in the output of two objects that compare as equal is unpredictable. REF-464 raise _________________________________________________________________ raise Generates a specified software signal. Generating a signal causes the action routine established by the signal, ssignal, or sigvec function to be invoked. Format #include int raise (int sig); (ANSI C) int raise (int sig[, int sigcode]); (DEC C Extension) Arguments sig The signal to be generated. sigcode An optional signal code, available only when not compiling in strict ANSI C mode. For example, signal SIGFPE-the arithmetic trap signal-has 10 different codes, each representing a different type of arithmetic trap. The signal codes can be represented by mnemonics or numbers. The arithmetic trap codes are represented by the numbers 1 to 10; the SIGILL codes are represented by the numbers 0 to 2. The code values are defined in the header file. See Tables 4-4 and 4-5 for a list of signal mnemonics, codes, and corresponding OpenVMS exceptions. Description Calling this function has one of the following results: o If raise specifies a sig argument that is outside the range defined in the header file, then the raise function returns 0, and the errno variable is set to EINVAL. REF-465 raise o If signal, ssignal, or sigvec establishes SIG_DFL (default action) for the signal, then the functions do not return. The image is exited with the OpenVMS error code corresponding to the signal. o If signal, ssignal, or sigvec establishes SIG_IGN (ignore signal) as the action for the signal, then raise returns its argument, sig. o signal, ssignal, or sigvec must establish an action function for the signal. That function is called and its return value is returned by raise. See Chapter 4 for more information on signal processing. See also gsignal, signal, ssignal, and sigvec in this section. Return Values 0 If successful. nonzero If unsuccessful. REF-466 rand _________________________________________________________________ rand Returns pseudorandom numbers in the range 0 to 2[31] - 1. Format #include int rand (void); Description This function uses the following ANSI Standard algorithm to return a random number: static unsigned int next = 1; int rand(void) { next = next * 1103515245 + 12345; return (next & RAND_MAX); } See also srand in this section. For other random number algorithms, see random and all the *48 functions. REF-467 random _________________________________________________________________ random Generates pseudorandom numbers in a more random sequence. Format #include long int random (void); Description This function is a random number generator that has virtually the same calling sequence and initialization properties as the rand function, but produces sequences that are more random. The low 12 bits generated by rand go through a cyclic pattern. All bits generated by random are usable. For example, random() &1 produces a random binary value. The random function uses a nonlinear additive feedback random number generator employing a default state array size of 31 integers to return successive pseudorandom numbers in the range from 0 to ( 231)-1. The period of this random number generator is approximately 16*(( 231)- 1). The size of the state array determines the period of the random number generator. Increasing the state array size increases the period. With a full 256 bytes of state information, the period of the random number generator is greater than 269, and is sufficient for most purposes. Like the rand function, the random function produces by default a sequence of numbers that you can duplicate by calling the srandom function with a value of 1 as the seed. The srandom function, unlike the srand function, does not return the old seed because the amount of state information used is more than a single word. See also rand, srand, srandom, setstate, and initstate in this section. REF-468 random Return Values n A random number. REF-469 [no]raw _________________________________________________________________ [no]raw Raw mode only works with the Curses input routines [w]getch and [w]getstr. Raw mode is not supported with the Compaq C RTL emulation of UNIX I/O, Terminal I/O, or Standard I/O. Format #include raw() noraw() Description Raw mode reads are satisfied on one of two conditions: after a minimum number (5) of characters are input at the terminal or after waiting a fixed time (10 seconds) from receipt of any characters from the terminal. Example /* Example of standard and raw input in Curses package. */ #include main() { WINDOW *win1; char vert = '.', hor = '.', str[80]; /* Initialize standard screen, turn echo off. */ initscr(); noecho(); /* Define a user window. */ win1 = newwin(22, 78, 1, 1); leaveok(win1, TRUE); leaveok(stdscr, TRUE); box(stdscr, vert, hor); REF-470 [no]raw /* Reset the video, refresh(redraw) both windows. */ mvwaddstr(win1, 2, 2, "Test line terminated input"); wrefresh(win1); /* Do some input and output it. */ nocrmode(); wgetstr(win1, str); mvwaddstr(win1, 5, 5, str); mvwaddstr(win1, 7, 7, "Type something to clear screen"); wrefresh(win1); /* Get another character then delete the window. */ wgetch(win1); wclear(win1); mvwaddstr(win1, 2, 2, "Test raw input"); wrefresh(win1); /* Do some raw input 5 chars or timeout - and output it. */ raw(); getstr(str); noraw(); mvwaddstr(win1, 5, 5, str); mvwaddstr(win1, 7, 7, "Raw input completed"); wrefresh(win1); endwin(); } REF-471 read _________________________________________________________________ read Reads bytes from a file and places them in a buffer. Format #include ssize_t read (int file_desc, void *buffer, size_t nbytes); (ISO POSIX-1) int read (int file_desc, void *buffer, int nbytes); (Compatability) Arguments file_desc A file descriptor. The specified file descriptor must refer to a file currently opened for reading. buffer The address of contiguous storage in which the input data is placed. nbytes The maximum number of bytes involved in the read operation. Description This function returns the number of bytes read. The return value does not necessarily equal nbytes. For example, if the input is from a terminal, at most one line of characters is read. ________________________ Note ________________________ The read function does not span record boundaries in a record file and, therefore, reads at most one record. A separate read must be done for each record. ______________________________________________________ REF-472 read Return Values n The number of bytes read. -1 Indicates a read error, including physical input errors, illegal buffer addresses, protection violations, undefined file descriptors, and so forth. Example #include #include #include #include #include main() { int fd, i; char buf[10]; FILE *fp ; /* Temporary STDIO file */ /* Create a dummy data file */ if ((fp = fopen("test.txt", "w+")) == NULL) { perror("open"); exit(1); } fputs("XYZ\n",fp) ; fclose(fp) ; /* And now practice "read" */ if ((fd = open("test.txt", O_ RDWR, 0, "shr=upd")) <= 0) { perror("open"); exit(0); } /* Read 2 characters into buf. */ REF-473 read if ((i = read(fd, buf, 2)) < 0) { perror("read"); exit(0); } /* Print out what was read. */ if (i > 0) printf("buf='%c%c'\n", buf[0], buf[1]); close(fd); } REF-474 readdir, readdir_r _________________________________________________________________ readdir, readdir_r Find entries in a directory. Format #include struct dirent *readdir (DIR *dir_pointer); int readdir_r (DIR *dir_pointer, struct dirent *entry, struct dirent **result); Arguments dir_pointer A pointer to the dir structure of an open directory. entry A pointer to a dirent structure that will be initialized with the directory entry at the current position of the specified stream. result Upon successful completion, the location where a pointer to entry is stored. Description The readdir function returns a pointer to a structure representing the directory entry at the current position in the directory stream specified by dir_pointer, and positions the directory stream at the next entry. It returns a NULL pointer upon reaching the end of the directory stream. The dirent structure defined in the header file describes a directory entry. The type DIR defined in the header file represents a directory stream. A directory stream is an ordered sequence of all the directory entries in a particular directory. Directory entries represent files. You can remove files from or add files to a directory asynchronously to the operation of the readdir function. REF-475 readdir, readdir_r The pointer returned by the readdir function points to data that you can overwrite by another call to readdir on the same directory stream. This data is not overwritten by another call to readdir on a different directory stream. If a file is removed from or added to the directory after the most recent call to the opendir or rewinddir function, a subsequent call to the readdir function might not return an entry for that file. When it reaches the end of the directory, or when it detects an invalid seekdir operation, the readdir function returns the null value. An attempt to seek to an invalid location causes the readdir function to return the null value the next time it is called. A previous telldir function call returns the position. The readdir_r function is a reentrant version of readdir. In addition to dir_pointer, you must specify a pointer to a dirent structure in which the current directory entry of the specified stream is returned. If the operation is successful, readdir_r returns 0 and stores one of the two following pointers in result: o Pointer to entry if the entry was found o NULL pointer if the end of the directory stream was reached If an error occurred, an error value is returned that indicates the cause of the error. The storage pointed to by entry must be large enough for a dirent with an array of char d_name member containing at least NAME_MAX + 1 elements. Example See the description of closedir for an example. REF-476 readdir, readdir_r Return Values x On successful completion of readdir, a pointer to an object of type struct dirent. 0 Successful completion of readdir_r. x On error, an error value (readdir_r only). NULL An error occurred or end of the directory stream (readdir_r only). If an error occurred, errno is set to a value indicating the cause. REF-477 realloc _________________________________________________________________ realloc Changes the size of the area pointed to by the first argument to the number of bytes given by the second argument. These functions are AST-reentrant. Format #include void *realloc (void *ptr, size_t size); Function Variants This function also has variants named _realloc32 and _ realloc64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments ptr Points to an allocated area, or can be NULL. size The new size of the allocated area. Description If ptr is the NULL pointer, the behavior of the realloc function is identical to the malloc function. The contents of the area are unchanged up to the lesser of the old and new sizes. The ANSI C Standard states that "If the new size is larger than the old size, the value of the newly allocated portion of memory is indeterminate." For compatibility with old implementations, Compaq C initializes the newly allocated memory to 0. For efficiency, the previous actual allocation could have been larger than the requested size. If it was allocated with malloc, the value of the portion of memory between the previous requested allocation and the actual allocation is indeterminate. If it was allocated with calloc, that same REF-478 realloc memory was initialized to 0. If your application relies on realloc initializing memory to 0, then use calloc instead of malloc to perform the initial allocation. See also free, cfree, calloc, and malloc in this section. Return Values x The address of the area, quadword- aligned. The address is returned because the area may have to be moved to a new address to reallocate enough space. If the area was moved, the space previously occupied is freed. NULL Indicates that space cannot be reallocated (for example, if there is not enough room). REF-479 [w]refresh _________________________________________________________________ [w]refresh Repaint the specified window on the terminal screen. The refresh function acts on the stdscr window. Format #include int refresh(); int wrefresh (WINDOW *win); Argument win A pointer to the window. Description The result of this process is that the portion of the window not occluded by subwindows or other windows appears on the terminal screen. To see the entire occluded window on the terminal screen, call the touchwin function instead of the refresh or wrefresh function. See also touchwin in this section. Return Values OK Indicates success. ERR Indicates an error. REF-480 remove _________________________________________________________________ remove Deletes a file. Format #include int remove (const char *file_spec); Argument file_spec A pointer to the string that is an OpenVMS or a UNIX style file specification. The file specification can include a wildcard in its version number. So, for example, files of the form filename.txt;* can be deleted. Description If you specify a directory in the file name and it is a search list that contains an error, Compaq C for OpenVMS Systems interprets it as a file error. The remove and delete functions are functionally equivalent in the Compaq C RTL. See also delete in this section. Return Values 0 Indicates success. nonzero value Indicates failure. REF-481 rename _________________________________________________________________ rename Gives a new name to an existing file. Format #include int rename (const char *old_file_spec, const char *new_file_spec); Arguments old_file_spec A pointer to a string that is the existing name of the file to be renamed. new_file_spec A pointer to a string that is to be the new name of the file. Description If you try to rename a file that is currently open, the behavior is undefined. You cannot rename a file from one physical device to another. Both the old and new file specifications must reside on the same device. If the new_file_spec does not contain a file extension, the file extension of old_file_spec is used. To rename a file to have no file extension, new_file_spec must contain a period (.) For example, the following renames SYS$DISK:[]FILE.DAT to SYS$DISK:[]FILE1.DAT: rename("file.dat", "file1"); Whereas the following renames SYS$DISK:[]FILE.DAT to SYS$DISK:[]FILE1: rename(file.dat", "file1."); ________________________ Note ________________________ Because the rename function does special processing of the file extension, the caller must be careful when specifying the name of the renamed file in a call to REF-482 rename a C Run-Time Library function that accepts a filename argument. For example, after the following call to the rename function, the new file should be opened as fopen("bar.dat",...): rename("foo.dat", "bar"); ______________________________________________________ Return Values 0 Indicates success. nonzero value Indicates failure. REF-483 rewind _________________________________________________________________ rewind Sets the file to its beginning. Format #include void rewind (FILE *file_ptr); (ISO POSIX-1) int rewind (FILE *file_ptr); (DEC C Extension) Argument file_ptr A file pointer. Description The rewind function is equivalent to fseek (file_ptr, 0, SEEK_SET). You can use the rewind function with either record or stream files. A successful call to rewind clears the error indicator for the file. The ANSI C standard defines rewind as not returning a value; therefore, the function prototype for rewind is declared with a return type of void. However, since a rewind can fail, and since previous versions of the Compaq C RTL have declared rewind to return an int, the code for rewind does return 0 on success and -1 on failure. See also fseek in this section. REF-484 rewinddir _________________________________________________________________ rewinddir Resets the position of the specified directory stream to the beginning of a directory. Format #include void rewinddir (DIR *dir_pointer); Arguments dir_pointer A pointer to the dir structure of an open directory. Description This function resets the position of the specified directory stream to the beginning of the directory. It also causes the directory stream to refer to the current state of the corresonding directory, the same as using the opendir function. If the dir_pointer argument does not refer to a directory stream, the effect is undefined. The type DIR, defined in the header file, represents a directory stream. A directory stream is an ordered sequence of all the directory entries in a particular directory. Directory entries represent files. See also opendir in this section. REF-485 rindex _________________________________________________________________ rindex Searches for character in string. Format #include char *rindex (const char *s, int c); Function Variants This function also has variants named _rindex32 and _ rindex64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s The string to search. c The character to search for. Description This function is identical to the strchr function, and is provided for compatibility with some UNIX implementations. REF-486 rmdir _________________________________________________________________ rmdir Removes a directory file. Format #include int rmdir (const char *path); Arguments path A directory path name. Description This function removes a directory file whose name is specified in the path argument. The directory is removed only if it is empty. Restriction When using OpenVMS format names, the path argument must be in the form directory.dir. Return Values 0 Indicates success. -1 An error occurred; errno is set to indicate the error. REF-487 sbrk _________________________________________________________________ sbrk Determines the lowest virtual address that is not used with the program. Format #include void *sbrk (long int incr); Argument incr The number of bytes to add to the current break address. Description This function adds the number of bytes specified by its argument to the current break address and returns the old break address. When a program is executed, the break address is set to the highest location defined by the program and data storage areas. Consequently, sbrk is needed only by programs that have growing data areas. sbrk(0) returns the current break address. Return Values x The old break address. (void *)(-1) Indicates that the program is requesting too much memory. Restriction Unlike other C library implementations, the Compaq C RTL memory allocation functions (such as malloc) do not rely on brk or sbrk to manage the program heap space. Consequently, on OpenVMS systems, calling brk or sbrk can interfere with memory allocation routines. The brk and sbrk functions are provided only for compatibility purposes. REF-488 scanf _________________________________________________________________ scanf Performs formatted input from the standard input (stdin), interpreting it according to the format specification. See Chapter 2 for information on format specifiers. Format #include int scanf (const char *format_spec, . . . ); Arguments format_spec Characters to be taken literally from the input or converted and placed in memory at the specified input sources. For a list of conversion characters, see Chapter 2. . . . Optional expressions that are pointers to objects whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you can omit these input pointers. Otherwise, the function call must have at least as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. Return Values x The number of successfully matched and assigned input items. REF-489 scanf EOF Indicates that a read error occurred prior to any successful conversions.The function sets errno. For a list of errno values set by this function, see fscanf in this section. REF-490 [w]scanw _________________________________________________________________ [w]scanw Perform a scanf on the window. The scanw function acts on the stdscr window. Format #include int scanw (char *format_spec, . . . ); int wscanw (WINDOW *win, char *format_spec, . . . ); Arguments win A pointer to the window. format_spec A pointer to the format specification string. . . . Optional expressions that are pointers to objects whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you may omit these input pointers. Otherwise, the function call must have at least as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. Description The formatting specification (format_spec) and the other arguments are identical to those used with the scanf function. REF-491 [w]scanw The scanw and wscanw functions accept, format, and return a line of text from the terminal screen. For more information, see the scrollok and scanf functions in this section. Return Values OK Indicates success. ERR Indicates that the function makes the screen scroll illegally or that the scan was unsuccessful. REF-492 scroll _________________________________________________________________ scroll Moves all the lines on the window up one line. The top line scrolls off the window and the bottom line becomes blank. Format #include int scroll (WINDOW *win); Argument win A pointer to the window. Return Values OK Indicates success. ERR Indicates an error. REF-493 scrollok _________________________________________________________________ scrollok Sets the scroll flag for the specified window. Format #include scrollok (WINDOW *win, bool boolf); Arguments win A pointer to the window. boolf A Boolean TRUE or FALSE value. If boolf is FALSE, scrolling is not allowed. This is the default setting. The bool type is defined in the header file as follows: #define bool int REF-494 seed48 _________________________________________________________________ seed48 Initializes a 48-bit random number generator. Format #include unsigned short *seed48 (unsigned short seed_16v[3]); Arguments seed_16v An array of three unsigned short int that form a 48-bit seed value. Description The seed48 function initializes the random number generator. You can use this function in your program before calling the drand48, lrand48, or mrand48 functions. (Although it is not recommended practice, constant default initializer values are supplied automatically if you call drand48, lrand48, or mrand48 without calling an initialization function). The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n > 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 The initializer function seed48: o Sets the value of Xi to the 48-bit value specified in the array pointed to by seed_16v. o Returns a pointer to a 48-bit internal buffer that contains the previous value of Xi, used only by seed48. REF-495 seed48 The returned pointer allows you to restart the pseudorandom sequence at a given point. Use the pointer to copy the previous Xi value into a temporary array. To resume where the original sequence left off, you can call seed48 with a pointer to this array. See also drand48, lrand48, and mrand48 in this section. Return Values x A pointer to a 48-bit internal buffer. REF-496 seekdir _________________________________________________________________ seekdir Sets the position of a directory stream. Format #include void seekdir (DIR *dir_pointer, long int location); Arguments dir_pointer A pointer to the dir structure of an open directory. location The number of an entry relative to the start of the directory. Description This function sets the position of the next readdir operation on the directory stream specified by dir_ pointer to the position specified by location. The value of location should be returned from an earlier call to telldir. If the value of location was not returned by a call to the telldir function, or if there was an intervening call to the rewinddir function on this directory stream, the effect is unspecified. The type DIR, defined in the header file, represents a directory stream. A directory stream is an ordered sequence of all the directory entries in a particular directory. Directory entries represent files. You can remove files from or add files to a directory asynchronously to the operation of the readdir function. See readdir, rewinddir, and telldir in this section. REF-497 [w]setattr _________________________________________________________________ [w]setattr Activate the video display attribute attr within the window. The setattr function acts on the stdscr window. Format #include int setattr (int attr); int wsetattr (WINDOW *win, int attr); Arguments win A pointer to the window. attr One of a set of video display attributes, which are blinking, boldface, reverse video, and underlining, and are represented by the defined constants _BLINK, _BOLD, _ REVERSE, and _UNDERLINE, respectively. You can set multiple attributes by separating them with a bitwise OR operator (|) as follows: setattr(_BLINK | _UNDERLINE); Description The setattr and wsetattr functions are specific to Compaq C for OpenVMS Systems and are not portable. Return Values OK Indicates success. ERR Indicates an error. REF-498 setbuf _________________________________________________________________ setbuf Associates a new buffer with an input or output file and potentially modifies the buffering behavior. Format #include void setbuf (FILE *file_ptr, char *buffer); Arguments file_ptr A file pointer. buffer A pointer to a character array, or a NULL pointer. Description You can use this function after the specified file is opened but before any I/O operations are performed. If buffer is a NULL pointer, then the call is equivalent to a call to setvbuf with the same file_ptr, a NULL buffer pointer, a buffering type of _IONBF (no buffering), and a buffer size of 0. If buffer is not a NULL pointer, then the call is equivalent to a call to setvbuf with the same file_ptr, the same buffer pointer, a buffering type of _IOFBF, and a buffer size given by the value BUFSIZ (defined in ). You should, therefore, use BUFSIZ to allocate the buffer argument used in the call to setbuf. For example: REF-499 setbuf #include . . . char my_buf[BUFSIZ]; . . . setbuf(stdout, my_buf); . . . User programs must not depend on the contents of buffer once I/O has been performed on the stream. The Compaq C RTL might or might not use buffer for any given I/O operation. The setbuf function originally allowed programmers to substitute larger buffers in place of the system default buffers in obsolete versions of UNIX. The large default buffer sizes in modern implementations of C make the use of this function unnecessary most of the time. The setbuf function is retained in the ANSI C standard for compatibility with old programs. New programs should use setvbuf instead, because it allows the programmer to bind the buffer size at run time instead of compile time, and it returns a testable result value. REF-500 setenv _________________________________________________________________ setenv Inserts or resets the environment variable name in the current environment list. Format #include int setenv (const char *name, const char *value, int overwrite); Arguments name A variable name in the environment variable list. value The value for the environment variable. overwrite A value of 0 or 1 indicating whether to reset the environment variable, if it exists. Description This function inserts or resets the environment variable name in the current environment list. If the variable name does not exist in the list, it is inserted with the value argument. If the variable does exist, the overwrite argument is tested. When the overwrite argument value is: o 0 (zero) - then the variable is not reset. o 1 - then the variable is reset to value. Return Values 0 Indicates success. -1 Indicates an error. errno is set to ENOMEM-Not enough memory available to expand the environment list. REF-501 setgid _________________________________________________________________ setgid Implemented for program portability and serves no function. It returns 0 (to indicate success). Format #include int setgid (__gid_t group_number); (_DECC_V4_SOURCE) gid_t setgid (gid_t group_number); (not _DECC_V4_SOURCE) Argument group_number The group number. Description This function is implemented for program portability and serves no function. It returns 0 (to indicate success). __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. If the process has appropriate privileges, the setuid function sets the real user ID, effective user ID, and the saved set-user-ID to uid. If the process does not have appropriate privileges but uid is equal to the real user ID or to the saved set-user-ID, then the setuid function sets the effective user ID to uid. The real user ID and saved set-user-ID remain unchanged. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": REF-502 setgid $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ REF-503 setitimer _________________________________________________________________ setitimer Sets the value of interval timers. Format #include int setitimer (int which, struct itimerval *value, struct itimerval *ovalue); Arguments which The type of interval timer. The Compaq C RTL only supports ITIMER_REAL. value A pointer to an itimerval structure whose members specify a timer interval and the time left to the end of the interval. ovalue A pointer to an itimerval structure whose members specify a current timer interval and the time left to the end of the interval. Description This function sets the timer specified by which to the value specified by value, returning the previous value of the timer if ovalue is nonzero. A timer value is defined by the itimerval structure: struct itimerval { struct timeval it_interval; struct timeval it_value; }; REF-504 setitimer The value of the itimerval structure members are: as follows ___________________________________________________________ itimerval Member Value_________________Meaning______________________________ it_interval = 0 Disables a timer after its next expiration (Assumes it_value is nonzero). it_interval = Specifies a value used in reloading nonzero it_value when the timer expires. it_value = 0 Disables a timer. it_value = nonzero Indicates the time to the next timer ______________________expiration.__________________________ Time values smaller than the resolution of the system clock are rounded up to this resolution. The getitimer function provides one interval timer, defined in the header file as ITIMER_REAL. This timer decrements in real time. When the timer expires, it delivers a SIGALARM signal. ________________________ Note ________________________ The interaction between setitimer and any of alarm, sleep, or usleep is unspecified. ______________________________________________________ Return Values 0 Indicates success. -1 An error occurred; errno is set to indicate the error. REF-505 setjmp _________________________________________________________________ setjmp Provides a way to transfer control from a nested series of function invocations back to a predefined point without returning normally. It does not use a series of return statements. The setjmp function saves the context of the calling function in an environment buffer. Format #include int setjmp (jmp_buf env); Argument env The environment buffer, which must be an array of integers long enough to hold the register context of the calling function. The type jmp_buf is defined in the header file. The contents of the general-purpose registers, including the program counter (PC), are stored in the buffer. Description When setjmp is first called, it returns the value 0. If longjmp is then called, naming the same environment as the call to setjmp, control is returned to the setjmp call as if it had returned normally a second time. The return value of setjmp in this second return is the value supplied by you in the longjmp call. To preserve the true value of setjmp, the function calling setjmp must not be called again until the associated longjmp is called. The setjmp function preserves the hardware general purpose registers, and the longjmp function restores them. After a longjmp, all variables have their values as of the time of the longjmp except for local automatic variables not marked volatile. These variables have indeterminate values. REF-506 setjmp The setjmp and longjmp functions rely on the OpenVMS condition-handling facility to effect a nonlocal goto with a signal handler. The longjmp function is implemented by generating a Compaq C RTL specified signal that allows the OpenVMS condition-handling facility to unwind back to the desired destination. The Compaq C RTL must be in control of signal handling for any Compaq C image. For Compaq C to be in control of signal handling, you must establish all exception handlers through a call to the VAXC$ESTABLISH function. See Section 4.2.5 and the VAXC$ESTABLISH function in this section for more information. ________________________ Note ________________________ There are Alpha specific, non-standard decc$setjmp and decc$fast_longjmp functions. To use these non-standard functions instead of the standard ones, a program must be compiled with __FAST_SETJMP or __UNIX_SETJMP macros defined. Unlike the standard longjmp function, the decc$fast_ longjmp function does not convert its second argument from 0 to 1. After a call to decc$fast_longjmp, a corresponding setjmp function returns with the exact value of the second argument specified in the decc$fast_longjmp call. ______________________________________________________ Restrictions You cannot invoke the longjmp function from an OpenVMS condition handler. However, you may invoke longjmp from a signal handler that has been established for any signal supported by the Compaq C RTL, subject to the following nesting restrictions: o The longjmp function will not work if you invoke it from nested signal handlers. The result of the longjmp function, when invoked from a signal handler that has been entered as a result of an exception generated in another signal handler, is undefined. REF-507 setjmp o Do not invoke the setjmp function from a signal handler unless the associated longjmp is to be issued before the handling of that signal is completed. o Do not invoke the longjmp function from within an exit handler (established with atexit or SYS$DCLEXH). Exit handlers are invoked after image tear-down, so the destination address of the longjmp no longer exists. o Invoking longjmp from within a signal handler to return to the main thread of execution might leave your program in an inconsistent state. Possible side effects include the inability to perform I/O or to receive any more UNIX signals. Use siglongjmp instead. Return Values See the Description section. REF-508 setlocale _________________________________________________________________ setlocale Selects the appropriate portion of the program's locale as specified by the category and locale arguments. You can use this function to change or query one category or the program's entire current locale. Format #include char *setlocale (int category, const char *locale); Arguments category The name of the category. Specify LC_ALL to change or query the entire locale. Other valid category names are: o LC_COLLATE o LC_CTYPE o LC_MESSAGES o LC_MONETARY o LC_NUMERIC o LC_TIME locale Pointer to a string that specifies the locale. Description This function sets or queries the appropriate portion of the program's locale as specified by the category and locale arguments. Specifying LC_ALL for the category argument names the entire locale; specifying the other values name only a portion of the program's locale. The locale argument points to a character string that identifies the locale to be used. This argument can be one of the following: o Name of the public locale REF-509 setlocale Specifies the public locale in the following format: language_country.codeset[@modifier] The function searches for the public locale binary file in the location defined by the logical name SYS$I18N_LOCALE. The file type defaults to .LOCALE. The period (.) and at-sign (@) characters in the name are replaced by an underscore (_). For example: If the specified name is "zh_CN.dechanzi@radical", the function searches for the SYS$I18N_LOCALE:ZH_CN_DECHANZI_RADICAL.LOCALE binary locale file. o A file specification Specifies the binary locale file. It can be any valid file specification. If either the device or directory is omitted, the function first applies the current caller's device and directory as defaults for any missing component. If the file not found, the function applies the device and directory defined by the SYS$I18N_LOCALE logical name as defaults. The file type defaults to .LOCALE. No wildcards are allowed. The binary locale file cannot reside on a remote node. o "C" Specifies the C locale. If a program does not call setlocale, the C locale is the default. o "POSIX" This is the same as the C locale. o "" Specifies that the locale is initialized from the setting of the international environment logical names. The function checks the following logical names in the order shown until it finds a logical that is defined: 1. LC_ALL REF-510 setlocale 2. Logical names corresponding to the category. For example, if LC_NUMERIC is specified as the category, then the first logical name that setlocale checks is LC_NUMERIC. 3. LANG 4. SYS$LC_ALL 5. The system default for the category, which is defined by the SYS$LC_* logical names. For example, the default for the LC_NUMERIC category is defined by the SYS$LC_NUMERIC logical name. 6. SYS$LANG If none of the logical names is defined, the C locale is used as the default. The SYS$LC_* logical names are set up at the system startup time. Like the locale argument, the equivalence name of the international environment logical name can be either the name of the public locale or the file specification. The setlocale function treats this equivalence name as if it were specified as the locale argument. o NULL Causes setlocale to query the current locale. The function returns a pointer to a string describing the portion of the program's locale associated with category. Specifying the LC_ALL category returns the string describing the entire locale. The locale is not changed. o The string returned from the previous call to setlocale Causes the function to restore the portion of the program's locale associated with category. If the string contains the description of the entire locale, the part of the string corresponding to category is used. If the string describes the portion of the program's locale for a single category, this locale is used. For example, this means that you can use the string returned from the call setlocale with the LC_COLLATE category to set the same locale for the LC_MESSAGES category. REF-511 setlocale If the specified locale is available, then setlocale returns a pointer to the string that describes the portion of the program's locale associated with category. For the LC_ALL category, the returned string describes the entire program's locale. If an error occurs, a NULL pointer is returned and the program's locale is not changed. Subsequent calls to setlocale overwrite the returned string. If that part of the locale needs to be restored, the program should save the string. The calling program should make no assumptions about the format or length of the returned string. Return Values x Pointer to a string describing the locale. NULL Indicates an error occurred; errno is set. Example #include #include #include /* This program calls setlocale() three times. The second call */ /* is for a nonexistent locale. The third call is for an */ /* existing file that is not a locale file. */ main() { char *ret_str; errno = 0; printf("setlocale (LC_ALL, \"POSIX\")"); ret_str = (char *) setlocale(LC_ALL, "POSIX"); if (ret_str == NULL) perror("setlocale error"); else printf(" call was succesfull\n"); REF-512 setlocale errno = 0; printf("\n\nsetlocale (LC_ALL, \"junk.junk_ codeset\")"); ret_str = (char *) setlocale(LC_ALL, "junk.junk_ codeset"); if (ret_str == NULL) perror(" returned error"); else printf(" call was succesfull\n"); errno = 0; printf("\n\nsetlocale (LC_ ALL, \"sys$login:login.com\")"); ret_str = (char *) setlocale(LC_ ALL, "sys$login:login.com"); if (ret_str == NULL) perror(" returned error"); else printf(" call was succesfull\n"); } Running the example program produces the following result: setlocale (LC_ALL, "POSIX") call was succesfull setlocale (LC_ALL, "junk.junk_codeset") returned error: no such file or directory setlocale (LC_ALL, "sys$login:login.com") returned error: non-translatable vms error code: 0x35C07C %c-f-localebad, not a locale file REF-513 setstate _________________________________________________________________ setstate Restarts, and changes random number generators. Format char *setstate (char *state;) Arguments state Points to the array of state information. Description This function handles restarting and changing random number generators. Once you initialize a state, the setstate function allows rapid switching between state arrays. The array defined by state is used for further random number generation until the initstate function is called or the setstate function is called again. The setstate function returns a pointer to the previous state array. After initialization, you can restart a state array at a different point in one of two ways: o Use the initstate function, with the desired seed, state array, and size of the array. o Use the setstate function, with the desired state, followed by the srandom function with the desired seed. The advantage of using both functions is that you do not have to save the state array size once you initialize it. See also initstate, srandom, and random, in this section. REF-514 setstate Return Values x A pointer to the previous state array information. 0 Indicates an error. The state information is damaged. Further specified in the following errno value: o EINVAL-The state argument is invalid. REF-515 setuid _________________________________________________________________ setuid Implemented for program portability and serves no function. It returns 0 (to indicate success). Format #include int setuid (__uid_t member_number); (_DECC_V4_SOURCE) uid_t setuid (uid_t member_number); (not _DECC_V4_SOURCE) Argument member_number The member number. Description This function is implemented for program portability only and serves no function. It returns 0 to indicate success. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, this function has been enhanced to take advantage of the new OpenVMS support for POSIX-style user, group, and session IDs available on a version of OpenVMS Alpha after Version 7.3. The new functionality, based on PERSONA VMS services, is the default on those versions of OpenVMS Alpha where the underlying operating system support is available. If the process has appropriate privileges, the setuid function sets the real user ID, effective user ID, and the saved set-user-ID to uid. If the process does not have appropriate privileges but uid is equal to the real user ID or to the saved set-user-ID, then the setuid function sets the effective user ID to uid. The real user ID and saved set-user-ID remain unchanged. To request the old behavior, define the DECC$GETJPI_ BASED_UID logical name to "ENABLE": REF-516 setuid $ DEFINE DECC$GETJPI_BASED_UID ENABLE ______________________________________________________ REF-517 setvbuf _________________________________________________________________ setvbuf Associates a buffer with an input or output file and potentially modifies the buffering behavior. Format #include int setvbuf (FILE *file_ptr, char *buffer, int type, size_t size); Arguments file_ptr A pointer to a file. buffer A pointer to a character array, or a NULL pointer. type The buffering type. Use one of the following values defined in : _IONBF, _IOFBF, _IOLBF. size The number of bytes to be used in buffer by the Compaq C RTL for buffering this file. The buffer size must be a minimum of 8192 bytes and a maximum of 32767 bytes. Description You can use this function after the file is opened but before any I/O operations are performed. The ANSI C standard defines the following types of file buffering. In unbuffered I/O, each I/O operation is performed immediately. Output characters or lines are written to the output device before control is returned to the program. Input characters or lines are sent directly to the program without read-ahead by the Compaq C RTL. REF-518 setvbuf In line-buffered I/O, characters are buffered in an area of memory until a new-line character is seen, at which point the appropriate RMS routine is called to transmit the entire buffer. Line buffering is more efficient than unbuffered I/O since it reduces the system overhead, but it delays the availability of the data to the user or disk on output. In fully buffered I/O, characters are buffered in an area of memory until the buffer is full, regardless of the presence of break characters. Full buffering is more efficient than line buffering or unbuffered I/O, but it delays the availability of output data even longer than line buffering. Use the values _IONBF, _IOLBF, and _IOFBF defined in for the type argument to specify unbuffered, line-buffered, and fully buffered I/O, respectively. If _IONBF is specified for type, I/O will be unbuffered and the buffer and size arguments are ignored. If _IOLBF or _IOFBF is specified for type, the Compaq C RTL will use line-buffered I/O if file_ptr specifies a terminal device; otherwise, it will use fully buffered I/O. The Compaq C RTL automatically allocates a buffer to use for each I/O stream. So there are several buffer allocation possibilities: o If buffer is not a NULL pointer and size is not smaller than the automatically allocated buffer, then setvbuf uses buffer as the file buffer. o If buffer is a NULL pointer or size is smaller than the automatically allocated buffer, the automatically allocated buffer is used as the buffer area. o If buffer is a NULL pointer and size is larger than the automatically allocated buffer, then setvbuf allocates a new buffer equal to the specified size and uses that as the file buffer. User programs must not depend on the contents of buffer once I/O has been performed on the stream. The Compaq C RTL might or might not use buffer for any given I/O operation. REF-519 setvbuf Generally, it is unnecessary to use setvbuf or setbuf to control the buffer size used by the Compaq C RTL. The automatically allocated buffer sizes are chosen for efficiency based on the kind of I/O operations performed and the device characteristics (such as terminal, disk, or socket). The setvbuf and setbuf functions are useful to introduce buffering for improved performance when writing a large amount of text to the stdout stream. This stream is unbuffered by default when bound to a terminal device (the normal case), and therefore incurs a large number of OpenVMS buffered I/O operations unless Compaq C RTL buffering is introduced by a call to setvbuf or setbuf. The setvbuf function is used only to control the buffering used by the Compaq C RTL, not the buffering used by the underlying RMS I/O operations. You can modify RMS default buffering behavior by specifying various values for the ctx, fop, rat, gbc, mbc, mbf, rfm, and rop RMS keywords when the file is opened by the creat, freopen or open functions. Return Values 0 Indicates success. nonzero value Indicates that an invalid input value was specifed for type or file_ptr, or because file_ptr is being used by another thread (see Section 1.7.1). REF-520 sigaction _________________________________________________________________ sigaction Specifies the action to take upon delivery of a signal. Format #include int sigaction (int sig, const struct sigaction *action, struct sigaction *o_action); Arguments sig The signal for which the action is to be taken. action A pointer to a sigaction structure that describes the action to take when you receive the signal specified by the sig argument. o_action A pointer to a sigaction structure. When the sigaction function returns from a call, the action previously attached to the specified signal is stored in this structure. Description When a process requests the sigaction function, the process can both examine and specify what action to perform when the specified signal is delivered. The arguments determine the behavior of the sigaction function as follows: o Specifying the sig argument identifies the affected signal. Use any one of the signal values defined in the header file, except SIGKILL. If sig is SIGCHLD and the SA_NOCLDSTOP flag is not set in sa_flags, then a SIGCHLD signal is generated for the calling process whenever any of its child processes stop. If sig is SIGCHLD and the SA_NOCLDSTOP flag is set in sa_flags, then SIGCHLD signal is not generated in this way. REF-521 sigaction o Specifying the action argument, if not null, points to a sigaction structure that defines what action to perform when the signal is received. If the action argument is null, signal handling remains unchanged, so you can use the call to inquire about the current handling of the signal. o Specifying the o_action argument, if not null, points to a sigaction structure that contains the action previously attached to the specified signal. The sigaction structure consists of the following members: void (*sa_handler)(int); sigset_t sa_mask; int sa_flags; The sigaction structure members are defined as follows: sa_handler This member can contain the following values: o SIG_DFL - Specifies the default action taken when the signal is delivered. o SIG_IGN - Specifies that the signal has no effect on the receiving process. o Function pointer - Requests to catch the signal. The signal causes the function call. sa_mask This member can request that individual signals, in addition to those in the process signal mask, are blocked from delivery while the signal handler function specified by the sa_handler member is executing. sa_flags This member can set the flags to enable further control over the actions taken when a signal is delivered. The sa_flags member of the sigaction structure has the following values: REF-522 sigaction SA_ONSTACK Setting this bit causes the system to run the signal catching function on the signal stack specified by the sigstack function. If this bit is not set, the function runs on the stack of the process where the signal is delivered. SA_RESETHAND Setting this bit resets the signal to SIG_DFL. Be aware that you cannot automatically reset SIGILL and SIGTRAP. SA_NODEFER Setting this bit does not automatically block the signal as it is caught. SA_NOCLDSTOP If this bit is set and the sig argument is equal to SIGCHLD and a child process of the calling process stops, then a SIGCHLD signal is sent to the calling process only if SA_NOCLDSTOP is not set for SIGCHLD. When a signal is caught by a signal-catching function installed by sigaction, a new signal mask is calculated and installed for the duration of the signal-catching function (or until a call to either sigprocmask or sigsuspend is made. This mask is formed by taking the union of the current signal mask and the value of the sa_mask for the signal being delivered unless SA_NODEFER or SA_RESETHAND is set, and then including the signal being delivered. If and when the user's signal handler returns normally, the original signal mask is restored. Once an action is installed for a specific signal, it remains installed until another action is explicitly requested (by another call to sigaction), until the SA_ RESETHAND flag causes resetting of the handler, or until one of the exec functions is called. If the previous action for a specified signal had been established by signal, the values of the fields returned in the structure pointed to by the o_action argument of sigaction are unspecified, and in particular o_action->sa_handler is not necessarily the same value passed to signal. However, if a pointer to the same structure or a copy thereof is passed to a subsequent call to sigaction by means of the action argument of sigaction), REF-523 sigaction the signal is handled as if the original call to signal were repeated. If sigaction fails, no new signal handler is installed. It is unspecified whether an attempt to set the action for a signal that cannot be caught or ignored to SIG_DFL is ignored or causes an error to be returned with errno set to EINVAL. See Section 4.2 for more information on signal handling. ________________________ Note ________________________ The sigvec and signal functions are provided for compatibility to old UNIX systems; their function is a subset of that available with the sigaction function. ______________________________________________________ See also sigstack, sigvec, signal, wait, read, and write, in this section. Return Values 0 Indicates success. -1 Indicates an error; A new signal handler is not installed. errno is set to one of the following values: o EFAULT - The action or o_action argument points to a location outside of the allocated address space of the process. o EINVAL - The sig argument is not a valid signal number. Or an attempt was made to ignore or supply a handler for the SIGKILL, SIGSTOP, and SIGCONT signals. REF-524 sigaddset _________________________________________________________________ sigaddset Adds the specified individual signal. Format #include int sigaddset (sigset_t *set, int sig_number); Arguments set The signal set. sig_number The individual signal. Description This function manipulates sets of signals. This function operates on data objects that you can address by the application, not on any set of signals known to the system. For example, this function does not operate on the set blocked from delivery to a process or the set pending for a process. The sigaddset function adds the individual signal specified by sig_number from the signal set specified by set. Example The following example shows how to generate and use a signal mask that blocks only the SIGINT signal from delivery. #include int return_value; sigset_t newset; . . . sigemptyset(&newset); sigaddset(&newset, SIGINT); return_value = sigprocmask (SIG_SETMASK, &newset, NULL); REF-525 sigaddset Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EINVAL - The value of sig_number is not a valid signal number. REF-526 sigblock _________________________________________________________________ sigblock Adds the signals in mask to the current set of signals being blocked from delivery. Format #include int sigblock (int mask); Argument mask The signals to be blocked. Description Signal i is blocked if the i - 1 bit in mask is a 1. For example, to add the protection-violation signal to the set of blocked signals, use the following line: sigblock(1 << (SIGBUS - 1)); You can express signals in mnemonics (such as SIGBUS for a protection violation) or numbers as defined in the header file, and you can express combinations of signals by using the bitwise OR operator (|). Return Value x Indicates the previous set of masked signals. REF-527 sigdelset _________________________________________________________________ sigdelset Deletes a specified individual signal. Format #include int sigdelset (sigset_t *set, int sig_number;) Arguments set The signal set. sig_number The individual signal. Description The sigdelset function deletes the individual signal specified by sig_number from the signal set specified by set. This function operates on data objects that you can address by the application, not on any set of signals known to the system. For example, this function does not operate on the set blocked from delivery to a process or the set pending for a process. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EINVAL - The value of sig_number is not a valid signal number. REF-528 sigemptyset _________________________________________________________________ sigemptyset Initializes the signal set to exclude all signals. Format #include int sigemptyset (sigset_t *set); Arguments set The signal set. Description The sigemptyset function initializes the signal set pointed to by set such that you exclude all signals. A call to sigemptyset or sigfillset must be made at least once for each object of type sigset_t prior to any other use of that object. This function operates on data objects that you can address by the application, not on any set of signals known to the system. For example, this function does not operate on the set blocked from delivery to a process or the set pending for a process. See also sigfillset in this section. Example The following example shows how to generate and use a signal mask that blocks only the SIGINT signal from delivery. #include int return_value; sigset_t newset; . . . sigemptyset(&newset); sigaddset(&newset, SIGINT); return_value = sigprocmask (SIG_SETMASK, &newset, NULL); REF-529 sigemptyset Return Values 0 Indicates success. -1 Indicates an error; the global errno is set to indicate the error. REF-530 sigfillset _________________________________________________________________ sigfillset Initializes the signal set to include all signals. Format #include int sigfillset (sigset_t *set); Arguments set The signal set. Description The sigfillset function initializes the signal set pointed to by set such that you include all signals. A call to sigemptyset or sigfillset must be made at least once for each object of type sigset_t prior to any other use of that object. This function operates on data objects that you can address by the application, not on any set of signals known to the system. For example, this function does not operate on the set blocked from delivery to a process or the set pending for a process. See also sigemptyset in this section. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EINVAL - The value of the sig_ number argument is not a valid signal number. REF-531 sigismember _________________________________________________________________ sigismember Tests whether a specified signal is a member of the signal set. Format #include int sigismember (const sigset_t *set, int sig_number); Arguments set The signal set. sig_number The individual signal. Description The sigismember function tests whether sig_number is a member of the signal set pointed to by set. This function operates on data objects that you can address by the application, not on any set of signals known to the system. For example, this function does not operate on the set blocked from delivery to a process or the set pending for a process. Return Values 1 Indicates success. The specified signal is a member of the specified set. 0 Indicates an error. The specified signal is not a member of the specified set. REF-532 siglongjmp _________________________________________________________________ siglongjmp Nonlocal goto with signal handling. Format #include void siglongjmp (sigjmp_buf env, int value); Arguments env An address for a sigjmp_buf structure. value A nonzero value. Description This function restores the environment saved by the most recent call to sigsetjmp in the same process with the corresponding sigjmp_buf argument. All accessible objects have values when siglongjmp is called, with one exception: values of objects of automatic storage duration that changed between the sigsetjmp call and siglongjmp call are indeterminate. Because it bypasses the usual function call and return mechanisms, siglongjmp executes correctly during interrupts, signals, and any of their associated functions. However, if you invoke siglongjmp from a nested signal handler (for example, from a function invoked as a result of a signal raised during the handling of another signal), the behavior is undefined. The siglongjmp function restores the saved signal mask only if you initialize the env argument by a call to sigsetjmp with a nonzero savemask argument. After siglongjmp is completed, program execution continues as if the corresponding call of sigsetjmp just returned the value specified by value. The siglongjmp function REF-533 siglongjmp cannot cause sigsetjmp to return 0 (zero); if value is 0, sigsetjmp returns 1 See also sigsetjmp in this section. REF-534 sigmask _________________________________________________________________ sigmask Constructs the mask for a given signal number. Format #include int sigmask (signum); Argument signum The signal number for which the mask is to be constructed. Description This function is used to contruct the mask for a given signum. This mask can be used with the sigblock function. Return Value x The mask constructed for signum REF-535 signal _________________________________________________________________ signal Allows you to specify the way in which the signal sig is to be handled: use the default handling for the signal, ignore the signal, or call the signal handler at the address specified. Format #include void (*signal (int sig, void (*func) (int))) (int); Arguments sig The number or mnemonic associated with a signal. This argument is usually one of the mnemonics defined in the header file. func Either the action to take when the signal is raised, or the address of a function needed to handle the signal. Description If func is the constant SIG_DFL, the action for the given signal is reset to the default action, which is to terminate the receiving process. If the argument is SIG_ IGN, the signal is ignored. Not all signals can be ignored. If func is neither SIG_DFL nor SIG_IGN, it specifies the address of a signal-handling function. When the signal is raised, the addressed function is called with sig as its argument. When the addressed function returns, the interrupted process continues at the point of interruption. (This is called catching a signal. Signals are reset to SIG_DFL after they are caught, except as shown in Chapter 4.) You must call the signal function each time you want to catch a signal. See Section 4.2 for more information on signal handling. REF-536 signal To cause a OpenVMS exception or a signal to generate a UNIX style signal, user OpenVMS condition handlers must return SS$_RESIGNAL upon receiving any exception that they do not want to handle. Returning SS$_CONTINUE prevents the correct generation of a UNIX style signal. See Chapter 4 for a list of OpenVMS exceptions that correspond to UNIX signals. Return Values x The address of the function previously established to handle the signal. SIG_ERR Indicates that the sig argument is out of range. REF-537 sigpause _________________________________________________________________ sigpause Assigns mask to the current set of masked signals and then waits for a signal. Format #include int sigpause (int mask); Argument mask The signals to be blocked. Description See the sigblock function in this section for information about the mask argument. When control returns to sigpause, the function restores the previous set of masked signals, sets errno to EINTR, and returns -1 to indicate an interrupt. The value EINTR is defined in the header file. Return Value -1 Indicates an interrupt. errno is set to EINTR. REF-538 sigpending _________________________________________________________________ sigpending Examines pending signals. Format #include int sigpending (sigset_t *set); Arguments set A pointer to a sigset_t structure. Description This function stores the set of signals that are blocked from delivery and pending to the calling process in the location pointed to by the set argument. Call either the sigemptyset or the sigfillset function at least once for each object of type sigset_t prior to any other use of that object. If you do not initialize an object in this way and supply an argument to the sigpending function, the result is undefined. See sigemptyset, and sigfillset in this section. Return Values 0 Indicates success. -1 Indicates an error; errno is set to the following value: o SIGSEGV - Bad mask argument. REF-539 sigprocmask _________________________________________________________________ sigprocmask Sets the current signal mask. Format #include int sigprocmask (int how, const sigset_t *set, sigset_t *o_set); Arguments how An integer value that indicates how to change the set of masked signals. Use one of the following values: SIG_BLOCK The resulting set is the union of the current set and the signal set pointed to by the set argument. SIG_UNBLOCK The resulting set is the intersection of the current set and the complement of the signal set pointed to by the set argument. SIG_SETMASK The resulting set is the signal set pointed to by the set argument. set The signal set. If the value of the set argument is: o Not NULL - It points to a set of signals used to change the currently blocked set. o NULL - The value of the how argument is not significant, and the process signal mask is unchanged, so you can use the call to inquire about currently blocked signals. o_set A non-NULL pointer to the location where the signal mask in effect at the time of the call is stored. REF-540 sigprocmask Description This function is used to examine or change the signal mask of the calling process. Typically, use the sigprocmask SIG_BLOCK value to block signals during a critical section of code, then use the sigprocmask SIG_SETMASK value to restore the mask to the previous value returned by the sigprocmask SIG_BLOCK value. If there are any unblocked signals pending after the call to the sigprocmask function, at least one of those signals is delivered before the sigprocmask function returns. You cannot block SIGKILL or SIGSTOP signals with the sigprocmask function. If a program attempts to block one of these signals, the sigprocmask function gives no indication of the error. Example The following example shows how to set the signal mask to block only the SIGINT signal from delivery: #include int return_value; sigset_t newset; . . . sigemptyset(&newset); sigaddset(&newset, SIGINT); return_value = sigprocmask (SIG_SETMASK, &newset, NULL); Return Values 0 Indicates success. REF-541 sigprocmask -1 Indicates an error. The signal mask of the process is unchanged. errno is set to one of the following values: o EINVAL - The value of the how argument is not equal to one of the defined values. o EFAULT - The set or o_set argument points to a location outside the allocated address space of the process. REF-542 sigsetjmp _________________________________________________________________ sigsetjmp Sets jump point for a nonlocal goto. Format #include init sigsetjmp (sigjmp_buf env, int savemask); Arguments env An address for a sigjmp_buf structure. savemask An integer value that specifies whether you need to save the current signal mask. Description This function saves its calling environment in its env argument for later use by the siglongjmp function. If the value of savemask is not 0 (zero), sigsetjmp also saves the process' current signal mask as part of the calling environment. See also siglongjmp in this section. Restrictions You cannot invoke the longjmp function from an OpenVMS condition handler. However, you may invoke longjmp from a signal handler that has been established for any signal supported by the Compaq C RTL, subject to the following nesting restrictions: o The longjmp function will not work if you invoke it from nested signal handlers. The result of the longjmp function, when invoked from a signal handler that has been entered as a result of an exception generated in another signal handler, is undefined. REF-543 sigsetjmp o Do not invoke the sigsetjmp function from a signal handler unless the associated longjmp is to be issued before the handling of that signal is completed. o Do not invoke the longjmp function from within an exit handler (established with atexit or SYS$DCLEXH). Exit handlers are invoked after image tear-down, so the destination address of the longjmp no longer exists. o Invoking longjmp from within a signal handler to return to the main thread of execution might leave your program in an inconsistent state. Possible side effects include the inability to perform I/O or to receive any more UNIX signals. Use siglongjmp instead. Return Values 0 Indicates success. nonzero The return is a call to the siglongjmp function. REF-544 sigsetmask _________________________________________________________________ sigsetmask Establishes those signals that are blocked from delivery. Format #include int sigsetmask (int mask); Argument mask The signals to be blocked. Description See the sigblock function in this section for information about the mask argument. Return Value x The previous set of masked signals. REF-545 sigstack (VAX only) _________________________________________________________________ sigstack (VAX only) Defines an alternate stack on which to process signals. This allows the processing of signals in a separate environment from that of the current process. This function is nonreentrant. Format #include int sigstack (struct sigstack *ss, struct sigstack *oss); Arguments ss If ss is not NULL, it specifies the address of a structure that holds a pointer to a designated section of memory to be used as a signal stack on which to deliver signals. oss If oss is not NULL, it specifies the address of a structure in which the old value of the stack address is returned. Description The sigstack structure is defined in the standard header file as follows: struct sigstack { char *ss_sp; int ss_onstack; }; If the sigvec function specifies that the signal handler is to execute on the signal stack, the system checks to see if the process is currently executing on that stack. If the process is not executing on the signal stack, the system arranges a switch to the signal stack for the duration of the signal handler's execution. If the oss argument is not NULL, the current state of the signal stack is returned. REF-546 sigstack (VAX only) Signal stacks must be allocated an adequate amount of storage; they do not expand like the run-time stack. For example, if your signal handler calls printf or any similarly complex Compaq C RTL routine, at least 12,000 bytes of storage should be allocated for the signal stack. If the stack overflows, an error occurs. ss_sp must point to at least four bytes before the end of the allocated memory area (see the example). This is architecture-dependent and possibly not portable to other machine architectures or operating systems. The sigstack structure is defined in the header file. Return Values 0 Indicates success. -1 Indicates failure. Example #define ss_size 15000 static char mystack[ss_size]; struct sigstack ss = {&mystack + sizeof(mystack) - sizeof(void *), 1}; REF-547 sigsuspend _________________________________________________________________ sigsuspend Atomically changes the set of blocked signals and waits for a signal. Format #include int sigsuspend (const sigset_t *signal_mask); Arguments signal_mask A pointer to a set of signals. Description This function replaces the signal mask of the process with the set of signals pointed to by the signal_mask argument. Then it suspends execution of the process until delivery of a signal whose action is either to execute a signal catching function or to terminate the process. You cannot block the SIGKILL or SIGSTOP signals with the sigsuspend function. If a program attempts to block either of these signals, sigsuspend gives no indication of the error. If delivery of a signal causes the process to terminate, sigsuspend does not return. If delivery of a signal causes a signal catching function to execute, sigsuspend returns after the signal catching function returns, with the signal mask restored to the set that existed prior to the call to sigsuspend. The sigsuspend function sets the signal mask and waits for an unblocked signal as one atomic operation. This means that signals cannot occur between the operations of setting the mask and waiting for a signal. If a program invokes sigprocmask SIG_SETMASK and sigsuspend separately, a signal that occurs between these functions is often not noticed by sigsuspend. REF-548 sigsuspend In normal usage, a signal is blocked by using the sigprocmask function at the beginning of a critical section. The process then determines whether there is work for it to do. If there is no work, the process waits for work by calling sigsuspend with the mask previously returned by sigprocmask. If a signal is caught by the calling process and control is returned from the signal handler, the calling process resumes execution after sigsuspend, which always returns a value of -1 and sets errno to EINTR. See also sigpause, and sigprocmask in this section. REF-549 sigvec _________________________________________________________________ sigvec Permanently assigns a handler for a specific signal. Format #include int sigvec (int sigint, struct sigvec *sv, struct sigvec *osv); Arguments sigint The signal identifier. sv Pointer to a sigvec structure (see the Description section). osv If osv is not NULL, the previous handling information for the signal is returned. Description If sv is not NULL, it specifies the address of a structure containing a pointer to a handler routine and mask to be used when delivering the specified signal, and a flag indicating whether the signal is to be processed on an alternative stack. If sv->onstack has a value of 1, the system delivers the signal to the process on a signal stack specified with sigstack. The sigvec function establishes a handler that remains established until explicitly removed or until the image terminates. The sigvec structure is defined in the header file as follows: REF-550 sigvec struct sigvec { int (*handler)(); int mask; int onstack; }; See Section 4.2 for more information on signal handling. Return Values 0 Indicates that the call succeeded. -1 Indicates that an error occurred. REF-551 sin _________________________________________________________________ sin Returns the sine of its radian argument. Format #include double sin (double x); Argument x A radian expressed as a real number. REF-552 sinh _________________________________________________________________ sinh Returns the hyperbolic sine of its argument. Format #include double sinh (double x); Argument x A real number. Return Values n The hyperbolic sine of the argument. HUGE_VAL Indicates that the argument is too large; errno is set to ERANGE. REF-553 sleep _________________________________________________________________ sleep Suspends the execution of the current process for at least the number of seconds indicated by its argument. Format #include unsigned int sleep (unsigned seconds); (_DECC_V4_SOURCE) int sleep (unsigned seconds); (not _DECC_V4_SOURCE) Argument seconds The number of seconds. Description This function sleeps for the specified number of seconds, or until a signal is received, or until the process executes a call to SYS$WAKE. If a SIGALRM signal is generated, but blocked or ignored, the sleep function returns. For all other signals, a blocked or ignored signal does not cause sleep to return. Return Values x The number of seconds that the process awoke early. 0 If the process slept the full number of seconds specified by seconds REF-554 sprintf _________________________________________________________________ sprintf Performs formatted output to a string in memory. Format #include int sprintf (char *str, const char *format_spec, . . . ); Arguments str The address of the string that will receive the formatted output. It is assumed that this string is large enough to hold the output. format_spec A pointer to a character string that contains the format specification. For more information about format specifications and conversion characters, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you may omit the output sources. Otherwise, the function calls must have at least as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Excess output pointers, if any, are ignored. REF-555 sprintf Description A null character is automatically appended to the end of the output string. Consider the following example of a conversion specification: #include main() { int temp = 4, temp2 = 17; char s[80]; sprintf(s, "The answers are %d, and %d.", temp, temp2); } In this example, character string s has the following contents: The answers are 4, and 17. For a complete description of the format specification and the output source, see Chapter 2. Return Value x The number of characters placed in the output string, not including the final null character. Negative value Indicates an output error occurred. The function sets errno. For a list of errno values set by this function, see fprintf in this section. REF-556 sqrt _________________________________________________________________ sqrt Returns the square root of its argument. Format #include double sqrt (double x); Argument x A real number. Description The argument and the returned value are both objects of type double. Return Values val The square root of x, if x is nonnegative. 0 Indicates that x is negative; errno is set to EDOM. REF-557 srand _________________________________________________________________ srand Initializes the pseudorandom number generator rand. Format #include void srand (unsigned int seed); Argument seed An unsigned integer. Description This function uses the argument as a seed for a new sequence of pseudorandom numbers to be returned by subsequent calls to rand. If rand is called before any calls to srand, the sequence of pseudorandom numbers is generated as if the seed were set to 1. REF-558 srand48 _________________________________________________________________ srand48 Initializes a 48-bit random number generator. Format #include void srand48 (long int seed_val); Arguments seed_val The initialization value to begin randomization. Changing this value changes the randomization pattern. Description This function initializes the random number generator. You can use this function in your program before calling the drand48, lrand48, or mrand48 functions. (Although it is not recommended practice, constant default initializer values are supplied automatically if you call drand48, lrand48, or mrand48 without calling an initialization function). The function works by generating a sequence of 48-bit integer values, Xi, according to the linear congruential formula: Xn+1 = (aXn+c)mod m n >= 0 The argument m equals 248, so 48-bit integer arithmetic is performed. Unless you invoke the lcong48 function, the multiplier value a and the addend value c are: a = 5DEECE66D16 = 2736731631558 c = B16 = 138 The initializer function srand48 sets the high-order 32 bits of Xi to the low-order 32 bits contained in its argument. The low-order 16 bits of Xi are set to the arbitrary value 330E16. See also drand48, lrand48, and mrand48 in this section. REF-559 srandom _________________________________________________________________ srandom Initializes the pseudorandom number generator random. Format int srandom (unsigned seed); Arguments seed An initial seed value. Description This function uses the argument as a seed for a new sequence of pseudorandom numbers to be returned by subsequent calls to random. This function has virtually the same calling sequence and initialization properties as the srand function, but produce sequences that are more random. The srandom function initializes the current state with the initial seed value. The srandom function, unlike the srand function, does not return the old seed because the amount of state information used is more than a single word. See also rand, srand, random, setstate, and initstate in this section. Return Values 0 Indicates success. Initializes the state seed. -1 Indicates an error, further specified in the global errno. REF-560 sscanf _________________________________________________________________ sscanf Reads input from a character string in memory, interpreting it according to the format specification. Format #include int sscanf (const char *str, const char *format_spec, . . . ); Arguments str The address of the character string that provides the input text to sscanf. format_spec A pointer to a character string that contains the format specification. For more information about format specifications and conversion characters, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, you can omit the input pointers. Otherwise, the function calls must have at least as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. REF-561 sscanf Description The following is an example of a conversion specification: main () { char str[] = "4 17"; int temp, temp2; sscanf(str, "%d %d", &temp, &temp2); printf("The answers are %d and %d.", temp, temp2); } This example produces the following output: $ RUN EXAMPLE The answers are 4 and 17. For a complete description of the format specification and the input pointers, see Chapter 2. Return Values x The number of successfully matched and assigned input items. EOF Indicates that a read error occurred before any conversion.The function sets errno. For a list of the values set by this function, see fscanf in this section. REF-562 ssignal _________________________________________________________________ ssignal Allows you to specify the action to take when a particular signal is raised. Format #include void (*ssignal (int sig, void (*func) (int, . . . ))) (int, . . . ); Arguments sig A number or mnemonic associated with a signal. The symbolic constants for signal values are defined in the header file (see Chapter 4). func The action to take when the signal is raised, or the address of a function that is executed when the signal is raised. Description This function is equivalent to the signal function except for the return value on error conditions. Since the signal function is defined by the ANSI C standard and the ssignal function is not, use signal for greater portability. See Section 4.2 for more information on signal handling. Return Values x The address of the function previously established as the action for the signal. The address may be the value SIG_DFL (0) or SIG_IGN (1). REF-563 ssignal 0 Indicates errors. For this reason, there is no way to know whether a return status of 0 indicates failure, or whether it indicates that a previous action was SIG_DFL (0). REF-564 [w]standend _________________________________________________________________ [w]standend Deactivate the boldface attribute for the specified window. The standend function operates on the stdscr window. Format #include int standend (void); int wstandend (WINDOW *win); Argument win A pointer to the window. Description The standend and wstandend functions are equivalent to clrattr and wclrattr called with the attribute _BOLD. Return Values OK Indicates success. ERR Indicates an error. REF-565 [w]standout _________________________________________________________________ [w]standout Activate the boldface attribute of the specified window. The standout function acts on the stdscr window. Format #include int standout (void); int wstandout (WINDOW *win); Argument win A pointer to the window. Description The standout and wstandout functions are equivalent to setattr and wsetattr called with the attribute _BOLD. Return Values OK Indicates success. ERR Indicates an error. REF-566 stat _________________________________________________________________ stat Accesses information about the specified file. Format #include int stat (const char *file_spec, struct stat *buffer); (ISO POSIX-1) int stat (const char *file_spec, struct stat *buffer, . . . ); (DEC C Extension) Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Arguments file_spec A valid OpenVMS or UNIX style file specification (no wildcards). Read, write, or execute permission of the named file is not required, but you must be able to reach all directories listed in the file specification leading to the file. For more information about UNIX style file specifications, see Chapter 1. buffer A pointer to a structure of type stat_t that is defined in the header file. The argument receives information about the particular file. The members of the structure pointed to by buffer are described as follows: REF-567 stat ___________________________________________________________ Member______Type____________Definition_____________________ st_dev dev_t Pointer to the physical device name st_ino[3] ino_t Three words to receive the file ID st_mode mode_t File "mode" (prot, dir, . . . ) st_nlink nlink_t For UNIX system compatibility only st_uid uid_t Owner user ID st_gid gid_t Group member: from st_uid st_rdev dev_t UNIX system compatibility - always 0 st_size off_t File size, in bytes st_atime time_t File access time; always the same as st_mtime st_mtime time_t Last modification time st_ctime time_t File creation time st_fab_rfm char Record format st_fab_rat char Record attributes st_fab_fsz char Fixed header size st_fab_mrs__unsigned________Record_size____________________ The types dev_t, ino_t, off_t, mode_t, nlink_t, uid_t, gid_ t, and time_t, are defined in the header file. However, when compiling for compatibility (/DEFINE=_DECC_ V4_SOURCE), only dev_t, ino_t, and off_t are defined. As of OpenVMS Version 7.0, times are given in seconds since the Epoch (00:00:00 GMT, January 1, 1970). The st_mode structure member is the status information mode defined in the header file. The st_mode bits are described as follows: ___________________________________________________________ Bits_____Constant__Definition______________________________ 0170000 S_IFMT Type of file 0040000 S_IFDIR Directory REF-568 stat ___________________________________________________________ Bits_____Constant__Definition______________________________ 0020000 S_IFCHR Character special 0060000 S_IFBLK Block special 0100000 S_IFREG Regular 0030000 S_IFMPC Multiplexed char special 0070000 S_IFMPB Multiplexed block special 0004000 S_ISUID Set user ID on execution 0002000 S_ISGID Set group ID on execution 0001000 S_ISVTX Save swapped text even after use 0000400 S_IREAD Read permission, owner 0000200 S_IWRITE Write permission, owner 0000100__S_IEXEC___Execute/search_permission,_owner________ . . . An optional default file-name string. This is the only optional RMS keyword that can be specified for the stat function. See the description of the creat function for the full list of optional RMS keywords and their values. Description This function does not work on remote network files. If the file is a record file, the st_size field includes carriage-control information. Consequently, the st_size value will not correspond to the number of characters that can be read from the file. The physical device name string referred to by the st_dev member of the stat structure is overwritten by the next stat call. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, the stat, fstat, utime, and utimes functions have been enhanced to take advantage of the new file-system support for POSIX-compliant file timestamps. REF-569 stat This support is available only on ODS-5 devices on OpenVMS Alpha systems beginning with a version of OpenVMS Alpha after Version 7.3. Before this change, the stat and fstat functions were setting the values of the st_ctime, st_mtime, and st_ atime fields based on the following file attributes: st_ctime - ATR$C_CREDATE (file creation time) st_mtime - ATR$C_REVDATE (file revision time) st_atime - was always set to st_mtime because no support for file access time was available Also, for the file-modification time, utime and utimes were modifying the ATR$C_REVDATE file attribute, and ignoring the file-access-time argument. After the change, for a file on an ODS-5 device, the stat and fstat functions set the values of the st_ ctime, st_mtime, and st_atime fields based on the following new file attributes: st_ctime - ATR$C_ATTDATE (last attribute modification time) st_mtime - ATR$C_MODDATE (last data modification time) st_atime - ATR$C_ACCDATE (last access time) If ATR$C_ACCDATE is zero, as on an ODS-2 device, the stat and fstat functions set st_atime to st_mtime. For the file-modification time, the utime and utimes functions modify both the ATR$C_REVDATE and ATR$C_MODDATE file attributes. For the file-access time, these functions modify the ATR$C_ACCDATE file attribute. Setting the ATR$C_MODDATE and ATR$C_ACCDATE file attributes on an ODS-2 device has no effect. For compatibility, the old behavior of stat, fstat, utime and utimes remains the default, regardless of the kind of device. The new behavior must be explicitly enabled by defining the DECC$EFS_FILE_TIMESTAMPS logical name to "ENABLE" before invoking the application. Setting this logical does not affect the behavior of stat, fstat, utime and utimes for files on an ODS-2 device. ______________________________________________________ REF-570 stat Return Values 0 Indicates success. -1 Indicates an error other than a privilege violation; errno is set to indicate the error. -2 Indicates a privilege violation. REF-571 strcasecmp _________________________________________________________________ strcasecmp Does a case-insensitive comparison of two 7-bit ASCII strings. Format #include int strcasecmp (const char *s1, const char *s2); Arguments s1 The first of two strings to compare. s2 The second of two strings to compare. Description This function is case-insensitive. The returned lexicographic difference reflects a conversion to lowercase. The strcasecmp function works for 7-bit ASCII compares only. Do not use this function for internationalized applications. Return Values n An integer value greater than, equal to, or less than 0 (zero), depending on whether the s1 string is greater than, equal to, or less than the s2 string. REF-572 strcat _________________________________________________________________ strcat Concatenates str_2, including the terminating null character, to the end of str_1. Format #include char *strcat (char *str_1, const char *str_2); Function Variants This function also has variants named _strcat32 and _ strcat64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments str_1, str_2 Pointers to null-terminated character strings. Description See also strncat in this section. Return Value x The address of the first argument, str_1, which is assumed to be large enough to hold the concatenated result. Example #include #include /* This program concatenates two strings using the strcat */ /* function, and then manually compares the result of strcat */ /* to the expected result. */ REF-573 strcat #define S1LENGTH 10 #define S2LENGTH 8 main() { static char s1buf[S1LENGTH + S2LENGTH] = "abcmnexyz"; static char s2buf[] = " orthis"; static char test1[] = "abcmnexyz orthis"; int i; char *status; /* Take static buffer s1buf, concatenate static buffer */ /* s2buf to it, and compare the answer in s1buf with the */ /* static answer in test1. */ status = strcat(s1buf, s2buf); for (i = 0; i <= S1LENGTH + S2LENGTH - 2; i++) { /* Check for correct returned string. */ if (test1[i] != s1buf[i]) printf("error in strcat"); } } REF-574 strchr _________________________________________________________________ strchr Returns the address of the first occurrence of a given character in a null-terminated string. The terminating null character is considered to be part of the string. Format #include char *strchr (const char *str, int character); Function Variants This function also has variants named _strchr32 and _ strchr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments str A pointer to a null-terminated character string. character An object of type int. Description See also strrchr in this section. Return Values x The address of the first occurrence of the specified character. NULL Indicates that the character does not occur in the string. REF-575 strchr Example #include #include main() { static char s1buf[] = "abcdefghijkl lkjihgfedcba"; int i; char *status; /* This program checks the strchr function by incrementally */ /* going through a string that ascends to the middle and then */ /* descends towards the end. */ for (i = 0; s1buf[i] != '\0' && s1buf[i] != ' '; i++) { status = strchr(s1buf, s1buf[i]); /* Check for pointer to leftmost character - test 1. */ if (status != &s1buf[i]) printf("error in strchr"); } } REF-576 strcmp _________________________________________________________________ strcmp Compares two ASCII character strings and returns a negative, 0, or positive integer, indicating that the ASCII values of the individual characters in the first string are less than, equal to, or greater than the values in the second string. Format #include int strcmp (const char *str_1, const char *str_2); Arguments str_1, str_2 Pointers to character strings. Description The strings are compared until a null character is encountered or until the strings differ. Return Values < 0 Indicates that str_1 is less than str_2. = 0 Indicates that str_1 equals str_2. > 0 Indicates that str_1 is greater than str_2. REF-577 strcoll _________________________________________________________________ strcoll Compares two strings and returns an integer that indicates if the strings differ and how they differ. The function uses the collating information in the LC_COLLATE category of the current locale to determine how the comparison is performed. Format #include int strcoll (const char *s1, const char *s2); Arguments s1, s2 Pointers to character strings. Description This function, unlike strcmp, compares two strings in a locale-dependent manner. Because no value is reserved for error indication, the application must check for one by setting errno to 0 before the function call and testing it after the call. See also the strxfrm function is this section. Return Values < 0 Indicates that s1 is less than s2. = 0 Indicates that the strings are equal. > 0 Indicates that s1 is greater than s2. REF-578 strcpy _________________________________________________________________ strcpy Copies all of source, including the terminating null character, into dest. Format #include char *strcpy (char *dest, const char *source); Function Variants This function also has variants named _strcpy32 and _ strcpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest Pointer to the destination character string. source Pointer to the source character string. Description This function copies source into dest, and stops after copying source's null character. The behavior of this function is undefined if the area pointed to by dest overlaps the area pointed to by source. Return Value x The address of dest. REF-579 strcspn _________________________________________________________________ strcspn Returns the length of the prefix of a string that consists entirely of characters not in a specified set of characters. Format #include size_t strcspn (const char *str, const char *charset); Arguments str A pointer to a character string. If this character string is a null string, 0 is returned. charset A pointer to a character string containing the set of characters. Description This function scans the characters in the string, stops when it encounters a character found in charset, and returns the length of the string's initial segment formed by characters not found in charset. If none of the characters match in the character strings pointed to by str and charset, strcspn returns the length of string. Return Value x The length of the segment. REF-580 strdup _________________________________________________________________ strdup Finds and points to a duplicate string. Format #include char *strdup (const char *s1); Function Variants This function also has variants named _strdup32 and _ strdup64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s1 The first of two strings to compare. Description This function returns a pointer to a string that is an exact duplicate of the string pointed to by s1. The malloc function is used to allocate space for the new string. The strdup function is provided for compatibility with existing systems. Return Values x A pointer to the resulting string. NULL Indicates an error. REF-581 strerror _________________________________________________________________ strerror Maps the error number in error_code to a locale-dependent error message string. Format #include char *strerror (int error_code); (ANSI C) char *strerror (int error_code[, int vms_error_code]); (DEC C Extension) Arguments error_code An error code. vms_error_code An OpenVMS error code. Description This function uses the error number in error_code to retrieve the appropriate locale-dependent error message. The contents of the error message strings are determined by the LC_MESSAGES category of the program's current locale. When a program is not compiled with any standards-related feature-test macros (see Section 1.5.1), strerror has a second argument (vms_error_code), which is used in the following way: o If error_code is EVMSERR and there is a second argument, then that second argument is used as the vaxc$errno value. o If error_code is EVMSERR and there is no second argument, look at vaxc$errno to get the OpenVMS error condition. See the strerror example. Use of the second argument is not included in the ANSI C definition of strerror and is, therefore, not portable. REF-582 strerror Because no return value is reserved to indicate an error, applications should set the value of errno to 0, call strerror, and then test the value of errno; a nonzero value indicates an error condition. Return Values x A pointer to a buffer containing the appropriate error message. Do not modify this buffer in your programs. Moreover, calls to the strerror function may overwrite this buffer with a new message. Example #include #include #include #include #include main() { puts(strerror(EVMSERR)); errno = EVMSERR; vaxc$errno = SS$_LINKEXIT; puts(strerror(errno)); puts(strerror(EVMSERR, SS$_ABORT)); exit(1); } Running this example produces the following output: non-translatable vms error code: network partner exited abort REF-583 strfmon _________________________________________________________________ strfmon Converts a number of monetary values into a string. The conversion is controlled by a format string. Format #include ssize_t strfmon (char *s, size_t maxsize, const char *format, . . . ); Arguments s A pointer to the resultant string. maxsize The maximum number of bytes to be stored in the resultant string. format A pointer to a string that controls the format of the output string. . . . The monetary values of type double that are to be formatted for the output string. There should be as many values as there are conversion specifications in the format string pointed to by format. The function fails if there are insufficient values. Excess arguments are ignored. Description This function creates a string pointed to by s, using the monetary values supplied. A maximum of maxsize bytes is copied to s. The format string pointed to by format consists of ordinary characters and conversion specifications. All ordinary characters are copied unchanged to the output string. A conversion specification defines how one of the monetary values supplied is formatted in the output string. REF-584 strfmon A conversion specification consists of a percent character (%), followed by a number of optional characters (see Table REF-5), and concluding with a conversion specifier (see Table REF-6). If any of the optional characters listed in Table REF-5 is included in a conversion specification, they must appear in the order shown. Table REF-5 Optional Characters in strfmon Conversion ____________Specifications_________________________________ Character_______Meaning____________________________________ =character Use character as the numeric fill character if a left precision is specified. The default numeric fill character is the space character. The fill character must be representable as a single byte in order to work with precision and width count. This conversion specifier is ignored unless a left precision is specified, and it does not affect width filling, which always uses the space character. ^ Do not use separator characters to format the number. By default, the digits are grouped according to the mon_grouping field in the LC_MONETARY category of the current locale. + Add the string specified by the positive_ sign or negative_sign fields in the current locale. If p_sign_posn or n_sign_posn is set to zero, then parentheses are used by default to indicate negative values. Otherwise, sign strings are used to indicate the sign of the value. You cannot use a + and a ( in the same conversion specification. (continued on next page) REF-585 strfmon Table REF-5 (Cont.) Optional Characters in strfmon ____________________Conversion_Specifications______________ Character_______Meaning____________________________________ ( Enclose negative values within parentheses. The default is taken from the p_sign_posn and n_sign_posn fields in the current locale. If p_sign_posn or n_sign_posn is set to zero, then parentheses are used by default to indicate negative values. Otherwise, sign strings are used to indicate the sign of the value. You cannot use a + and ( in the same conversion specification. ! Suppress the currency symbol. By default, the currency symbol is included. - Left-justify the value within the field. By default, values are right-justified. field width A decimal integer that specifies the minimum field width in which to align the result of the conversion. The default field width is the smallest field that can contain the result. #left_ A # followed by a decimal integer specifies precision the number of digits to the left of the radix character. Extra positions are filled by the fill character. By default the precision is the smallest required for the argument. If grouping is not suppressed with the ^ conversion specifier, and if grouping is defined for the current locale, grouping separators are inserted before any fill characters are added. Grouping separators are not applied to fill characters even if the fill character is defined as a digit. (continued on next page) REF-586 strfmon Table REF-5 (Cont.) Optional Characters in strfmon ____________________Conversion_Specifications______________ Character_______Meaning____________________________________ .right_ A period (.) followed by a decimal integer precision specifies the number of digits to the right of the radix character. Extra positions are filled with zeros. The amount is rounded to this number of decimal places. If the right precision is zero, the radix character is not included in the output. By default the right precision is defined by the frac_ digits or int_frac_digits field of the ________________current_locale.____________________________ Table_REF-6_strfmon_Conversion_Specifiers__________________ Specifier_Meaning__________________________________________ i Use the international currency symbol defined by the int_currency_symbol field in the current locale, unless the currency symbol has been suppressed. n Use the local currency symbol defined by the currency_symbol field in the current locale, unless the currency symbol has been suppressed. % Output a % character. The conversion specification must be %%; none of the optional __________characters_is_valid_with_this_specifier._________ Return Values x The number of bytes written to the string pointed to by s, not including the null terminating character. REF-587 strfmon -1 Indicates an error.The function sets errno to one of the following values: o EINVAL - A conversion specification is syntactically incorrect. o E2BIG - Processing the complete format string would produce more than maxsize bytes. Example #include #include #include #include #include #define MAX_BUF_SIZE 124 main() { size_t ret; char buffer[MAX_BUF_SIZE]; double amount = 102593421; /* Display a monetary amount using the en_US.ISO8859- 1 */ /* locale and a range of different display formats. */ if (setlocale(LC_ALL, "en_US.ISO8859- 1") == (char *) NULL) { perror("setlocale"); exit(EXIT_FAILURE); } ret = strfmon(buffer, MAX_BUF_ SIZE, "International: %i\n", amount); printf(buffer); ret = strfmon(buffer, MAX_BUF_ SIZE, "National: %n\n", amount); printf(buffer); REF-588 strfmon ret = strfmon(buffer, MAX_BUF_ SIZE, "National: %=*#10n\n", amount); printf(buffer); ret = strfmon(buffer, MAX_BUF_ SIZE, "National: %(n\n", -1 * amount); printf(buffer); ret = strfmon(buffer, MAX_BUF_ SIZE, "National: %^!n\n", amount); printf(buffer); } Running the example program produces the following result: International: USD 102,593,421.00 National: $102,593,421.00 National: $**102,593,421.00 National: ($102,593,421.00) National: 102593421.00 REF-589 strftime _________________________________________________________________ strftime Uses date and time information stored in a tm structure, to create an output string. The format of the output string is controlled by a format string. Format #include size_t strftime (char *s, size_t maxsize, const char *format, const struct tm *timeptr); Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Arguments s A pointer to the resultant string. maxsize The maximum number of bytes to be stored in the resultant string, including the null terminator. format A pointer to a string that controls the format of the output string. timeptr A pointer to the local time (tm) structure. The tm structure is defined in the header file. REF-590 strftime Description This function uses data in the structure pointed to by timeptr to create the string pointed to by s. A maximum of maxsize bytes is copied to s. The format string consists of zero or more conversion specifications and ordinary characters. All ordinary characters (including the terminating null character) are copied unchanged into the output string. A conversion specification defines how data in the tm structure is formatted in the output string. A conversion specification consists of a percent (%) character followed by one or more optional characters (see Table REF-7), and concluding with a conversion specifier (see Table REF-8). If any of the optional characters listed in Table REF-7 are specified, they must appear in the order shown in the table. The strftimefunction behaves as if it called tzset. Table REF-7 Optional Elements of strftime Conversion ____________Specifications_________________________________ Element___Meaning__________________________________________ - Optional with the field width to specify that the field is left-justified and padded with spaces. This cannot be used with the 0 element. 0 Optional with the field width to specify that the field is right-justified and padded with zeros. This cannot be used with the - element. field A decimal integer that specifies the maximum width field width (continued on next page) REF-591 strftime Table REF-7 (Cont.) Optional Elements of strftime ____________________Conversion_Specifications______________ Element___Meaning__________________________________________ .precisionA decimal integer that specifies the precision of data in a field. For the d, H, I, j, m, M, o, S, U, w, W, y and Y conversion specifiers, the precision specifier is the minimum number of digits to appear in the field. If the conversion specification has fewer digits than that specified by the precision, leading zeros are added. For the a, A, b, B, c, D, E, h, n, N, p, r, t, T, x, X, Z, and % conversion specifiers, the precision specifier is the maximum number of characters to appear in the field. If the conversion specification has more characters than that specified by the the precision, characters are truncated on the right. The default precision for the d, H, I, m, M, o, S, U, w, W, y and Y conversion specifiers is 2; the default precision for the j conversion __________specifier_is_3.__________________________________ Note that the list of conversion specifications in Table REF-7 are extensions to the XPG4 specification. Table REF-8 lists the conversion specifiers. The strftime function uses fields in the LC_TIME category of the program's current locale to provide a value. For example, if %B is specified, the function accesses the mon field in LC_TIME to find the full month name for the month specified in the tm structure. The result of using invalid conversion specifiers is undefined. Table_REF-8_strftime_Conversion_Specifiers_________________ Specifier_Replaced_by______________________________________ a The locale's abbreviated weekday name (continued on next page) REF-592 strftime Table_REF-8_(Cont.)_strftime_Conversion_Specifiers_________ Specifier_Replaced_by______________________________________ A The locale's full weekday name b The locale's abbreviated month name B The locale's full month name c The locale's appropriate date and time representation C The century number (the year divided by 100 and truncated to an integer) as a decimal number (00 - 99) d The day of the month as a decimal number (01 - 31) D Same as %m/%d/%y e The day of the month as a decimal number (1 - 31) in a 2 digit field with the leading space character fill Ec The locale's alternative date and time representation EC The name of the base year (period) in the locale's alternative representation Ex The locale's alternative date representation EX The locale's alternative time representation Ey The offset from the base year (%EC) in the locale's alternative representation EY The locale's full alternative year representation h Same as %b H The hour (24-hour clock) as a decimal number (00 - 23) I The hour (12-hour clock) as a decimal number (01 - 12) j The day of the year as a decimal number (001 - 366) m The month as a decimal number (01 - 12) M The minute as a decimal number (00 - 59) (continued on next page) REF-593 strftime Table_REF-8_(Cont.)_strftime_Conversion_Specifiers_________ Specifier_Replaced_by______________________________________ n The newline character Od The day of the month using the locale's alternative numeric symbols Oe The date of the month using the locale's alternative numeric symbols OH The hour (24-hour clock) using the locale's alternative numeric symbols OI The hour (12-hour clock) using the locale's alternative numeric symbols Om The month using the locale's alternative numeric symbols OM The minutes using the locale's alternative numeric symbols OS The seconds using the locale's alternative numeric symbols Ou The weekday as a number in the locale's alternative representation (Monday=1) OU The week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols OV The week number of the year (Monday as the first day of the week) as a decimal number (01 -53) using the locale's alterntative numeric symbols. If the week containing January 1 has four or more days in the new year, it is considered as week 1. Otherwise, it is considered as week 53 of the previous year, and the next week is week 1. Ow The weekday as a number (Sunday=0) using the locale's alternative numeric symbols OW The week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols (continued on next page) REF-594 strftime Table_REF-8_(Cont.)_strftime_Conversion_Specifiers_________ Specifier_Replaced_by______________________________________ Oy The year without the century using the locale's alternative numeric symbols p The locale's equivalent of the AM/PM designations associated with a 12-hour clock r The time in AM/PM notation R The time in 24-hour notation (%H:%M) S The second as a decimal number (00 - 61) t The tab character T The time (%H:%M:%S) u The weekday as a decimal number between 1 and 7 (Monday=1) U The week number of the year (the first Sunday as the first day of week 1) as a decimal number (00 - 53) V The week number of the year (Monday as the first day of the week) as a decimal number (00 - 53). If the week containing January 1 has four or more days in the new year, it is considered as week 1. Otherwise, it is considered as week 53 of the previous year, and the next week is week 1. w The weekday as a decimal number (0 [Sunday] - 6) W The week number of the year (the first Monday as the first day of week 1) as a decimal number (00 - 53) x The locale's appropriate date representation X The locale's appropriate time representation y The year without century as a decimal number (00 - 99) Y The year with century as a decimal number Z Time-zone name or abbreviation. If time-zone information is not available, no character is output. (continued on next page) REF-595 strftime Table_REF-8_(Cont.)_strftime_Conversion_Specifiers_________ Specifier_Replaced_by______________________________________ %_________%________________________________________________ Return Values x The number of characters placed into the array pointed to by s, not including the terminating null character. 0 Indicates an error occurred. The contents of the array are indeterminate. Example #include #include #include #include #include #define NUM_OF_DATES 7 #define BUF_SIZE 256 /* This program formats a number of different dates, once using */ /* the C locale and then using the fr_FR.ISO8859- 1 locale. Date */ /* and time formatting is done using strftime(). */ main() { int count, i; char buffer[BUF_SIZE]; struct tm *tm_ptr; time_t time_list[NUM_OF_DATES] = {500, 68200000, 694223999, 694224000, 704900000, 705000000, 705900000}; /* Display dates using the C locale */ printf("\nUsing the C locale:\n\n"); setlocale(LC_ALL, "C"); REF-596 strftime for (i = 0; i < NUM_OF_DATES; i++) { /* Convert to a tm structure */ tm_ptr = localtime(&time_list[i]); /* Format the date and time */ count = strftime(buffer, BUF_SIZE, "Date: %A %d %B %Y%nTime: %T%n%n", tm_ ptr); if (count == 0) { perror("strftime"); exit(EXIT_FAILURE); } /* Print the result */ printf(buffer); } /* Display dates using the fr_FR.ISO8859-1 locale */ printf("\nUsing the fr_FR.ISO8859-1 locale:\n\n"); setlocale(LC_ALL, "fr_FR.ISO8859-1"); for (i = 0; i < NUM_OF_DATES; i++) { /* Convert to a tm structure */ tm_ptr = localtime(&time_list[i]); /* Format the date and time */ count = strftime(buffer, BUF_SIZE, "Date: %A %d %B %Y%nTime: %T%n%n", tm_ ptr); if (count == 0) { perror("strftime"); exit(EXIT_FAILURE); } /* Print the result */ printf(buffer); } } Running the example program produces the following result: Using the C locale: Date: Thursday 01 January 1970 Time: 00:08:20 Date: Tuesday 29 February 1972 Time: 08:26:40 REF-597 strftime Date: Tuesday 31 December 1991 Time: 23:59:59 Date: Wednesday 01 January 1992 Time: 00:00:00 Date: Sunday 03 May 1992 Time: 13:33:20 Date: Monday 04 May 1992 Time: 17:20:00 Date: Friday 15 May 1992 Time: 03:20:00 Using the fr_FR.ISO8859-1 locale: Date: jeudi 01 janvier 1970 Time: 00:08:20 Date: mardi 29 février 1972 Time: 08:26:40 Date: mardi 31 décembre 1991 Time: 23:59:59 Date: mercredi 01 janvier 1992 Time: 00:00:00 Date: dimanche 03 mai 1992 Time: 13:33:20 Date: lundi 04 mai 1992 Time: 17:20:00 Date: vendredi 15 mai 1992 Time: 03:20:00 REF-598 strlen _________________________________________________________________ strlen Returns the length of a string of ASCII characters. The returned length does not include the terminating null character (\0). Format #include size_t strlen (const char *str); Argument str A pointer to the character string. Return Value x The length of the string. REF-599 strncasecmp _________________________________________________________________ strncasecmp Does a case-insensitive comparison between two 7-bit ASCII strings. Format #include int strncasecmp (const char *s1, const char *s2, size_t n); Arguments s1 The first of two strings to compare. s2 The second of two strings to compare. n The maximum number of bytes in a string to compare. Description This function is case-insensitive. The returned lexicographic difference reflects a conversion to lowercase. The strncasecmp function is similar to the strcasecmp function, but also compares size. If the size specified by n is read before a NULL, the comparison stops. The strcasecmp function works for 7-bit ASCII compares only. Do not use this function for internationalized applications. Return Values n An integer value greater than, equal to, or less than 0 (zero), depending on whether s1 is greater than, equal to, or less than s2. REF-600 strncat _________________________________________________________________ strncat Appends not more than maxchar characters from str_2 to the end of str_1. Format #include char *strncat (char *str_1, const char *str_2, size_t maxchar); Function Variants This function also has variants named _strncat32 and _ strncat64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments str_1, str_2 Pointers to null-terminated character strings. maxchar The number of characters to concatenate from str_2, unless strncat first encounters a null terminator in str_2. If maxchar is 0, no characters are copied from str_2. Description A null character is always appended to the result of the strncat function. If strncat reaches the specified maximum, it sets the next byte in str_1 to the null character. Return Value x The address of the first argument, str_1, which is assumed to be large enough to hold the concatenated result. REF-601 strncmp _________________________________________________________________ strncmp Compares not more than maxchar characters of two ASCII character strings and returns a negative, 0, or positive integer, indicating that the ASCII values of the individual characters in the first string are less than, equal to, or greater than the values in the second string. Format #include int strncmp (const char *str_1, const char *str_2, size_t maxchar); Arguments str_1, str_2 Pointers to character strings. maxchar The maximum number of characters (beginning with the first) to search in both str_1 and str_2. If maxchar is 0, no comparison is performed and 0 is returned (the strings are considered equal). Description This function compares no more than maxchar characters from the string pointed to by str_1 to the string pointed to by str_2. The strings are compared until a null character is encountered, the strings differ, or maxchar is reached. Characters that follow a difference or a null character are not compared. Return Values < 0 Indicates that str_1 is less than str_2. = 0 Indicates that str_1 equals str_2. REF-602 strncmp > 0 Indicates that str_1 is greater than str_2. Examples 1.#include #include main() { printf( "%d\n", strncmp("abcde", "abc", 3)); } When linked and executed, this example returns 0, because the first 3 characters of the 2 strings are equal: $ run tmp 0 2.#include #include main() { printf( "%d\n", strncmp("abcde", "abc", 4)); } When linked and executed, this example returns a value greater than 0 because the first 4 characters of the 2 strings are not equal (The "d" in the first string is not equal to the null character in the second): $ run tmp 100 REF-603 strncpy _________________________________________________________________ strncpy Copies not more than maxchar characters from source into dest. Format #include char *strncpy (char *dest, const char *source, size_t maxchar); Function Variants This function also has variants named _strncpy32 and _ strncpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest Pointer to the destination character string. source Pointer to the source character string. maxchar The maximum number of characters to copy from source to dest up to but not including the null terminator of source. Description This function copies no more than maxchar characters from source to dest, up to but not including the null terminator of source. If source contains less than maxchar characters, dest is padded with null characters. If source contains greater than or equal to maxchar characters, as many characters as possible are copied to dest. Be aware that the dest argument might not be terminated by a null character after a call to strncpy. REF-604 strncpy Return Value x The address of dest. REF-605 strnlen _________________________________________________________________ strnlen Returns the number of bytes in a string. Format #include size_t strnlen (const char *s, size_t n); Arguments s Pointer to the string. n The maximum number of characters to examine. Description This function returns the number of bytes in the string pointed to by s. The string length value does not include the terminating null character. The strnlen function counts bytes until the first null byte or until n bytes have been examined. Return Values n The length of the string. REF-606 strpbrk _________________________________________________________________ strpbrk Searches a string for the occurrence of one of a specified set of characters. Format #include char *strpbrk (const char *str, const char *charset); Function Variants This function also has variants named _strpbrk32 and _ strpbrk64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments str A pointer to a character string. If this character string is a null string, 0 is returned. charset A pointer to a character string containing the set of characters for which the function will search. Description This function scans the characters in the string, stops when it encounters a character found in charset, and returns the address of the first character in the string that appears in the character set. Return Values x The address of the first character in the string that is in the set. NULL Indicates that no character is in the set. REF-607 strptime _________________________________________________________________ strptime Converts a character string into date and time values that are stored in a tm structure. Conversion is controlled by a format string. Format #include char *strptime (const char *buf, const char *format, struct tm *timeptr); Function Variants This function also has variants named _strptime32 and _ strptime64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments buf A pointer to the character string to convert. format A pointer to the string that defines how the input string is converted. timeptr A pointer to the local time structure. The tm structure is defined in the header file. Description This function converts the string pointed to by buf into values that are stored in the structure pointed to by timeptr. The string pointed to by format defines how the conversion is performed. The strptime function modifies only those fields in the tm structure that have corresponding conversion specifications in the format. In particular, strptime never sets the tm_ isdst member of the tm structure. REF-608 strptime The format string consists of zero or more directives. A directive is composed of one of the following: o One or more white-space characters (as defined by the isspace function). This directive causes the function to read input up to the first character that is not a white-space character. o Any character other than the percent character (%) or a white-space character. This directive causes the function to read the next character. The character read must be the same as the character that comprises the directive. If the character is different, the function fails. o A conversion specification. A conversion specification defines how characters in the input string are interpreted as values that are then stored in the tm structure. A conversion specification consists of a percent (%) character followed by a conversion specifier. Table REF-9 lists the valid conversion specifications. The strptime function uses fields in the LC_TIME category of the program's current locale to provide a value. ________________________ Note ________________________ To be compliant with X/Open CAE Specification System Interfaces and Headers Issue 5 (commonly known as XPG5), the strptime function processes the "%y" directive differently than in previous versions of the Compaq C RTL. With Compaq C Version 6.4 and higher, for a two-digit year within the century if no century is specified, "%y" directive values ranging from: o 69 to 99 refer to years in the twentieth century (1969 to 1999 inclusive) o 00 to 68 refer to years in the twenty-first century (2000 to 2068 inclusive) In previous (XPG4-compliant) versions of the Compaq C RTL, strptime interpreted a two-digit year with no century specified as a year within the twentieth century. REF-609 strptime The XPG5-compliant strptime is now the default version in the Compaq C RTL. To obtain the old, XPG4-compliant strptime function behavior, specify one of the following: o Define the DECC$XPG4_STRPTIME logical name: $ DEFINE DECC$XPG4_STRPTIME ENABLE Or o Call the XPG4 strptime directly as the function decc$strptime_xpg4. To return to using the XPG5 strptime version, DEASSIGN the DECC$XPG4_STRPTIME logical name: $ DEASSIGN DECC$XPG4_STRPTIME ______________________________________________________ Table_REF-9_strptime_Conversion_Specifications_____________ SpecificatReplaced_by______________________________________ %a The weekday name. This is either the abbreviated or the full name. %A Same as %a %b The month name. This is either the abbreviated or the full name. %B Same as %b. %c The date and time using the locale's date format %Ec The locale's alternative date and time representation %C The century number (the year divided by 100 and truncated to an integer) as a decimal number (00 - 99). Leading zeros are permitted. %EC The name of the base year (period) in the locale's alternative representation %d The day of the month as a decimal number (01 - 31). Leading zeros are permitted. (continued on next page) REF-610 strptime Table_REF-9_(Cont.)_strptime_Conversion_Specifications_____ SpecificatReplaced_by______________________________________ %Od The day of the month using the locale's alternative numeric symbols %D Same as %m/%d/%y %e Same as %d %Oe The date of the month using the locale's alternative numeric symbols %h Same as %b %H The hour (24-hour clock) as a decimal number (00 - 23). Leading zeros are permitted. %OH The hour (24-hour clock) using the locale's alternative numeric symbols %I The hour (12-hour clock) as a decimal number (01 - 12). Leading zeros are permitted. %OI The hour (12-hour clock) using the locale's alternative numeric symbols %j The day of the year as a decimal number (001 - 366) %m The month as a decimal number (01 - 12). Leading zeros are permitted. %Om The month using the locale's alternative numeric symbols %M The minute as a decimal number (00 - 59). Leading zeros are permitted. %OM The minutes using the locale's alternative numeric symbols %n Any whitespace character %p The locale's equivalent of the AM/PM designations associated with a 12-hour clock %r The time in AM/PM notation (%I:%M:%S %p) %R The time in 24-hour notation (%H:%M) %S The second as a decimal number (00 - 61). Leading zeros are permitted. (continued on next page) REF-611 strptime Table_REF-9_(Cont.)_strptime_Conversion_Specifications_____ SpecificatReplaced_by______________________________________ %OS The seconds using the locale's alternative numeric symbols %t Any whitespace character %T The time (%H:%M:%S) %U The week number of the year (the first Sunday as the first day of week 1) as a decimal number (00 - 53). Leading zeros are permitted. %OU The week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols %w The weekday as a decimal number (0 [Sunday] - 6). Leading zeros are permitted. %Ow The weekday as a number (Sunday=0) using the locale's alternative numeric symbols %W The week number of the year (the first Monday as the first day of week 1) as a decimal number (00 - 53). Leading zeros are permitted. %OW The week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols %x The locale's appropriate date representation %Ex The locale's alternative date representation %EX The locale's alternative time representation %X The locale's appropriate time representation %y The year without century as a decimal number (00 - 99) %Ey The offset from the base year (%EC) in the locale's alternative representation %Oy The year without the century using the locale's alternative numeric symbols %Y The year with century as a decimal number %EY The locale's full alternative year representation (continued on next page) REF-612 strptime Table_REF-9_(Cont.)_strptime_Conversion_Specifications_____ SpecificatReplaced_by______________________________________ %%________%________________________________________________ Return Values x A pointer to the character following the last character parsed. NULL Indicates that an error occurred. The contents of the tm structure are undefined. Example #include #include #include #include #include #include #define NUM_OF_DATES 7 #define BUF_SIZE 256 /* This program takes a number of date and time strings and */ /* converts them into tm structs using strptime(). These tm */ /* structs are then passed to strftime() which will reverse the */ /* process. The resulting strings are then compared with the */ /* originals and if a difference is found then an error is */ /* displayed. */ REF-613 strptime main() { int count, i; char buffer[BUF_SIZE]; char *ret_val; struct tm time_struct; char dates[NUM_OF_DATES][BUF_SIZE] = { "Thursday 01 January 1970 00:08:20", "Tuesday 29 February 1972 08:26:40", "Tuesday 31 December 1991 23:59:59", "Wednesday 01 January 1992 00:00:00", "Sunday 03 May 1992 13:33:20", "Monday 04 May 1992 17:20:00", "Friday 15 May 1992 03:20:00"}; for (i = 0; i < NUM_OF_DATES; i++) { /* Convert to a tm structure */ ret_ val = strptime(dates[i], "%A %d %B %Y %T", &time_struct); /* Check the return value */ if (ret_val == (char *) NULL) { perror("strptime"); exit(EXIT_FAILURE); } /* Convert the time structure back to a formatted string */ count = strftime(buffer, BUF_ SIZE, "%A %d %B %Y %T", &time_struct); /* Check the return value */ if (count == 0) { perror("strftime"); exit(EXIT_FAILURE); } REF-614 strptime /* Check the result */ if (strcmp(buffer, dates[i]) != 0) { printf("Error: Converted string differs from the original\n"); } else { printf("Successfully converted <%s>\n", dates[i]); } } } Running the example program produces the following result: Successfully converted Successfully converted Successfully converted Successfully converted Successfully converted Successfully converted Successfully converted REF-615 strrchr _________________________________________________________________ strrchr Returns the address of the last occurrence of a given character in a null-terminated string. The terminating null character is considered to be part of the string. Format #include char *strrchr (const char *str, int character); Function Variants This function also has variants named _strrchr32 and _ strrchr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments str A pointer to a null-terminated character string. character An object of type int. Description See also strchr in this section. Return Values x The address of the last occurrence of the specified character. NULL Indicates that the character does not occur in the string. REF-616 strsep _________________________________________________________________ strsep Separates strings. Format #include char *strsep (char **stringp, char *delim); Function Variants This function also has variants named _strsep32 and _ strsep64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments stringp A pointer to a pointer to a character string. delim A pointer to a string containing characters to be used as delimeters. Description This function locates in stringp, the first occurrence of any character in delim (or the terminating '\0' character) and replaces it with a '\0'. The location of the next character after the delimiter character (or NULL, if the end of the string is reached) is stored in the stringp argument. The original value of the stringp argument is returned. You can detect an "empty" field; one caused by two adjacent delimiter characters, by comparing the location referenced by the pointer returned in the stringp argument to '\0'. The stringp argument is initially NULL, strsep returns NULL. REF-617 strsep Return Values x The address of the string pointed to by stringp. NULL Indicates that stringp is NULL. Example The following example uses strsep to parse a string, containing token delimited by white space, into an argument vector: char **ap, **argv[10], *inputstring; for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;) if (**ap != '\0') ++ap; REF-618 strspn _________________________________________________________________ strspn Returns the length of the prefix of a string that consists entirely of characters from a set of characters. Format #include size_t strspn (const char *str, const char *charset); Arguments str A pointer to a character string. If this string is a null string, 0 is returned. charset A pointer to a character string containing the characters for which the function will search. Description This function scans the characters in the string, stops when it encounters a character not found in charset, and returns the length of the string's initial segment formed by characters found in charset. Return Value x The length of the segment. REF-619 strstr _________________________________________________________________ strstr Locates the first occurrence in the string pointed to by s1 of the sequence of characters in the string pointed to by s2. Format #include char *strstr (const char *s1, const char *s2); Function Variants This function also has variants named _strstr32 and _ strstr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s1, s2 Pointers to character strings. Return Values Pointer A pointer to the located string. NULL Indicates that the string was not found. Example #include #include #include main() { static char lookin[]="that this is a test was at the end"; REF-620 strstr putchar('\n'); printf("String: %s\n", &lookin[0] ); putchar('\n'); printf("Addr: %s\n", &lookin[0] ); printf("this: %s\n", strstr( &lookin[0] ,"this") ); printf("that: %s\n", strstr( &lookin[0] , "that" ) ); printf("NULL: %s\n", strstr( &lookin[0], "" ) ); printf("was: %s\n", strstr( &lookin[0], "was" ) ); printf("at: %s\n", strstr( &lookin[0], "at" ) ); printf("the end: %s\n", strstr( &lookin[0], "the end") ); putchar('\n'); exit(0); } This example produces the following results: $ RUN STRSTR_EXAMPLE String: that this is a test was at the end Addr: that this is a test was at the end this: this is a test was at the end that: that this is a test was at the end NULL: that this is a test was at the end was: was at the end at: at this is a test was at the end the end: the end $ REF-621 strtod _________________________________________________________________ strtod Converts a given string to a double-precision number. Format #include double strtod (const char *nptr, char **endptr); Function Variants This function also has variants named _strtod32 and _ strtod64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the character string to be converted to a double-precision number. endptr The address of an object where the function can store the address of the first unrecognized character that terminates the scan. If endptr is a NULL pointer, the address of the first unrecognized character is not retained. Description This function recognizes an optional sequence of white- space characters (as defined by isspace), then an optional plus or minus sign, then a sequence of digits optionally containing a radix character, then an optional letter (e or E) followed by an optionally signed integer. The first unrecognized character ends the conversion. The string is interpreted by the same rules used to interpret floating constants. The radix character is defined the program's current locale (category LC_NUMERIC). REF-622 strtod This function returns the converted value. For strtod, overflows are accounted for in the following manner: o If the correct value causes an overflow, HUGE_VAL (with a plus or minus sign according to the sign of the value) is returned and errno is set to ERANGE. o If the correct value causes an underflow, 0 is returned and errno is set to ERANGE. If the string starts with an unrecognized character, then the conversion is not performed, *endptr is set to nptr, a 0 value is returned, and errno is set to EINVAL.) Return Values x The converted string. 0 Indicates the conversion could not be performed. errno is set to one of the following: o EINVAL - No conversion could be performed. o ERANGE - The value would cause an underflow. o ENOMEM - Not enough memory available for internal conversion buffer. (+/-)HUGE_VAL Indicates overflow. errno is set to ERANGE. REF-623 strtok _________________________________________________________________ strtok Locates text tokens in a given string. The text tokens are delimited by one or more characters from a separator string that you specify. This function keeps track of its position in the string between calls and, as successive calls are made, the function works through the string, identifying the text token following the one identified by the previous call. Format #include char *strtok (char *s1, const char *s2); Function Variants This function also has variants named _strtok32 and _ strtok64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s1 On the first call, a pointer to a string containing 0 or more text tokens. On all subsequent calls for that string, a NULL pointer. s2 A pointer to a separator string consisting of one or more characters. The separator string may differ from call to call. Description A token in s1 starts at the first character that is not a character in the separator string s2 and ends either at the end of the string or at (but not including) a separator character. REF-624 strtok The first call to the strtok function returns a pointer to the first character in the first token and writes a null character into s1 immediately following the returned token. Each subsequent call (with the value of the first argument remaining NULL) returns a pointer to a subsequent token in the string originally pointed to by s1. When no tokens remain in the string, the strtok function returns a NULL pointer. (This can occur on the first call to strtok if the string is empty or contains only separator characters.) Since strtok inserts null characters into s1 to delimit tokens, s1 cannot be a const object. Return Values x A pointer to the first character of a token. NULL Indicates that there are no tokens remaining in s1. Examples 1.#include #include main() { static char str[] = "...ab..cd,,ef.hi"; printf("|%s|\n", strtok(str, ".")); printf("|%s|\n", strtok(NULL, ",")); printf("|%s|\n", strtok(NULL, ",.")); printf("|%s|\n", strtok(NULL, ",.")); } Running this example program produces the following results: $ RUN STRTOK_EXAMPLE1 |ab| |.cd| |ef| |hi| $ REF-625 strtok 2. #include #include main() { char *ptr, string[30]; /* The first character not in the string "-" is "A". The */ /* token ends at "C. */ strcpy(string, "ABC"); ptr = strtok(string, "-"); printf("|%s|\n", ptr); /* Returns NULL because no characters not in separator */ /* string "-" were found (i.e. only separator characters */ /* were found) */ strcpy(string, "-"); ptr = strtok(string, "-"); if (ptr == NULL) printf("ptr is NULL\n"); } Running this example program produces the following results: $ RUN STRTOK_EXAMPLE2 |abc| ptr is NULL $ REF-626 strtol _________________________________________________________________ strtol Converts strings of ASCII characters to the appropriate numeric values. Format #include long int strtol (const char *nptr, char **endptr, int base); Function Variants This function also has variants named _strtol32 and _ strtol64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the character string to be converted to a long. endptr The address of an object where the function can store a pointer to the first unrecognized character encountered in the conversion process (that is, the character that follows the last character in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. REF-627 strtol Description This function recognizes strings in various formats, depending on the value of the base. This function ignores any leading white-space characters (as defined by isspace in ) in the given string. It recognizes an optional plus or minus sign, then a sequence of digits or letters that may represent an integer constant according to the value of the base. The first unrecognized character ends the conversion. Leading zeros after the optional sign are ignored, and 0x or 0X is ignored if the base is 16. If base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant: after the optional sign, a leading 0 indicates octal conversion, a leading 0x or 0X indicates hexadecimal conversion, and any other combination of leading characters indicates decimal conversion. Truncation from long to int can take place after assignment or by an explicit cast (arithmetic exceptions not withstanding). The function call atol (str) is equivalent to strtol (str, (char**)NULL, 10). Return Values x The converted value. LONG_MAX or LONG_MIN Indicates that the converted value would cause an overflow. 0 Indicates that the string starts with an unrecognized character or that the value for base is invalid. If the string starts with an unrecognized character, *endptr is set to nptr. REF-628 strtoq, strtoll (Alpha only) _________________________________________________________________ strtoq, strtoll (Alpha only) Converts strings of ASCII characters to the appropriate numeric values. strtoll is a synonym for strtoq. Format #include __int64 strtoq (const char *nptr, char **endptr, int base); __int64 strtoll (const char *nptr, char **endptr, int base); Function Variants This function also has variants named _strtoq32/_strtoll32 and _strtoq64/_strtoll64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the character string to be converted to an __int64. endptr The address of an object where the function can store a pointer to the first unrecognized character encountered in the conversion process (that is, the character that follows the last character in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. REF-629 strtoq, strtoll (Alpha only) Description This function recognizes strings in various formats, depending on the value of the base. This function ignores any leading white-space characters (as defined by isspace in ) in the given string. It recognizes an optional plus or minus sign, then a sequence of digits or letters that may represent an integer constant according to the value of the base. The first unrecognized character ends the conversion. Leading zeros after the optional sign are ignored, and 0x or 0X is ignored if the base is 16. If base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant: after the optional sign, a leading 0 indicates octal conversion, a leading 0x or 0X indicates hexadecimal conversion, and any other combination of leading characters indicates decimal conversion. The function call atoq (str) is equivalent to strtoq (str, (char**)NULL, 10). Return Values x The converted value. __INT64_MAX or Indicates that the converted value __INT64_MIN would cause an overflow. 0 Indicates that the string starts with an unrecognized character or that the value for base is invalid. If the string starts with an unrecognized character, *endptr is set to nptr. REF-630 strtoul _________________________________________________________________ strtoul Converts the initial portion of the string pointed to by nptr to an unsigned long integer. Format #include unsigned long int strtoul (const char *nptr, char **endptr, int base); Function Variants This function also has variants named _strtoul32 and _ strtoul64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the character string to be converted to an unsigned long. endptr The address of an object where the function can store a pointer to a pointer to the first unrecognized character encountered in the conversion process (that is, the character that follows the last character in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. Leading zeros after the optional sign are ignored, and 0x or 0X is ignored if the base is 16. If the base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant: after the optional sign, a leading 0 indicates octal conversion, a leading 0x or 0X indicates hexadecimal conversion, and any other combination of leading characters indicates decimal conversion. REF-631 strtoul Return Values x The converted value. 0 Indicates that the string starts with an unrecognized character or that the value for base is invalid. If the string starts with an unrecognized character, *endptr is set to nptr. ULONG_MAX Indicates that the converted value would cause an overflow. REF-632 strtouq, strtoull (Alpha only) _________________________________________________________________ strtouq, strtoull (Alpha only) Converts the initial portion of the string pointed to by nptr to an unsigned __int64 integer. strtoull is a synonym for strtouq. Format #include unsigned __int64 strtouq (const char *nptr, char **endptr, int base); unsigned __int64 strtoull (const char *nptr, char **endptr, int base); Function Variants This function also has variants named _strtouq32/_ strtoull32 and _strtouq64/_strtoull64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the character string to be converted to an unsigned __int64. endptr The address of an object where the function can store a pointer to a pointer to the first unrecognized character encountered in the conversion process (that is, the character that follows the last character in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. Leading zeros after the optional sign are ignored, and 0x or 0X is ignored if the base is 16. REF-633 strtouq, strtoull (Alpha only) If the base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant: after the optional sign, a leading 0 indicates octal conversion, a leading 0x or 0X indicates hexadecimal conversion, and any other combination of leading characters indicates decimal conversion. Return Values x The converted value. 0 Indicates that the string starts with an unrecognized character or that the value for base is invalid. If the string starts with an unrecognized character, *endptr is set to nptr. __UINT64_MAX Indicates that the converted value would cause an overflow. REF-634 strxfrm _________________________________________________________________ strxfrm Changes a string such that the changed string can be passed to the strcmp function and produce the same result as passing the unchanged string to the strcoll function. Format #include size_t strxfrm (char *s1, const char *s2, size_t maxchar); Arguments s1, s2 Pointers to character strings. maxchar The maximum number of bytes (including the null terminator) to be stored in s1. Description This function transforms the string pointed to by s2, and stores the resulting string in the array pointed to by s1. No more than maxchar bytes, including the null terminator, are placed into the array pointed to by s1. If the value of maxchar is less than the required size to store the transformed string (including the terminating null), the contents of the array pointed to by s1 is indeterminate. In such a case, the function returns the size of the transformed string. If maxchar is 0, then s1 is allowed to be a NULL pointer, and the function returns the required size of the s1 array before making the transformation. The string comparison functions, strcoll and strcmp, can produce different results given the same two string to compare. The reason for this is that strcmp does a straightforward comparison of the code point values of the characters in the strings, whereas strcoll uses the locale information to do the comparison. Depending on the locale, REF-635 strxfrm the strcoll comparison can be a multipass operation, which is slower than strcmp. The purpose of the strxfrm function is to transform strings in such a way that if you pass two transformed strings to the strcmp function, the result is the same as passing the two original strings to the strcoll function. The strxfrm function is useful in applications that need to do a large number of comparisons on the same strings using strcoll. In this case, it might be more efficient (depending on the locale) to transform the strings once using strxfrm, and then do comparisons using strcmp. Return Value x Length of the resulting string pointed to by s1, not including the terminating null character. No return value is reserved for error indication. However, the function can set errno to EINVAL - The string pointed to by ws2 contains characters outside the domain of the collating sequence . Example /* This program verifies that two transformed strings when */ /* passed through strxfrm and then compared, provide the same */ /* result as if passed through strcoll without any */ /* transformation. #include #include #include #include #define BUFF_SIZE 256 REF-636 strxfrm main() { char string1[BUFF_SIZE]; char string2[BUFF_SIZE]; int errno; int coll_result; int strcmp_result; size_t strxfrm_result1; size_t strxfrm_result2; /* setlocale to French locale */ if (setlocale(LC_ALL, "fr_FR.ISO8859-1") == NULL) { perror("setlocale"); exit(EXIT_FAILURE); } /* collate string 1 and string 2 and store the result */ errno = 0; coll_result = strcoll("bcd", "abcz"); if (errno) { perror("strcoll"); exit(EXIT_FAILURE); } else { /* Transform the strings (using strxfrm) into string1 */ /* and string2 */ strxfrm_ result1 = strxfrm(string1, "bcd", BUFF_SIZE); if (strxfrm_result1 == ((size_t) - 1)) { perror("strxfrm"); exit(EXIT_FAILURE); } else if (strxfrm_result1 > BUFF_SIZE) { perror("\n** String is too long **\n"); exit(EXIT_FAILURE); } else { strxfrm_ REF-637 strxfrm result2 = strxfrm(string2, "abcz", BUFF_SIZE); if (strxfrm_result2 == ((size_t) - 1)) { perror("strxfrm"); exit(EXIT_FAILURE); } else if (strxfrm_result2 > BUFF_SIZE) { perror("\n** String is too long **\n"); exit(EXIT_FAILURE); } /* Compare the two transformed strings and verify */ /* that the result is the same as the result from */ /* strcoll on the original strings */ else { strcmp_ result = strcmp(string1, string2); if (strcmp_result == 0 && (coll_ result == 0)) { printf("\nReturn value from strcoll() and " "return value from strcmp() are both zero."); printf("\nThe program was successful\n\n"); } else if ((strcmp_result < 0) && (coll_ result < 0)) { printf("\nReturn value from strcoll() and " "return value from strcmp() are less than zero."); printf("\nThe program successful\n\n"); } else if ((strcmp_result > 0) && (coll_ result > 0)) { printf("\nReturn value from strcoll() and return " " value from strcmp() are greater than zero."); printf("\nThe program was successful\n\n"); } REF-638 strxfrm else { printf("** Error **\n"); printf("\nReturn values are not of the same type"); } } } } } Running the example program produces the following result: Return value from strcoll() and return value from strcmp() are less than zero. The program was successful REF-639 subwin _________________________________________________________________ subwin Creates a new subwindow with numlines lines and numcols columns starting at the coordinates (begin_y,begin_x) on the terminal screen. Format #include WINDOW *subwin (WINDOW *win, int numlines, int numcols, int begin_y, int begin_x); Arguments win A pointer to the parent window. numlines The number of lines in the subwindow. If numlines is 0, then the function sets that dimension to LINES - begin_y. To get a subwindow of dimensions LINES by COLS, use the following format: subwin (win, 0, 0, 0, 0) numcols The number of columns in the subwindow. If numcols is 0, then the function sets that dimension to COLS - begin_x. To get a subwindow of dimensions LINES by COLS, use the following format: subwin (win, 0, 0, 0, 0) begin_y A window coordinate at which the subwindow is to be created. begin_x A window coordinate at which the subwindow is to be created. REF-640 subwin Description When creating the subwindow, begin_y and begin_x are relative to the entire terminal screen. If either numlines or numcols is 0, then the subwin function sets that dimension to (LINES - begin_y) or (COLS - begin_x), respectively. The window pointed to by win must be large enough to contain the entire area of the subwindow. Any changes made to either window within the coordinates of the subwindow appear on both windows. Return Values window pointer A pointer to an instance of the structure window corresponding to the newly created subwindow. ERR Indicates an error. REF-641 swab _________________________________________________________________ swab Swaps bytes. Format #include void swab (const void *src, void *dest, ssize_t nbytes); Arguments src A pointer to the location of the string to copy. dest A pointer to where you want the results copied. nbytes The number of bytes to copy. Make this argument an even value. When it is an odd value, the swab function uses nbytes -1 instead. Description This function copies the number of bytes specified by nbytes from the location pointed to by src to the array pointed to by dest. The function then exchanges adjacent bytes. If a copy takes place between objects that overlap, the result is undefined. REF-642 swprintf _________________________________________________________________ swprintf Writes output to an array of wide characters under control of the wide-character format string. Format #include int swprintf (wchar_t *s, size_t n, const wchar_t *format, . . . ); Arguments s A pointer to the resulting wide-character sequence. n The maximum number of wide characters that can be written to an array pointed to by s, including a terminating null wide character. format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, the output sources can be omitted. Otherwise, the function calls must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Excess output pointers, if any, are ignored. REF-643 swprintf Description The swprintf function is equivalent to the fwprintf function, except that the first parameter specifies an array of wide characters instead of a stream. No more than n wide characters are written, including a terminating null wide character, which is always added (unless n is 0). See also fwprintf in this section. Return Values x The number of wide characters written, not counting the terminating null wide character. Negative value Indicates an error. Either n or more wide characters were requested to be written, or a conversion error occurred, in which case errno is set to EILSEQ. REF-644 swscanf _________________________________________________________________ swscanf Reads input from a wide-character string under control of the wide-character format string. Format #include int swscanf (const wchar_t *s, const wchar_t *format, . . . ); Arguments s A pointer to a wide-character string from which the input is to be obtained. format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose results correspond to conversion specifications given in the format specification. If no conversion specifications are given, you can omit the input pointers. Otherwise, the function calls must have exactly as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. REF-645 swscanf Description The swscanf function is equivalent to the fwscanf function, except that the first argument specifies a wide-character string rather than a stream. Reaching the end of the wide- character string is the same as encountering EOF for the fwscanf function. See also fwscanf in this section. Return Values x The number of input items assigned, sometimes fewer than provided for, or even 0 in the event of an early matching failure. EOF Indicates and error. An input failure occurred before any conversion. REF-646 sysconf _________________________________________________________________ sysconf Gets configurable system variables. Format #include long int sysconf (int name); Arguments name Specifies the system variable to be queried. Description This function provides a method for determining the current value of a configurable system limit or whether optional features are supported. You supply a symbolic constant in the name argument, and sysconf returns a value for the corresponding system variable: o The symbolic constants defined in the header file. o The system variables are defined in the and header files. Table REF-10 lists the system variables returned by the sysconf function, and the symbolic constants that you can supply as the name value. REF-647 sysconf Table_REF-10_SYSCONF_Argument_and_Return_Values__________________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-1______________________________________________________ ARG_MAX _SC_ARG_MAX The maximum length, in bytes, of the arguments for one of the exec functions, including environment data. CHILD_MAX _SC_CHILD_MAX The maximum number of simultaneous processes for each real user ID. CLK_TCK _SC_CLK_TCK The number of clock ticks per second. The value of CLK_TCK can be variable. Do not assume that CLK_TCK is a compile time constant. NGROUPS_MAX _SC_NGROUPS_MAX The maximum number of simultaneous supplementary group IDs for each process. OPEN_MAX _SC_OPEN_MAX The maximum number of files that one process can have open at one time. STREAM_MAX _SC_STREAM_MAX The number of streams that one process can have open at one time. TZNAME_MAX _SC_TZNAME_MAX The maximum number of bytes supported for the name of a time zone (not the length of the TZ environmental variable). _POSIX_JOB_CONTROL _SC_JOB_CONTROL This variable has a value of 1 if the system supports job control; otherwise, -1 is returned. (continued on next page) REF-648 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-1______________________________________________________ _POSIX_SAVED_IDS _SC_SAVED_IDS This variable has a value of 1 if each process has a saved set user ID and a saved set group ID; otherwise, -1 is returned. _POSIX_VERSION _SC_VERSION The date of approval of the most current version of the POSIX-1 standard that the system supports. The date is a 6-digit number, with the first 4 digits signifying the year and the last 2 digits the month. If_POSIX_VERSION is not defined, -1 is returned. Different versions of the POSIX-1 standard are periodically approved by the IEEE Standards Board, and the date of approval is used to distinguish between different versions. _________________________________________________________________ ISO_POSIX-2______________________________________________________ BC_BASE_MAX _SC_BC_BASE_MAX The maximum value allowed for the obase variable with the bc command. BC_DIM_MAX _SC_BC_DIM_MAX The maximum number of elements permitted in an array by the bc command. (continued on next page) REF-649 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-2______________________________________________________ BC_SCALE_MAX _SC_BC_SCALE_ The maximum value allowed MAX for the scale variable with the bc command. BC_STRING_MAX _SC_BC_STRING_ The maximum length of MAX string constants accepted by the bc command. COLL_WEIGHTS_MAX _SC_COLL_ The maximum number of WEIGHTS_MAX weights that can be assigned to an entry in the LC_COLLATE locale- dependent information in a locale definition file. EXPR_NEST_MAX _SC_EXPR_NEST_ The maximum number of MAX expressions that you can nest within parentheses by the expr command. LINE_MAX _SC_LINE_MAX The maximum length, in bytes, of a command input line (either standard input or another file) when the utility is described as processing text files. The length includes room for the trailing newline character. (continued on next page) REF-650 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-2______________________________________________________ RE_DUP_MAX _SC_RE_DUP_MAX The maximum number of repeated occurrences of a regular expression permitted when using the interval notation arguments, such as the m and n arguments with the ed command. _POSIX2_CHAR_TERM _SC_2_CHAR_TERM This variable has a value of 1 if the system supports at least one terminal type; otherwise, -1 is returned. _POSIX2_C_BIND _SC_2_C_BIND This variable has a value of 1 if the system supports the C language binding option; otherwise, -1 is returned. _POSIX2_C_DEV _SC_2_C_DEV This variable has a value of 1 if the system supports the optional C Language Development Utilities from the ISO POSIX-2 standard; otherwise, -1 is returned. _POSIX2_C_VERSION _SC_2_C_VERSION Integer value indicating the version of the ISO POSIX-2 standard (C language binding). It changes with each new version of the ISO POSIX-2 standard. (continued on next page) REF-651 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-2______________________________________________________ _POSIX2_VERSION _SC_2_VERSION Integer value indicating the version of the ISO POSIX-2 standard (Commands). It changes with each new version of the ISO POSIX-2 standard. _POSIX2_FORT_DEV _SC_2_FORT_DEV The variable has a value of 1 if the system supports the FORTRAN Development Utilities Option from the ISO POSIX-2 standard; otherwise, -1 is returned. _POSIX2_FORT_RUN _SC_2_FORT_RUN The variable has a value of 1 if the system supports the FORTRAN Runtime Utilities Option from the ISO POSIX-2 standard; otherwise, -1 is returned. _POSIX2_LOCALEDEF _SC_2_LOCALEDEF The variable has a value of 1 if the system supports the creation of new locales with the localedef command; otherwise, -1 is returned. (continued on next page) REF-652 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ ISO_POSIX-2______________________________________________________ _POSIX2_SW_DEV _SC_2_SW_DEV The variable has a value of 1 if the system supports the Software Development Utilities Option from the ISO POSIX-2 standard; otherwise, -1 is returned. _POSIX2_UPE _SC_2_UPE The variable has a value of 1 if the system supports the User Portability Utilities Option; otherwise, -1 is returned. _________________________________________________________________ POSIX_1003.1c-1995_______________________________________________ _POSIX_THREADS _SC_THREADS This variable has a value of 1 if the system supports POSIX threads; otherwise, -1 is returned. _POSIX_THREAD_ATTR_ _SC_THREAD_ This variable has a value STACKSIZE ATTR_STACKSIZE of 1 if the system supports the POSIX threads stack size attribute; otherwise, -1 is returned. _POSIX_THREAD_ _SC_THREAD_ The 1003.1c implementation PRIORITY_SCHEDULING PRIORITY_ supports the realtime SCHEDULING scheduling functions. _POSIX_THREAD_SAFE_ _SC_THREAD_ TRUE if the implementation FUNCTIONS SAFE_FUNCTIONS supports the thread-safe ANSI C functions in POSIX 1003.1c. (continued on next page) REF-653 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ POSIX_1003.1c-1995_______________________________________________ PTHREAD_DESTRUCTOR_ _SC_THREAD_ When a thread terminates, ITERATIONS DESTRUCTOR_ DECthreads iterates through ITERATIONS all non-NULL thread- specific data values in the thread, and calls a registered destructor routine (if any) for each. It is possible for a destructor routine to create new values for one or more thread-specific data keys. In that case, DECthreads goes through the entire process again. _SC_THREAD_DESTRUCTOR_ ITERATIONS is the maximum number of times the implementation loops before it terminates the thread even if there are still non-NULL values. PTHREAD_KEYS_MAX _SC_THREAD_ The maximum number of KEYS_MAX thread-specific data keys that an application can create. (continued on next page) REF-654 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ POSIX_1003.1c-1995_______________________________________________ PTHREAD_STACK_MIN _SC_THREAD_ The minimum allowed size of STACK_MIN a stack for a new thread. Any lower value specified for the "stacksize" thread attribute is rounded up. UINT_MAX _SC_THREAD_ The maximum number of THREADS_MAX threads an application is allowed to create. Since DECthreads does not enforce any fixed limit, this value is -1. _________________________________________________________________ X/Open___________________________________________________________ _XOPEN_VERSION _SC_XOPEN_ An integer indicating the VERSION most current version of the X/OPEN standard that the system supports. PASS_MAX _SC_PASS_MAX Maximum number of significant bytes in a password (not including terminating null). XOPEN_CRYPT _SC_XOPEN_CRYPT This variable has a value of 1 if the system supports the X/Open Encryption Feature Group; otherwise, -1 is returned. (continued on next page) REF-655 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ X/Open___________________________________________________________ XOPEN_ENH_I18N _SC_XOPEN_ENH_ This variable has a value I18N of 1 if the system supports the X/Open enhanced Internationalization Feature Group; otherwise, -1 is returned. XOPEN_SHM _SC_XOPEN_SHM This variable has a value of 1 if the system supports the X/Open Shared Memory Feature Group; otherwise, -1 is returned. _________________________________________________________________ X/Open_Extended__________________________________________________ ATEXIT_MAX _SC_ATEXIT_MAX The maximum number of functions that you can register with atexit per process. PAGESIZE _SC_PAGESIZE Size in bytes of a page. PAGE_SIZE _SC_PAGE_SIZE Same as PAGESIZE. If either PAGESIZE or PAGE_SIZE is defined, the other is defined with the same value. IOV_MAX _SC_IOV_MAX Maximum number of iovec structures that one process has available for use with readv or writev. (continued on next page) REF-656 sysconf Table_REF-10_(Cont.)_SYSCONF_Argument_and_Return_Values__________ Symbolic System Variable Constant for Returned_____________name_____________Meaning____________________ X/Open_Extended__________________________________________________ XOPEN_UNIX _SC_XOPEN_UNIX This variable has a value of 1 if the system supports the X/Open CAE Specification, August 1994, System Interfaces and Headers, Issue 4, Version 2, (ISBN: 1-85912-037-7, C435); otherwise, -1 is ______________________________________returned.__________________ Return Values x The current variable value on the system. The value does not change during the lifetime of the calling process. -1 Indicates an error. If the value of the name argument is invalid, errno is set to indicate the error. If the value of the name argument is undefined, errno is unchanged. REF-657 system _________________________________________________________________ system Passes a given string to the host environment to be executed by a command processor. This function is nonreentrant. Format #include int system (const char *string); Argument string A pointer to the string to be executed. If string is NULL, a nonzero value is returned. The string is a DCL command, not the name of an image. To execute an image, use one of the exec routines. Description This function spawns a subprocess and executes the command specified by string in that subprocess. The system function waits for the subprocess to complete before returning the subprocess status as the return value of the function. The subprocess is spawned within the system call by a call to vfork. Because of this, a call to system should not be made after a call to vfork and before the corresponding call to an exec function. For OpenVMS Version 7.0 and higher systems, if you include and compile with the _POSIX_EXIT feature-test macro set, then the system function returns the status as if it called waitpid to wait for the child. Therefore, use the WIFEXITED and WEXITSTATUS macros to retrieve the exit status in the range of 0 to 255. You set the _POSIX_EXIT feature-test macro by using /DEFINE=_POSIX_EXIT or #define _POSIX_EXIT at the top of your file, before any file inclusions. REF-658 system Return Values nonzero value If string is NULL, a value of 1 is returned, indicating that the system function is supported. If string is not NULL, the value is the subprocess OpenVMS return status. Example #include #include #include /* write, close */ #include /* Creat */ main() { int status, fd; /* Creat a file we are sure is there */ fd = creat("system.test", 0); write(fd, "this is an example of using system", 34); close(fd); if (system(NULL)) { status = system("DIR/NOHEAD/NOTRAIL/SIZE SYSTEM.TEST"); printf("system status = %d\n", status); } else printf("system() not supported.\n"); } Running this example program produces the following result: DISK3$:[JONES.CRTL.2059.SRC]SYSTEM.TEST;1 1 system status = 1 REF-659 tan _________________________________________________________________ tan Returns a double value that is the tangent of its radian argument. Format #include double tan (double x); Argument x A radian expressed as a real number. Return Values n tan(x) HUGE_VAL If x is a singular point ( . . . -3/2, -/2, /2 . . . ) REF-660 tanh _________________________________________________________________ tanh Returns a double value that is the hyperbolic tangent of its double argument. Format #include double tanh (double x); Argument x A real number. Return Values n The hyperbolic tangent of the argument. HUGE_VAL Indicates that the argument is too large; errno is set to ERANGE. REF-661 telldir _________________________________________________________________ telldir Returns the current location associated with a specified directory stream. Performs operations on directories. Format #include long int telldir (DIR *dir_pointer); Arguments dir_pointer A pointer to the DIR structure of an open directory. Description This function returns the current location associated with the specified directory stream. Return Values x The current location. -1 Indicates an error and is further specified in the global errno. REF-662 tempnam _________________________________________________________________ tempnam Constructs the name for a temporary file. Format #include char *tempnam (const char *directory, const char *prefix); Arguments directory A pointer to the pathname of the directory where you want to create a file. prefix A pointer to an initial character sequence of the filename. The prefix argument can be null, or it can point to a string of up to five characters used as the first characters of the temporary filename. Description This function generates filenames for temporary files. It allows you to control the choice of a directory. If the directory argument is null or points to a string that is not a pathname for an appropriate directory, the pathname defined as P_tmpdir in the header file is used. You can bypass the selection of a pathname by providing the TMPDIR environment variable in the user environment. The value of the TMPDIR variable is a pathname for the desired temporary file directory. Use the prefix argument to specify a prefix of up to 5 characters for the temporary filename. The tempnam function returns a pointer to the generated pathname, suitable for use in a subsequent call to the free function. See also free in this section. REF-663 tempnam ________________________ Note ________________________ In contrast to tmpnam, tempnam does not have to generate a different file name on each call. tempnam generates a new file name only if the file with the specified name exists. If you need a unique filename on each call, use tmpnam instead of tempnam. ______________________________________________________ Return Values x A pointer to the generated pathname, suitable for use in a subsequent call to the free function. NULL An error occurred; errno is set to indicate the error. REF-664 time _________________________________________________________________ time Returns the time (expressed as Universal Coordinated Time) elapsed since 00:00:00, January 1, 1970, in seconds. Format #include time_t time (time_t *time_location); Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Argument time_location Either NULL or a pointer to the place where the returned time is also stored. The time_t type is defined in the header file as follows: typedef unsigned long int time_t; Return Values x The time elapsed past the epoch. (time_t)(-1) Indicates an error. If the value of SYS$TIMEZONE_DIFFERENTIAL logical is wrong, the function will fail with errno set to EINVAL. REF-665 times _________________________________________________________________ times Passes back the accumulated times of the current process and its terminated child processes. Format #include clock_t times (struct tms *buffer); (OpenVMS V7.0 and higher) void times (tbuffer_t *buffer); (pre OpenVMS V7.0) Argument buffer A pointer to the terminal buffer. Description For both process and children times, the structure breaks down the time by user and system time. Since the OpenVMS system does not differentiate between system and user time, all system times are returned as 0. Accumulated CPU times are returned in 10-millisecond units. Only the accumulated times for child processes running a C main program or a program that calls VAXC$CRTL_INIT or DECC$CRTL_INIT are included. On OpenVMS Version 7.0 and higher systems, the times function returns the elapsed real time in clock ticks since an arbitrary reference time in the past (for example, system startup time). This reference time does not change from one times function call to another. The return value can overflow the possible range of type clock_t values. When times fails, it returns a value of -1. The Compaq C RTL uses system-boot time as its reference time. REF-666 times Return Values x The elapsed real time in clock ticks since system-boot time. (clock_t)(-1) Indicates an error. REF-667 tmpfile _________________________________________________________________ tmpfile Creates a temporary file that is opened for update. Format #include FILE *tmpfile (void); Description The file exists only for the duration of the process, or until the file is closed and is preserved across calls to vfork. Return Values x The address of a file pointer (defined in the header file). NULL Indicates an error. REF-668 tmpnam _________________________________________________________________ tmpnam Generates file names that can be safely used for a temporary file. Format #include char *tmpnam (char *name); Function Variants This function also has variants named _tmpnam32 and _ tmpnam64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Argument name A character string containing a name to use in place of file-name arguments in functions or macros. Successive calls to tmpnam with a null argument cause the function to overwrite the current name. Return Value x If the name argument is the null pointer value NULL, tmpnam returns the address of an internal storage area. If name is not NULL, then it is considered the address of an area of length L_tmpnam (defined in the header file). In this case, tmpnam returns the name argument as the result. REF-669 toascii _________________________________________________________________ toascii Converts its argument, an 8-bit ASCII character, to a 7-bit ASCII character. Format #include int toascii (char character); Argument character An object of type char. Return Value x A 7-bit ASCII character. REF-670 tolower _________________________________________________________________ tolower Converts a character to lowercase. Format #include int tolower (int character); Argument character An object of type int representable as an unsigned char or the value of EOF. For any other value, the behavior is undefined. Description If the argument represents an uppercase letter, and there is a corresponding lowercase letter, as defined by character type information in the program locale category LC_TYPE, the corresponding lowercase letter is returned. If the argument is not an uppercase character, it is returned unchanged. Return Value x The lowercase letter corresponding to the argument. Or, the unchanged argument, if it is not an uppercase character. REF-671 _tolower _________________________________________________________________ _tolower Converts an uppercase character to lowercase. Format #include int _tolower (int character); Argument character This argument must be an uppercase letter. Description The _tolower macro is equivalent to the tolower function except that its argument must be an uppercase letter (not lowercase, not EOF). The _tolower macro should not be used with arguments that contain side-effect operations. For instance, the following example will not return the expected result: d = _tolower (c++); Return Value x The lowercase letter corresponding to the argument. REF-672 touchwin _________________________________________________________________ touchwin Places the most recently edited version of the specified window on the terminal screen. Format #include int touchwin (WINDOW *win); Argument win A pointer to the window. Description This function is normally used only to refresh overlapping windows. Return Values OK Indicates success. ERR Indicates an error. REF-673 toupper _________________________________________________________________ toupper Converts a character to uppercase. Format #include int toupper (int character); Argument character An object of type int representable as an unsigned char or the value of EOF. For any other value, the behavior is undefined. Description If the argument represents a lowercase letter, and there is a corresponding uppercase letter, as defined by character type information in the program locale category LC_TYPE, the corresponding uppercase letter is returned. If the argument is not a lowercase character, it is returned unchanged. Return Value x The uppercase letter corresponding to the argument. Or, the unchanged argument, if the argument is not a lowercase character. REF-674 _toupper _________________________________________________________________ _toupper Converts a lowercase character to uppercase. Format #include int _toupper (int character); Argument character This argument must be an uppercase letter. Description The _toupper macro is equivalent to the toupper function except that its argument must be a lowercase letter (not uppercase, not EOF). The _toupper macro should not be used with arguments that contain side-effect operations. For instance, the following example will not return the expected result: d = _toupper (c++); Return Value x The uppercase letter corresponding to the argument. REF-675 towctrans _________________________________________________________________ towctrans Maps one wide character to another according to a specified mapping descriptor. Format #include wint_t towctrans (wint_t wc, wctrans_t desc); Arguments wc The wide character that you want to map. desc Description of the mapping obtained through a call to the wctrans function. Description This function maps the wide character specified in wc, using the mapping described by desc. The current setting of the LC_CTYPE category must be the same as during the call to the wctrans function that returned the value of desc. Return Values x The mapped value of the wc wide character, if this character exists in the mapping described by desc. Otherwise, the value of wc is returned. REF-676 towlower _________________________________________________________________ towlower Converts the argument, a wide-character code, to lowercase. If the argument is not an uppercase character, it is returned unchanged. Format #include (ISO C) #include (XPG4) int towlower (wint_t wc); Arguments wc An object of type wint_t representable as a valid wide character in the current locale, or the value of WEOF. For any other value, the behavior is undefined. Description If the argument is an uppercase wide character, the corresponding lowercase wide character (as defined in the LC_CTYPE category of the locale) is returned, if it exists. If it does not exist, the function returns the input argument unchanged. REF-677 towupper _________________________________________________________________ towupper Converts the argument, a wide character, to uppercase. If the argument is not a lowercase character, it is returned unchanged. Format #include (ISO C) #include (XPG4) int towupper (wint_t wc); Arguments wc An object of type wint_t representable as a valid wide character in the current locale, or the value of WEOF. For any other value, the behavior is undefined. Description If the argument is a lowercase wide character, the corresponing uppercase wide character (as defined in the LC_CTYPE category of the locale) is returned, if it exists. If it does not exist, the function returns the input argument unchanged. REF-678 truncate _________________________________________________________________ truncate Changes file length to a specified length in bytes. Format #include int truncate (const char *path, off_t length); Arguments path The name of a file that is to be truncated. This argument must point to a pathname that names a regular file for which the calling process has write permission. length The new length of the file in bytes. Description This function changes the length of a file to the size in bytes specified by the length argument. If the new length is less than the previous length, the function removes all data beyond length bytes from the specified file. All file data between the new End-of-File and the previous End-of-File is discarded. For stream files, if the new length is greater than the previous length, new file data between the previous End- of-File and the new End-of-File is added, consisting of all zeros. (For record files, it is not possible to extend the file in this manner.) Return Values 0 Indicates success. -1 An error occurred; errno is set to indicate the error. REF-679 ttyname _________________________________________________________________ ttyname Returns a pointer to the null-terminated name of the terminal device associated with file descriptor 0, the default input device (stdin). Format #include char *ttyname (void); Description This function is provided only for UNIX compatibility and has limited use in the OpenVMS environment. Return Values x A pointer to a null-terminated string. 0 Indicates that SYS$INPUT is not a TTY device. REF-680 tzset _________________________________________________________________ tzset Sets and accesses time-zone conversion. Format #include void tzset (void); extern char *tzname[]; extern long int timezone; extern int daylight; Description This function initializes time conversion information used by the ctime, localtime, mktime, strftime, and wcsftime functions. The tzset function sets the following external variables: o tzname is set as follows, where "std" is a 3-byte name for the standard time zone, and "dst" is a 3-byte name for the Daylight Savings Time zone: tzname[0] = "std" tzname[1] = "dst" o daylight is set to 0 if Daylight Savings Time should never be applied to the time zone. Otherwise, daylight is set to 1. o timezone is set to the difference between UTC and local standard time. The environment variable TZ specifies how tzset initializes time conversion information: o If TZ is absent from the environment, the implementation-dependent time-zone information is used, as follows: The best available approximation to local wall- clock time is used, as defined by the system logical REF-681 tzset SYS$LOCALTIME, which points to a tzfile format file that describes default time-zone rules. This system logical is set during the installation of OpenVMS Version 7.0 or higher to define a time-zone file based off the root directory SYS$COMMON:[SYS$ZONEINFO.SYSTEM].[1] o If TZ appears in the environment but its value is a null string, Coordinated Universal Time (UTC) is used (without leap-second correction). o If TZ appears in the environment and its value is not a null string, the value has one of three formats, as described in Table REF-11. Table_REF-11_Time-Zone_Initialization_Rules________________ TZ_Format______Meaning_____________________________________ : UTC is used. (continued on next page) ____________________ [1] The Compaq C RTL uses a public-domain, time-zone handling package that puts time-zone conversion rules in easily accessible and modifiable files. These files reside in the directory SYS$COMMON:[SYS$ZONEINFO.SYSTEM.SOURCES]. The time-zone compiler zic converts these files to a special format described by the header file. The converted files are created with a root directory of SYS$COMMON:[SYS$ZONEINFO.SYSTEM], which is pointed to by the SYS$TZDIR system logical. This format is readable by the C library functions that handle time-zone information. For example, in the eastern United Stated, SYS$LOCALTIME is defined to be SYS$COMMON:[SYS$ZONEINFO.SYSTEM.US]EASTERN. REF-682 tzset Table_REF-11_(Cont.)_Time-Zone_Initialization_Rules________ TZ_Format______Meaning_____________________________________ :pathname The characters following the colon specify the pathname of a tzfile format file from which to read the time-conversion information. A pathname beginning with a slash (/) represents an absolute pathname; otherwise, the pathname is relative to the system time-conversion information directory specified by SYS$TZDIR, which by default is SYS$COMMON:[SYS$ZONEINFO.SYSTEM]. stdoffset[dst[offset]lue is first used as the pathname of a file (as described for the :pathname format) [,rule]] from which to read the time-conversion information. If that file cannot be read, the value is then interpreted as a direct specification of the time-conversion information, as follows: (continued on next page) REF-683 tzset Table_REF-11_(Cont.)_Time-Zone_Initialization_Rules________ TZ_Format______Meaning_____________________________________ std and dst-Three or more characters that are the designation for the time zone: o std-Standard time zone. Required. o dst-Daylight Savings Time zone. Optional. If dst is omitted, Daylight Savings Time does not apply. Uppercase and lowercase letters are explicitly allowed. Any characters are allowed, except the following: o digits o leading colon (:) o comma (,) o minus (-) o plus (+) o ASCII null character offset-The value added to the local time to arrive at UTC. The offset has the following format: hh[:mm[:ss]] In this format: o hh (hours) is a one-or two-digit value of 0-24. o mm (minutes) is a value of 0-59. (optional) o ss (seconds) is a value of 0-59. (optional) (continued on next page) REF-684 tzset Table_REF-11_(Cont.)_Time-Zone_Initialization_Rules________ TZ_Format______Meaning_____________________________________ The offset following std is required. If no offset follows dst, summer time is assumed, one hour ahead of standard time. You can use one or more digits; the value is always interpreted as a decimal number. If the time zone is preceded by a minus sign (-), the time zone is East of Greenwich; otherwise, it is West, which can also be indicated by a preceding plus sign (+). rule-Indicates when to change to and return from summer time. The rule has the form: start[/time], end[/time] Where: o start is the date when the change from standard time to summer time occurs. o end is the date for returning from summer time to standard time. (continued on next page) REF-685 tzset Table_REF-11_(Cont.)_Time-Zone_Initialization_Rules________ TZ_Format______Meaning_____________________________________ If start and end are omitted, the default is the US Daylight Saving Time start and end dates. The format for start and end must be one of the following: o Jn-The Julian day n (1 < n < 365). Leap days are not counted. That is, in all years, including leap years, February 28 is day 59 and March 1 is day 60. You cannot explicitly refer to February 29. o n-The zero based Julian day (0 < n < 365). Leap days are counted, making it possible to refer to February 29. o Mm.n.d-The nth d day of month m where: 0 < n < 5, 0 < d < 6, 1 < m < 12. When n is 5, it refers to the last d day of month m. Sunday is day 0. time-The time when, in current time, the change to or return from summer time occurs. The time argument has the same format as offset, except that you cannot use a leading minus (-) or plus (+) sign. If time is not specified, the default is 02:00:00. If no rule is present in the TZ specification, the rules used are those specified by the tzfile format file defined by the system logical SYS$POSIXRULES in the system time-conversion information directory, with the standard and summer time offsets from UTC replaced by those specified by the offset values in TZ. If TZ does not specify a tzfile format file and cannot be interpreted as a direct _______________specification,_UTC_is_used._________________ REF-686 tzset ________________________ Note ________________________ The UTC-based time functions, introduced in OpenVMS Version 7.0, had degraded performance compared with the non-UTC-based time functions. OpenVMS Version 7.1 added a cache for time-zone files to improve performance. The size of the cache is determined by the logical name DECC$TZ_CACHE_SIZE. To accommodate most countries changing the time twice per year, the default cache size is large enough to hold two time-zone files. ______________________________________________________ See also ctime, localtime, mktime, strftime, and wcsftime in this section. Sample TZ Specification 1.EST5EDT4,M4.1.0,M10.5.0 This sample TZ specification describes the rule defined in 1987 for the Eastern time zone in the US: o EST (Eastern Standard Time) is the designation for standard time, which is 5 hours behind UTC. o EDT (Eastern Daylight Time) is the designation for summer time, which is 4 hours behind UTC. EDT starts on the first Sunday in April and ends on the last Sunday in October. Because time was not specified in either case, the changes occur at the default time, which is 2:00 a.m. The start and end dates did not need to be specified, because they are the defaults. REF-687 ualarm _________________________________________________________________ ualarm Sets or changes the timeout of interval timers. Format #include useconds_t ualarm (useconds_t mseconds, useconds_t interval); Arguments mseconds Specifies a number of real time microseconds. interval Specifies the interval for repeating the timer. Description This function causes the SIGALRM signal to be generated for the calling process after the number of real-time microseconds specified by useconds has elapsed. When the interval argument is nonzero, repeated timeout notification occurs with a period in microseconds specified by interval. If the notification signal SIGALRM is not caught or is ignored, the calling process is terminated. If you call a combination of ualarm and setitimer functions, and the AST status is disabled, the return value is invalid. If you call a combination of ualarm and setitimer functions, and the AST status is enabled, the return value is valid. This is because you cannot invoke an AST handler to clear the previous value of the timer when ASTs are disabled or invoked from a handler that was invoked at AST level. REF-688 ualarm ________________________ Note ________________________ Interactions between ualarm and either alarm, or sleep are unspecified. ______________________________________________________ See also setitimer in this section. Return Values n The number of microseconds remaining from the previous ualarm or setitimer call. 0 No timeouts are pending or ualarm not previously called. -1 Indicates an error. REF-689 umask _________________________________________________________________ umask Creates a file protection mask that is used when a new file is created, and returns the previous mask value. Format #include mode_t umask (mode_t mode_complement); Argument mode_complement Shows which bits to turn off when a new file is created. See the description of chmod to determine what the bits represent. Description Initially, the file protection mask is set from the current process's default file protection. This is done when the C main program starts up or when DECC$CRTL_INIT (or VAXC$CRTL_INIT) is called. You can change this for all files created by your program by calling umask or you can use chmod to change the file protection on individual files. The file protection of a file created by open or creat is the bitwise AND of the open and creat mode argument with the complement of the value passed to umask on the previous call. ________________________ Note ________________________ The way to create files with OpenVMS RMS default protections using the UNIX system-call functions umask, mkdir, creat, and open is to call mkdir, creat, and open with a file-protection mode argument of 0777 in a program that never specifically calls umask. These default protections include correctly establishing protections based on ACLs, previous versions of files, and so on. In programs that do vfork/exec calls, the new process image inherits whether umask has ever been called or REF-690 umask not from the calling process image. The umask setting and whether the umask function has ever been called are both inherited attributes. ______________________________________________________ Return Value x The old mask value. REF-691 uname _________________________________________________________________ uname Gets system identification information. Format #include int uname (struct utsname *name); Arguments name The current system identifier. Description This function stores null-terminated strings of information identifying the current system into the structure referenced by the name argument. The utsname structure is defined in the header file and contains the following members: sysname Name of the operating system implementation nodename Network name of this machine release Release level of the operating system version Version level of the operating system machine Machine hardware platform Return Values 0 Indicates success. -1 Indicates an error; errno or vaxc$errno is set as appropriate. REF-692 ungetc _________________________________________________________________ ungetc Pushes a character back into the input stream and leaves the stream positioned before the character. Format #include int ungetc (int character, FILE *file_ptr); Arguments character A value of type int. file_ptr A file pointer. Description When using this function, the character is pushed back onto the file indicated by file_ptr. One pushback is guaranteed, even if there has been no previous activity on the file. The fseek function erases all memory of pushed-back characters. The pushed-back character is not written to the underlying file. If the character to be pushed back is EOF, the operation fails, the input stream is left unchanged, and EOF is returned. See also fseek and getc in this section. Return Values x The push-back character. EOF Indicates it cannot push the character back. REF-693 ungetwc _________________________________________________________________ ungetwc Pushes a wide character back into the input stream. Format #include wint_t ungetwc (wint_t wc, FILE *file_ptr); Arguments wc A value of type wint_t. file_ptr A file pointer. Description When using this function, the wide character is pushed back onto the file indicated by file_ptr. One push-back is guaranteed, even if there has been no previous activity on the file. If a file positioning function (such as fseek) is called before the pushed back character is read, the bytes representing the pushed back character are lost. If the character to be pushed back is WEOF, the operation fails, the input stream is left unchanged, and WEOF is returned. See also getwc in this section. Return Values x The push-back character. REF-694 ungetwc WEOF Indicates that the function cannot push the character back. errno is set to one of the following: o EBADF - The file descriptor is not valid. o EALREADY - Operation is already in progress on the same file. o EILSEQ - Invalid wide-character code detected. REF-695 utime _________________________________________________________________ utime Sets file access and modification times. Format #include int utime (const char *path, const struct utimbuf *times); Argument path A pointer to a file. times A null pointer or a pointer to a utimbuf structure. Description The utime function sets the access and modification times of the file named by the path argument. If times is a null pointer, the access and modification times of the file are set to the current time. To use utime in this way, the effective user ID of the process must match the owner of the file, or the process must have write permission to the file or have appropriate privileges. If times is not a null pointer, it is interpreted as a pointer to a utimbuf structure, and the access and modification times are set to the values in the specified structure. Only a process with an effective user ID equal to the user ID of the file or a process with appropriate privileges can use utime this way. The utimbuf structure is defined by the header. The times in the utimbuf structure are measured in seconds since the Epoch. Upon successful completion, utime marks the time of the last file status change, st_ctime, to be updated. See the header file. REF-696 utime __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, the stat, fstat, utime, and utimes functions have been enhanced to take advantage of the new file-system support for POSIX-compliant file timestamps. This support is available only on ODS-5 devices on OpenVMS Alpha systems beginning with a version of OpenVMS Alpha after Version 7.3. Before this change, the stat and fstat functions were setting the values of the st_ctime, st_mtime, and st_ atime fields based on the following file attributes: st_ctime - ATR$C_CREDATE (file creation time) st_mtime - ATR$C_REVDATE (file revision time) st_atime - was always set to st_mtime because no support for file access time was available Also, for the file-modification time, utime and utimes were modifying the ATR$C_REVDATE file attribute, and ignoring the file-access-time argument. After the change, for a file on an ODS-5 device, the stat and fstat functions set the values of the st_ ctime, st_mtime, and st_atime fields based on the following new file attributes: st_ctime - ATR$C_ATTDATE (last attribute modification time) st_mtime - ATR$C_MODDATE (last data modification time) st_atime - ATR$C_ACCDATE (last access time) If ATR$C_ACCDATE is zero, as on an ODS-2 device, the stat and fstat functions set st_atime to st_mtime. For the file-modification time, the utime and utimes functions modify both the ATR$C_REVDATE and ATR$C_MODDATE file attributes. For the file-access time, these functions modify the ATR$C_ACCDATE file attribute. Setting the ATR$C_MODDATE and ATR$C_ACCDATE file attributes on an ODS-2 device has no effect. For compatibility, the old behavior of stat, fstat, utime and utimes remains the default, regardless of the kind of device. REF-697 utime The new behavior must be explicitly enabled by defining the DECC$EFS_FILE_TIMESTAMPS logical name to "ENABLE" before invoking the application. Setting this logical does not affect the behavior of stat, fstat, utime and utimes for files on an ODS-2 device. ______________________________________________________ Return Values 0 Successful execution. REF-698 utime -1 Indicates an error. The function sets errno to one of the following values: The utime function will fail if: o EACCES - Search permission is denied by a component of the path prefix; or the times argument is a null pointer and the effective user ID of the process does not match the owner of the file and write access is denied. o ELOOP - Too many symbolic links were encountered in resolving path. o ENAMETOOLONG - The length of the path argument exceeds {PATH_MAX}, a path name component is longer than {NAME_MAX}, or a path name resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. o ENOENT - A component of path does not name an existing file, or path is an empty string. o ENOTDIR - A component of the path prefix is not a directory. o EPERM -The times argument is not a null pointer and the calling process' effective user ID has write-access to the file but does not match the owner of the file and the calling process does not have the appropriate privileges. o EROFS - The file system containing the file is read-only. REF-699 utimes _________________________________________________________________ utimes Sets file access and modification times. Format #include int utimes (const char *path, const struct timeval times[2]); Argument path A pointer to a file. times an array of timeval structures. The first array member represents the date and time of last access, and the second member represents the date and time of last modification. The times in the timeval structure are measured in seconds and microseconds since the Epoch, although rounding toward the nearest second may occur. Description The utimes function sets the access and modification times of the file pointed to by the path argument to the value of the times argument. The utimes function allows time specifications accurate to the microsecond. If the times argument is a null pointer, the access and modification times of the file are set to the current time. The effective user ID of the process must be the same as the owner of the file, or must have write access to the file or appropriate privileges to use this call in this manner. Upon completion, utimes marks the time of the last file status change, st_ctime, for update. __________________ Note (Alpha only) __________________ On OpenVMS Alpha systems, the stat, fstat, utime, and utimes functions have been enhanced to take advantage REF-700 utimes of the new file-system support for POSIX-compliant file timestamps. This support is available only on ODS-5 devices on OpenVMS Alpha systems beginning with a version of OpenVMS Alpha after Version 7.3. Before this change, the stat and fstat functions were setting the values of the st_ctime, st_mtime, and st_ atime fields based on the following file attributes: st_ctime - ATR$C_CREDATE (file creation time) st_mtime - ATR$C_REVDATE (file revision time) st_atime - was always set to st_mtime because no support for file access time was available Also, for the file-modification time, utime and utimes were modifying the ATR$C_REVDATE file attribute, and ignoring the file-access-time argument. After the change, for a file on an ODS-5 device, the stat and fstat functions set the values of the st_ ctime, st_mtime, and st_atime fields based on the following new file attributes: st_ctime - ATR$C_ATTDATE (last attribute modification time) st_mtime - ATR$C_MODDATE (last data modification time) st_atime - ATR$C_ACCDATE (last access time) If ATR$C_ACCDATE is zero, as on an ODS-2 device, the stat and fstat functions set st_atime to st_mtime. For the file-modification time, the utime and utimes functions modify both the ATR$C_REVDATE and ATR$C_MODDATE file attributes. For the file-access time, these functions modify the ATR$C_ACCDATE file attribute. Setting the ATR$C_MODDATE and ATR$C_ACCDATE file attributes on an ODS-2 device has no effect. For compatibility, the old behavior of stat, fstat, utime and utimes remains the default, regardless of the kind of device. The new behavior must be explicitly enabled by defining the DECC$EFS_FILE_TIMESTAMPS logical name to "ENABLE" before invoking the application. Setting REF-701 utimes this logical does not affect the behavior of stat, fstat, utime and utimes for files on an ODS-2 device. ______________________________________________________ Return Values 0 Successful execution. REF-702 utimes -1 Indicates an error. The file times do not change and the function sets errno to one of the following values: The utimes function will fail if: o EACCES - Search permission is denied by a component of the path prefix; or the times argument is a null pointer and the effective user ID of the process does not match the owner of the file and write access is denied. o ELOOP - Too many symbolic links were encountered in resolving path. o ENAMETOOLONG - The length of the path argument exceeds {PATH_MAX}, a path name component is longer than {NAME_MAX}, or a path name resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}. o ENOENT - A component of path does not name an existing file, or path is an empty string. o ENOTDIR - A component of the path prefix is not a directory. o EPERM -The times argument is not a null pointer and the calling process' effective user ID has write-access to the file but does not match the owner of the file and the calling process does not have the appropriate privileges. o EROFS - The file system containing the file is read-only. REF-703 unsetenv _________________________________________________________________ unsetenv Deletes all instances of the environment variable name from the environment list. Format #include void unsetenv (const char *name); Arguments name The environment variable to delete from the environment list. Description This function deletes all instances of the variable name pointed to by the name argument from the environment list. REF-704 usleep _________________________________________________________________ usleep Suspends execution for an interval. Format #include int usleep (unsigned int mseconds); Arguments mseconds The number of microseconds to suspend execution for. Description This function suspends the current process from execution for the number of microseconds specified by the mseconds argument. This argument must be less than 1,000,000. However, if its value is 0, then the call has no effect. There is one real-time interval timer for each process. The usleep function does not interfere with a previous setting of this timer. If the process set this timer before calling usleep and if the time specified by mseconds equals or exceeds the interval timer's prior setting, then the process is awakened shortly before the timer was set to expire. Return Values 0 Indicates success. -1 Indicates an error occurred; errno is set to EINVAL. REF-705 VAXC$CRTL_INIT _________________________________________________________________ VAXC$CRTL_INIT Allows you to call the Compaq C RTL from other languages or to use the Compaq C RTL when your main function is not in C. It initializes the run-time environment and establishes both an exit and condition handler. VAXC$CRTL_INIT is a synonym for DECC$CRTL_INIT. Either name invokes the same routine. Format #include void VAXC$CRTL_INIT(); Description The following example shows a Pascal program that calls the Compaq C RTL using the VAXC$CRTL_INIT function: On OpenVMS VAX systems: $ PASCAL EXAMPLE $ LINK EXAMPLE,SYS$LIBRARY:DECCRTL/LIB $ TY EXAMPLE.PAS PROGRAM TESTC(input, output); PROCEDURE VAXC$CRTL_INIT; extern; BEGIN VAXC$CRTL_INIT; END $ On OpenVMS Alpha systems: $ PASCAL EXAMPLE $ LINK EXAMPLE,SYS$LIBRARY:VAXCRTL/LIB $ TY EXAMPLE.PAS PROGRAM TESTC(input, output); PROCEDURE VAXC$CRTL_INIT; extern; BEGIN VAXC$CRTL_INIT; END $ REF-706 VAXC$CRTL_INIT A shareable image need only call this function if it contains a Compaq C function for signal handling, environment variables, I/O, exit handling, a default file protection mask, or if it is a child process that should inherit context. Although many of the initialization activities are performed only once, DECC$CRTL_INIT can safely be called multiple times. On OpenVMS VAX systems, DECC$CRTL_INIT establishes the Compaq C RTL internal OpenVMS exception handler in the frame of the routine that calls DECC$CRTL_ INIT each time DECC$CRTL_INIT is called. At least one frame in the current call stack must have that handler established for OpenVMS exceptions to get mapped to UNIX signals. REF-707 VAXC$ESTABLISH _________________________________________________________________ VAXC$ESTABLISH Used for establishing an OpenVMS exception handler for a particular routine. This function establishes a special Compaq C RTL exception handler in the routine that called it. This special handler catches all RTL-related exceptions that occur in later routines, and passes on all other exceptions to your handler. Format #include void VAXC$ESTABLISH (unsigned int (*exception_handler)(void *sigarr, void *mecharr)); Arguments exception_handler The name of the function that you want to establish as an OpenVMS exception handler. You pass a pointer to this function as the parameter to VAXC$ESTABLISH. sigarr A pointer to the signal array. mecharr A pointer to the mechanism array. Description VAXC$ESTABLISH must be used in place of LIB$ESTABLISH when programs use the Compaq C RTL routines setjmp or longjmp. See setjmp and longjmp, or sigsetjmp and siglongjmp in this section. You can only invoke the VAXC$ESTABLISH function from a Compaq C for OpenVMS function, because it relies on the allocation of data space on the run-time stack by the Compaq C compiler. Calling the OpenVMS system library routine LIB$ESTABLISH directly from a Compaq C function results in undefined behavior from the setjmp and longjmp functions. REF-708 VAXC$ESTABLISH To cause an OpenVMS exception to generate a UNIX style signal, user exception handlers must return SS$_RESIGNAL upon receiving any exception that they do not want to handle. Returning SS$_NORMAL prevents the generation of a UNIX style signal. UNIX signals are generated as if by an exception handler in the stack frame of the main C program. Not all OpenVMS exceptions correspond to UNIX signals. See Chapter 4 for more information on the interaction of OpenVMS exceptions and UNIX style signals. Calling VAXC$ESTABLISH with an argument of NULL cancels an existing handler in that routine. ________________________ Notes ________________________ o On OpenVMS Alpha systems, VAXC$ESTABLISH is implemented as a compiler built-in function, not as a Compaq C RTL function. (Alpha only) o On OpenVMS VAX systems, programs compiled with /NAMES=AS_IS should link against SYS$LIBRARY:DECCRTL.OLB to resolve the name VAXC$ESTABLISH, whether or not the program is compiled with the /PREFIX_LIBRARY_ENTRIES switch. This is a restriction in the implementation. (VAX only) ______________________________________________________ REF-709 va_arg _________________________________________________________________ va_arg Used for returning the next item in the argument list. Format #include (ANSI C) #include (DEC C Extension) type va_arg (va_list ap, type); Arguments ap A variable list containing the next argument to be obtained. type A data type that is used to determine the size of the next item in the list. An argument list can contain items of varying sizes, but the calling routine must determine what type of argument is expected since it cannot be determined at run time. Description This function interprets the object at the address specified by the list incrementor according to type. If there is no corresponding argument, the behavior is undefined. When using va_arg to write portable applications, include the header file (defined by the ANSI C standard), not the header file, and use va_ arg only in conjunction with other functions and macros defined in . For an example of argument-list processing using the functions and definitions, see Chapter 3, Example 3-6. REF-710 va_count _________________________________________________________________ va_count Returns the number of longwords (VAX only) or quadwords (Alpha only) in the argument list. Format #include (ANSI C) #include (DEC C Extension) void va_count (int *count); Argument count An integer variable name in which the number of longwords (VAX only) or quadwords (Alpha only) is returned. Description This function places the number of longwords (VAX only) or quadwords (Alpha only) in the argument list into count. The value returned in count is the number of longwords (VAX only) or quadwords (Alpha only) in the function argument block not counting the count field itself. If the argument list contains items whose storage requirements are a longword (VAX only) or quadword (Alpha only) of memory or less, the number in the count argument is also the number of arguments. However, if the argument list contains items that are longer than a longword (VAX only) or a quadword (Alpha only), count must be interpreted to obtain the number of arguments. Because a double is 8 bytes, it occupies two argument-list positions on OpenVMS VAX systems, and one argument-list position on OpenVMS Alpha systems. This function is specific to Compaq C for OpenVMS Systems and is not portable. REF-711 va_end _________________________________________________________________ va_end Finishes the or session. Format #include (ANSI C) #include (DEC C Extension) void va_end (va_list ap); Argument ap The object used to traverse the argument list length. You must declare and use the argument ap as shown in this format section. Description You can execute multiple traversals of the argument list, each delimited by va_start . . . va_end. The va_end function sets ap equal to NULL. When using this function to write portable applications, include the header file (defined by the ANSI C standard), not the header file, and use va_ end only in conjunction with other routines defined in . For an example of argument-list processing using the functions and definitions, see Chapter 3, Example 3-6. REF-712 va_start_1, va_start _________________________________________________________________ va_start_1, va_start Used for initializing a variable to the beginning of the argument list. Format #include (DEC C Extension) void va_start (va_list ap); void va_start_1 (va_list ap, int offset); Arguments ap An object pointer. You must declare and use the argument ap as shown in the format section. offset The number of bytes by which ap is to be incremented so that it points to a subsequent argument within the list (that is, not to the start of the argument list). Using a nonzero offset can initialize ap to the address of the first of the optional arguments that follow a number of fixed arguments. Description The va_start macro initializes the variable ap to the beginning of the argument list. The va_start_1 macro initializes ap to the address of an argument that is preceded by a known number of defined arguments. The printf function is an example of a Compaq C RTL function that contains a variable-length argument list offset from the beginning of the entire argument list. The variable-length argument list is offset by the address of the formatting string. When determining value of the offset argument used in va_ start_1 the implications of the OpenVMS calling standard must be considered. REF-713 va_start_1, va_start On OpenVMS VAX, most argument items are a longword. For example, OpenVMS VAX arguments of types char and short use a full longword of memory when they are present in argument lists. However, OpenVMS VAX arguments of type float use two longwords because they are converted to type double. On OpenVMS Alpha, each argument item is a quadword. ________________________ Note ________________________ When accessing argument lists, especially those passed to a subroutine (written in C) by a program written in another programming language, consider the implications of the OpenVMS calling standard. For more information about the OpenVMS calling standard, see the Compaq C User's Guide for OpenVMS Systems or the OpenVMS Calling Standard. ______________________________________________________ The preceding version of va_start and va_start_1 is specific to the Compaq C RTL, and is not portable. The following syntax describes the va_start macro in the header file, as defined in the ANSI C standard: Format #include (ANSI C) void va_start (va_list ap, parmN); Arguments ap An object pointer. You must declare and use the argument ap as shown in the format section. parmN The name of the last of the known fixed arguments. REF-714 va_start_1, va_start Description The pointer ap is initialized to point to the first of the optional arguments that follow parmN in the argument list. Always use this version of va_start in conjunction with functions that are declared and defined with function prototypes. Also use this version of va_start to write portable programs. For an example of argument-list processing using the functions and definitions, see Chapter 3, Example 3-6. REF-715 vfork _________________________________________________________________ vfork Creates an independent child process. This function is nonreentrant. Format #include int vfork (void); (_DECC_V4_SOURCE) pid_t vfork (void); (not _DECC_V4_SOURCE) Description This function provided by Compaq C for OpenVMS Systems differs from the fork function provided by other C implementations. Table REF-12 shows the two major differences. Table_REF-12_The_vfork_and_fork_Functions__________________ The_vfork_Function_______The_fork_Function_________________ Used with the exec Can be used without an exec functions. function for asynchronous processing. Creates an independent Creates an exact duplicate of the child parent process that branches at process that shares the point where vfork is called, some of as if the parent and the child the parent's are the same process at different characteristics._________stages_of_execution.______________ The vfork function provides the setup necessary for a subsequent call to an exec function. Although no process is created by vfork, it performs the following steps: o It saves the return address (the address of the vfork call) to be used later as the return address for the call to an exec function. o It saves the current context. REF-716 vfork o It returns the integer 0 the first time it is called (before the call to an exec function is made). After the corresponding exec function call is made, the exec function returns control to the parent process, at the point of the vfork call, and it returns the process ID of the child as the return value. Unless the exec function fails, control appears to return twice from vfork even though one call was made to vfork and one call was made to the exec function. The behavior of the vfork function is similar to the behavior of the setjmp function. Both vfork and setjmp establish a return address for later use, both return the integer 0 when they are first called to set up this address, and both pass back the second return value as though it were returned by them rather than by their corresponding exec or longjmp function calls. However, unlike setjmp, with vfork, all local automatic variables, even those with volatile-qualified type, can have indeterminate values if they are modified between the call to vfork and the corresponding call to an exec routine. Return Values 0 Indicates successful creation of the context. nonzero Indicates the process ID (PID) of the child process. -1 Indicates an error - failure to create the child process. REF-717 vfprintf _________________________________________________________________ vfprintf Prints formatted output based on an argument list. Format #include int vfprintf (FILE *file_ptr, const char *format, va_list arg); Arguments file_ptr A pointer to the file to which the output is directed. format A pointer to a string containing the format specification. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg A list of expressions whose resultant types correspond to the conversion specifications given in the format specifications. Description See the vprintf and vsprintf functions in this section. See Chapter 2 for information on format specifiers. Return Values x The number of bytes written. Negative value Indicates an output error. The function sets errno. For a list of possible errno values set, see fprintf in this section. REF-718 vfwprintf _________________________________________________________________ vfwprintf Writes output to the stream under control of the wide- character format string. Format #include int vfwprintf (FILE *stream, const wchar_t *format, va_list arg); Arguments stream A file pointer. format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg A variable list of the items needed for output. Description This function is equivalent to the fwprintf function, with the variable argument list replaced by the arg argument. Initialize arg with the va_start macro (and possibly with subsequent va_arg calls) from . If the stream pointed to by stream has no orientation, vfwprintf makes the stream wide-oriented. See also fwprintf in this section REF-719 vfwprintf Return Values n The number of wide characters written. REF-720 vfwprintf Negative value Indicates an error. The function sets errno to one of the following: o EILSEQ - Invalid character detected. o EINVAL - Insufficient arguments. o ENOMEM - Not enough memory available for conversion. o ERANGE - Floating-point calculations overflow. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This might indicate that conversion to a numeric value failed because of overflow. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-721 vfwprintf Examples The following example shows the use of the vfwprintf function in a general error reporting routine. #include #include #include void error(char *function_name, wchar_t *format, . . . ); { va_list args; va_start(args, format); /* print out name of function causing error */ fwprintf(stderr, L"ERROR in %s: ", function_name); /* print out remainder of message */ vfwprintf(stderr, format, args); va_end(args); } REF-722 vprintf _________________________________________________________________ vprintf Prints formatted output based on an argument list. This function is the same as the printf function except that instead of being called with a variable number of arguments, it is called with an argument list that has been initialized by the va_start macro (and possibly with subsequent va_arg calls) from . Format #include int vprintf (const char *format, va_list arg); Arguments format A pointer to the string containing the format specification. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg A variable list of the items needed for output. Description See the vfprintf and vsprintf functions this section. See Chapter 2 for information on format specifiers. Return Values x The number of bytes written. Negative value Indicates an output error. The function sets errno. For a list of possible errno values set, see fprintf in this section. REF-723 vswprintf _________________________________________________________________ vswprintf Writes output to the stream under control of the wide- character format string. Format #include int vswprintf (wchar_t *s, size_t n, const wchar_t *format, va_list arg); Arguments s A pointer to a multibyte character sequence. n The maximum number of bytes that comprise the multibyte character. format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg A variable list of the items needed for output. Description This function is equivalent to the swprintf function, with the variable argument list replaced by the arg argument. Initialize arg with the va_start macro, and possibly with subsequent va_arg calls. See also swprintf in this section. REF-724 vswprintf Return Values n The number of wide characters written. REF-725 vswprintf Negative value Indicates an error. The function sets errno to one of the following: o EILSEQ - Invalid character detected. o EINVAL - Insufficient arguments. o ENOMEM - Not enough memory available for conversion. o ERANGE - Floating-point calculations overflow. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This might indicate that conversion to a numeric value failed because of overflow. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-726 vwprintf _________________________________________________________________ vwprintf Writes output to an array of wide characters under control of the wide-character format string. Format #include int vwprintf (const wchar_t *format, va_list arg); Arguments format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg The variable list of items needed for output. Description This function is equivalent to the wprintf function, with the variable argument list replaced by the arg argument. Initialize arg with the va_start macro, and possibly with subsequent va_arg calls. The vwprintf function does not invoke the va_end macro. See also wprintf in this section. Return Values x The number of wide characters written, not counting the terminating null wide character. REF-727 vwprintf Negative value Indicates an error. Either n or more wide characters were requested to be written, or a conversion error occurred, in which case errno is set to EILSEQ. REF-728 vsprintf _________________________________________________________________ vsprintf Prints formatted output based on an argument list. This function is the same as the sprintf function except that instead of being called with a variable number of arguments, it is called with an argument list that has been initialized by va_start (and possibly with subsequent va_ arg calls). Format #include int vsprintf (char *str, const char *format, va_list arg); Arguments str A pointer to a string that will receive the formatted output. This string is assumed to be large enough to hold the output. format A pointer to a character string that contains the format specification. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. arg A list of expressions whose resultant types correspond to the conversion specifications given in the format specifications. Return Value x The number of bytes written. Negative value Indicates an output error occurred.The function sets errno. For a list of possible errno values set, see fprintf in this section. REF-729 wait _________________________________________________________________ wait Checks the status of the child process before exiting. A child process is terminated when the parent process terminates. Format #include pid_t wait (int *status); Argument status The address of a location to receive the final status of the terminated child. The child can set the status with the exit function and the parent can retrieve this value by specifying status. Description This function suspends the parent process until the final status of a terminated child is returned from the child. On OpenVMS Version 7.0 and higher systems, the wait function is equivalent to waitpid( 0, status, 0 ) if you include and compile with the _POSIX_EXIT feature- test macro set (either with /DEFINE=_POSIX_EXIT or with #define _POSIX_EXIT at the top of your file, before any file inclusions). REF-730 wait Return Values x The process ID (PID) of the terminated child. If more than one child process was created, wait will return the PID of the terminated child that was most recently created. Subsequent calls will return the PID of the next most recently created, but terminated, child. -1 No child process was spawned. REF-731 wait3 _________________________________________________________________ wait3 Waits for a child process to stop or terminate. Format #include pid_t wait3 (int *status_location, int options, struct rusage *resource_usage); Arguments status_location A pointer to a location that contains the termination status of the child process as defined in the header file. Beginning with OpenVMS Version 7.2, when compiled with the _VMS_WAIT macro defined, this function puts the OpenVMS completion code of the child process at the address specified in the status_location argument. options Flags that modify the behavior of the function. These flags are defined in the Description section. resource_usage The location of a structure that contains the resource utilization information for terminated child processes. Description This function suspends the calling process until the request is completed, and redefines it so that only the calling thread is suspended. The options argument modifies the behavior of the function. You can combine the flags for the options argument by specifying their bitwise inclusive OR. The flags are: REF-732 wait3 WNOWAIT Specifies that the process whose status is returned in status_location is kept in a waitable state. You can wait for the process again with the same results. WNOHANG Prevents the suspension of the calling process. If there are child processes that stopped or terminated, one is chosen and the waitpid function returns its process ID, as when you do not specify the WNOHANG flag. If there are no terminated processes (that is, if waitpid suspends the calling process without the WNOHANG flag), 0 (zero) is returned. Because you can never wait for process 0, there is no confusion arising from this return. WUNTRACED Specifies that the call return additional information when the child processes of the current process stop because the child process received a SIGTTIN, SIGTTOU, SIGSTOP, or SIGTSTOP signal. If the wait3 function returns because the status of a child process is available, the process ID of the child process is returned. Information is stored in the location pointed to by status_location, if this pointer is not null. The value stored in the location pointed to by status_ location is 0 (zero) only if the status is returned from a terminated child process that did one of the following: o Returned 0 from the main function. o Passed 0 as the status argument to the _exit or exit function. Regardless of the status_location value, you can define this information using the macros defined in the header file, which evaluate to integral expressions. In the following macro descriptions, the status_value argument is equal to the integer value pointed to by the status_ location argument: REF-733 wait3 WIFEXITED(status_ Evaluates to a nonzero value if value) status was returned for a child process that terminated normally. WEXITSTATUS(status_ If the value of WIFEXITED(status_ value) value) is nonzero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to the _exit or exit function, or to the value the child process returned from the main function. WIFSIGNALED(status_ Evaluates to nonzero value if status value) was returned for a child process that terminated due to the receipt of a signal that was not caught. WTERMSIG(status_ If the value of WIFSIGNALED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the termination of the child process. WIFSTOPPED(status_ Evaluates to a nonzero value if value) status was returned for a child process that is currently stopped. WSTOPSIG(status_ If the value of WIFSTOPPED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the child process to stop. WIFCONTINUED(status_ Evaluates to a nonzero value if value) status was returned for a child process that has continued. If the information stored at the location pointed to by status_location was stored there by a call to wait3 that specified the WUNTRACED flag, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) o WIFSTOPPED(*status_value) REF-734 wait3 o WIFCONTINUED(*status_value) If the information stored in the location pointed to by status_location resulted from a call to wait3 without the WUNTRACED flag specified, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) The wait3 function provides compatibility with BSD systems. The resource_usage argument points to a location that contains resource usage information for the child processes as defined in the header file. If a parent process terminates without waiting for all of its child processes to terminate, the remaining child processes is assigned a parent process ID equal to the process ID of the init process. See also exit, -exit, and init in this section. Return Values 0 Indicates success. There are no stopped or exited child processes, the WNOHANG option is specified. x The process_id of the child process. Status of a child process is available. REF-735 wait3 -1 Indicates an error; errno is set to one of the following values: o ECHILD - There are no child processes to wait for. o EINTR - Terminated by receipt of a signal caught by the calling process. o EFAULT - The status_location or resource_usage argument points to a location outside of the address space of the process. o EINVAL- The value of the options argument is not valid. REF-736 wait4 _________________________________________________________________ wait4 Waits for a child process to stop or terminate. Format #include pid_t wait4 (pid_t process_id, union wait *status_location, int options, struct rusage *resource_usage); Arguments status_location A pointer to a location that contains the termination status of the child process as defined in the header file. Beginning with OpenVMS Version 7.2, when compiled with the _VMS_WAIT macro defined, this function puts the OpenVMS completion code of the child process at the address specified in the status_location argument. process_id The child process or set of child processes. options Flags that modify the behavior of the function. These flags are defined in the Description section. resource_usage The location of a structure that contains the resource utilization information for terminated child processes. Description This function suspends the calling process until the request is completed. The process_id argument allows the calling process to gather status from a specific set of child processes, according to the following rules: REF-737 wait4 ___________________________________________________________ If the process_ id_is____________Then_status_is_requested__________________ Equal to -1 For any child process. In this respect, the waitpid function is equivalent to the wait function. Greater than 0 For a single child process and specifies _________________the_process_ID.___________________________ The wait4 function only returns the status of a child process from this set. The options argument to the wait4 function modifies the behavior of the function. You can combine the flags for the options argument by specifying their bitwise-inclusive OR. The flags are: WNOWAIT Specifies that the process whose status is returned in status_location is kept in a waitable state. You can wait for the process again with the same results. WNOHANG Prevents the suspension of the calling process. If there are child processes that stopped or terminated, one is chosen and the waitpid function returns its process ID, as when you do not specify the WNOHANG flag. If there are no terminated processes (that is, if waitpid suspends the calling process without the WNOHANG flag), 0 is returned. Because you can never wait for process 0, there is no confusion arising from this return. WUNTRACED Specifies that the call return additional information when the child processes of the current process stop because the child process received a SIGTTIN, SIGTTOU, SIGSTOP, or SIGTSTOP signal. If the wait4 function returns because the status of a child process is available, the process ID of the child process is returned. Information is stored in the location pointed to by status_location, if this pointer is not null. REF-738 wait4 The value stored in the location pointed to by status_ location is 0 only if the status is returned from a terminated child process that did one of the following: o Returned 0 from the main function. o Passed 0 as the status argument to the _exit or exit function. Regardless of the status_location value, you can define this information using the macros defined in the header file, which evaluate to integral expressions. In the following macro descriptions, status_value is equal to the integer value pointed to by status_location: WIFEXITED(status_ Evaluates to a nonzero value if value) status was returned for a child process that terminated normally. WEXITSTATUS(status_ If the value of WIFEXITED(status_ value) value) is nonzero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to the _exit or exit function, or to the value the child process returned from the main function. WIFSIGNALED(status_ Evaluates to nonzero value if status value) was returned for a child process that terminated due to the receipt of a signal that was not caught. WTERMSIG(status_ If the value of WIFSIGNALED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the termination of the child process. WIFSTOPPED(status_ Evaluates to a nonzero value if value) status was returned for a child process that is currently stopped. REF-739 wait4 WSTOPSIG(status_ If the value of WIFSTOPPED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the child process to stop. WIFCONTINUED(status_ Evaluates to a nonzero value if value) status was returned for a child process that has continued. If the information stored at the location pointed to by status_location was stored there by a call to wait4 that specified the WUNTRACED flag, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) o WIFSTOPPED(*status_value) o WIFCONTINUED(*status_value) If the information stored in the location pointed to by status_location resulted from a call to wait4 without the WUNTRACED flag specified, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) The wait4 function is similar to the wait3 function. However, the wait4 function waits for a specific child as indicated by the process_id argument. The resource_ usage argument points to a location that contains resource usage information for the child processes as defined in the header file. See also exit and _exit in this section. REF-740 wait4 Return Values 0 Indicates success. There are no stopped or exited child processes, the WNOHANG option is specified. x The process_id of the child process. Status of a child process is available. -1 Indicates an error; errno is set to one of the following values: o ECHILD - There are no child processes to wait for. o EINTR - Terminated by receipt of a signal caught by the calling process. o EFAULT - The status_location or resource_usage argument points to a location outside of the address space of the process. o EINVAL- The value of the options argument is not valid. REF-741 waitpid _________________________________________________________________ waitpid Waits for a child process to stop or terminate. Format #include pid_t waitpid (pid_t process_id, int *status_location, int options); Arguments process_id The child process or set of child processes. status_location A pointer to a location that contains the termination status of the child process as defined in the header file. Beginning with OpenVMS Version 7.2, when compiled with the _VMS_WAIT macro defined, this function puts the OpenVMS completion code of the child process at the address specified in the status_location argument. options Flags that modify the behavior of the function. These flags are defined in the Description section. Description This function suspends the calling process until the request is completed. It is redefined so that only the calling thread is suspended. If the process_id argument is -1 and the options argument is 0, the waitpid function behaves the same as the wait function. If these arguments have other values, the waitpid function is changed as specified by those values. REF-742 waitpid The process_id argument allows the calling process to gather status from a specific set of child processes, according to the following rules: ___________________________________________________________ If the process_ id_is____________Then_status_is_requested__________________ Equal to -1 For any child process. In this respect, the waitpid function is equivalent to the wait function. Greater than 0 For a single child process and specifies _________________the_process_ID.___________________________ The waitpid function only returns the status of a child process from this set. The options argument to the waitpid function modifies the behavior of the function. You can combine the flags for the options argument by specifying their bitwise-inclusive OR. The flags are: WCONTINUED Specifies that the following is reported to the calling process: the status of any continued child process specified by the process_id argument whose status is unreported since it continued. WNOWAIT Specifies that the process whose status is returned in status_location is kept in a waitable state. You can wait for the process again with the same results. WNOHANG Prevents the calling process from being suspended. If there are child processes that stopped or terminated, one is chosen and waitpid returns its pid, as when you do not specify the WNOHANG flag. If there are no terminated processes (that is, if waitpid suspends the calling process without the WNOHANG flag), 0 (zero) is returned. Because you can never wait for process 0, there is no confusion arising from this return. REF-743 waitpid WUNTRACED Specifies that the call return additional information when the child processes of the current process stop because the child process received a SIGTTIN, SIGTTOU, SIGSTOP, or SIGTSTOP signal. If the waitpid function returns because the status of a child process is available, the process ID of the child process is returned. Information is stored in the location pointed to by status_location, if this pointer is not null. The value stored in the location pointed to by status_location is 0 only if the status is returned from a terminated child process that did one of the following: o Returned 0 from the main function. o Passed 0 as the status argument to the _exit or exit function. Regardless of the value of status_location, you can define this information using the macros defined in the header file, which evaluate to integral expressions. In the following function descriptions, status_value is equal to the integer value pointed to by status_location: WIFEXITED(status_ Evaluates to a nonzero value if value) status was returned for a child process that terminated normally. WEXITSTATUS(status_ If the value of WIFEXITED(status_ value) value) is nonzero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to the _exit or exit function, or to the value the child process returned from the main function. WIFSIGNALED(status_ Evaluates to nonzero value if status value) returned for a child process that terminated due to the receipt of a signal not caught. REF-744 waitpid WTERMSIG(status_ If the value of WIFSIGNALED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the termination of the child process. WIFSTOPPED(status_ Evaluates to a nonzero value if value) status was returned for a child process that is currently stopped. WSTOPSIG(status_ If the value of WIFSTOPPED(status_ value) value) is nonzero, this macro evaluates to the number of the signal that caused the child process to stop. WIFCONTINUED(status_ Evaluates to a nonzero value if value) status returned for a child process that continued. If the information stored at the location pointed to by status_location is stored there by a call to waitpid that specified the WUNTRACED flag, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) o WIFSTOPPED(*status_value) o WIFCONTINUED(*status_value) If the information stored in the buffer pointed to by status_location resulted from a call to waitpid without the WUNTRACED flag specified, one of the following macros evaluates to a nonzero value: o WIFEXITED(*status_value) o WIFSIGNALED(*status_value) If a parent process terminates without waiting for all of its child processes to terminate, the remaining child processes is assigned a parent process ID equal to the process ID of the init process. See also exit, _exit, and wait in this section. REF-745 waitpid Return Values 0 Indicates success. If the WNOHANG option was specified, and there are no stopped or exited child processes, the waitpid function also returns a value of 0. -1 Indicates an error; errno is set to one of the following values: o ECHILD-The calling process has no existing unwaited-for child processes. The process or process group ID specified by the process_ id argument does not exist or is not a child process of the calling process. o EINTR-The function was terminated by receipt of a signal. If the waitpid function returns because the status of a child process is available, the process ID of the child is returned to the calling process. If they return because a signal was caught by the calling process, -1 is returned. o EFAULT- The status_location argument points to a location outside of the address space of the process. o EINVAL- The value of the options argument is not valid. REF-746 wcrtomb _________________________________________________________________ wcrtomb Converts the wide character to its multibyte character representation. Format #include size_t wcrtomb (char *s, wchar_t wc, mbstate_t *ps); Arguments s A pointer to the resulting multibyte character. wc A wide character. ps A pointer to the mbstate_t object. If a NULL pointer is specified, the function uses its internal mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. Description If s is a NULL pointer, the wcrtomb function is equivalent to the call: wcrtomb (buf, L'\0', ps) where buf is an internal buffer. If s is not a NULL pointer, the wcrtomb function determines the number of bytes needed to represent the multibyte character that corresponds to the wide character specified by wc (including any shift sequences), and stores the resulting bytes in the array whose first element is pointed to by s. At most MB_CUR_MAX bytes are stored. If wc is a null wide character, a null byte is stored preceded by any shift sequence needed to restore the initial shift state. The resulting state described is the initial conversion state. REF-747 wcrtomb Return Values n The number of bytes stored in the resulting array, including any shift sequences to represent the multibyte character. -1 Indicates an encoding error. The wc argument is not a valid wide character. The global errno is set to EILSEQ; the conversion state is undefined. REF-748 wcscat _________________________________________________________________ wcscat Concatenates two wide-character strings. Format #include wchar_t *wcscat (wchar_t *wstr_1, const wchar_t *wstr_2); Function Variants This function also has variants named _wcscat32 and _ wcscat64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr_1, wstr_2 Pointers to null-terminated wide-character strings. Description This function appends the wide-character string wstr_2, including the terminating null character, to the end of wstr_1. See also wcsncat in this section. Return Values x The first argument, wstr_1, which is assumed to be large enough to hold the concatenated result. REF-749 wcscat Example #include #include #include #include /* This program concatenates two wide- character strings using */ /* the wcscat function, and then manually compares the result */ /* to the expected result */ #define S1LENGTH 10 #define S2LENGTH 8 main() { int i; wchar_t s1buf[S1LENGTH + S2LENGTH]; wchar_t s2buf[S2LENGTH]; wchar_t test1[S1LENGTH + S2LENGTH]; /* Initialize the three wide-character strings */ if (mbstowcs(s1buf, "abcmnexyz", S1LENGTH) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } if (mbstowcs(s2buf, " orthis", S2LENGTH) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } if (mbstowcs(test1, "abcmnexyz orthis", S1LENGTH + S2LENGTH) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } REF-750 wcscat /* Concatenate s1buf with s2buf, placing the result into */ /* s1buf. Then compare s1buf with the expected result */ /* in test1. */ wcscat(s1buf, s2buf); for (i = 0; i < S1LENGTH + S2LENGTH - 2; i++) { /* Check that each character is correct */ if (test1[i] != s1buf[i]) { printf("Error in wcscat\n"); exit(EXIT_FAILURE); } } printf("Concatenated string: <%S>\n", s1buf); } Running the example produces the following result: Concatenated string: REF-751 wcschr _________________________________________________________________ wcschr Scans for a wide character in a specifed wide-character string. Format #include wchar_t *wcschr (const wchar_t *wstr, wchar_t wc); Function Variants This function also has variants named _wcschr32 and _ wcschr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr A pointer to a null-terminated wide-character string. wc A character of type wchar_t. Description This function returns the address of the first occurrence of a specified wide character in a null-terminated wide- character string. The terminating null character is considered to be part of the string. See also wcsrchr in this section. Return Values x The address of the first occurrence of the specified wide character. NULL Indicates that the wide character does not occur in the string. REF-752 wcschr Example #include #include #include #include #define BUFF_SIZE 50 main() { int i; wchar_t s1buf[BUFF_SIZE]; wchar_t *status; /* Initialize the buffer */ if (mbstowcs(s1buf, "abcdefghijkl lkjihgfedcba", BUFF_ SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* This program checks the wcschr function by incrementally */ /* going through a string that ascends to the middle and then */ /* descends towards the end. */ for (i = 0; (s1buf[i] != '\0') && (s1buf[i] != ' '); i++) { status = wcschr(s1buf, s1buf[i]); /* Check for pointer to leftmost character - test 1. */ if (status != &s1buf[i]) { printf("Error in wcschr\n"); exit(EXIT_FAILURE); } } printf("Program completed successfully\n"); } When this example program is run, it produces the following result: Program completed successfully REF-753 wcscmp _________________________________________________________________ wcscmp Compares two wide-character strings. It returns an integer that indicates if the strings are different, and how they differ. Format #include int wcscmp (const wchar_t *wstr_1, const wchar_t *wstr_2); Arguments wstr_1, wstr_2 Pointers to null-terminated wide-character strings. Description This function compares the wide characters in wstr_1 with those in wstr_2. If the characters differ, the function returns: o An integer less than 0, if the codepoint of the first differing character in wstr_1 is less than the codepoint of the corresponding character in wstr_2 o An integer greater than 0, if the codepoint of the first differing character in wstr_1 is greater than the codepoint of the corresponding character in wstr_2 If the wide-characters strings are identical, the function returns zero. Unlike the wcscoll function, the wcscmp function compares the string based on the binary value of each wide character. See also wcsncmp in this section. REF-754 wcscmp Return Values < 0 Indicates that wstr_1 is less than wstr_2. = 0 Indicates that wstr_1 equals wstr_2. > 0 Indicates that wstr_1 is greater than wstr_2. REF-755 wcscoll _________________________________________________________________ wcscoll Compares two wide-character strings and returns an integer that indicates if the strings differ, and how they differ. The function uses the collating information in the LC_ COLLATE category of the current locale to determine how the comparison is performed. Format #include int wcscoll (const wchar_t *ws1, const wchar_t *ws2); Arguments ws1, ws2 Pointers to wide-character strings. Description This function, unlike wcscmp, compares two strings in a locale-dependent manner. Because no value is reserved for error indication, the application must check for one by setting errno to 0 before the function call and testing it after the call. See also the wcsxfrm function in this section. Return Values < 0 Indicates that ws1 is less than ws2. 0 Indicates that the strings are equal. > 0 Indicates that ws1 is greater than ws2. REF-756 wcscpy _________________________________________________________________ wcscpy Copies the wide-character string source, including the terminating null character, into dest. Format #include wchar_t *wcscpy (wchar_t *dest, const wchar_t *source); Function Variants This function also has variants named _wcscpy32 and _ wcscpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest Pointer to the null-terminated wide-character destination string. source Pointer to the null-terminated wide-character source string. Description This function copies source into dest, and stops after copying source's null character. If copying takes place between two ovelapping strings, the behavior is undefined. See also wcsncpy in this section. Return Values x The address of source. REF-757 wcscspn _________________________________________________________________ wcscspn Compares the characters in a wide-character string against a set of wide characters. The function returns the length of the initial substring that is comprised entirely of characters that are not in the set of wide characters. Format #include size_t wcscspn (const wchar_t *wstr1, const wchar_t *wstr2); Arguments wstr1 A pointer to a null-terminated wide-character string. If this is a null string, 0 is returned. wstr2 A pointer to a null-terminated wide-character string that contains the set of wide characters for which the function will search. Description This function scans the wide characters in the string pointed to by wstr1 until it encounters a character found in wstr2. The function returns the length of the initial segment of wstr1 that is formed by characters not found in wstr2. Return Values x The length of the segment. REF-758 wcscspn Example #include #include #include #include /* This test sets up 2 strings, buffer and w_ string, and then */ /* uses wcscspn() to calculate the maximum segment of w_ string, */ /* which consists entirely of characters NOT from buffer. */ #define BUFF_SIZE 20 #define STRING_SIZE 50 main() { wchar_t buffer[BUFF_SIZE]; wchar_t w_string[STRING_SIZE]; size_t result; /* Initialize the buffer */ if (mbstowcs(buffer, "abcdefg", BUFF_SIZE) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Initialize the string */ if (mbstowcs(w_ string, "jklmabcjklabcdehjklmno", STRING_SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Using wcscspn - work out the largest string in w_ string which */ /* consists entirely of characters NOT from buffer */ REF-759 wcscspn result = wcscspn(w_string, buffer); printf("Longest segment NOT found in w_ string is: %d", result); } Running the example program produces the following result: Longest segment NOT found in w_string is: 4 REF-760 wcsftime _________________________________________________________________ wcsftime Uses date and time information stored in a tm structure to create a wide-character output string. The format of the output string is controlled by a format string. Format #include size_t wcsftime (wchar_t *wcs, size_t maxsize, const char *format, const struct tm *timeptr); (XPG4) size_t wcsftime (wchar_t *wcs, size_t maxsize, const wchar_t *format, const struct tm *timeptr); (ISO C) Function Variants Compiling with the _DECC_V4_SOURCE and _VMS_V6_SOURCE feature-test macros defined enables a local-time-based entry point to this function that is equivalent to the behavior before OpenVMS Version 7.0. Arguments wcs A pointer to the resultant wide-character string. maxsize The maximum number of wide characters to be stored in the resultant string. format A pointer to the string that controls the format of the output string. For the XPG4 interface, this argument is a pointer to a constant character string. For the ISO C interface, it is a pointer to a constant wide-character string. timeptr A pointer to the local time structure. The tm structure is defined in the header file. REF-761 wcsftime Description This function uses data in the structure pointed to by timeptr to create the wide-character string pointed to by wcs. A maximum of maxsize wide characters is copied to wcs. The format string consists of zero or more conversion specifications and ordinary characters. All ordinary characters (including the terminating null character) are copied unchanged into the output string. A conversion specification defines how data in the tm structure is formatted in the output string. A conversion specification consists of a percent (%) character followed by one or more optional characters (see Table REF-13), and ending with a conversion specifier (see Table REF-14). If any of the optional characters listed in Table REF-13 are specified, they must appear in the order shown in the table. Table REF-13 Optional Elements of wcsftime Conversion _____________Specifications________________________________ Element___Meaning__________________________________________ - Optional with the field width to specify that the field is left-justified and padded with spaces. This cannot be used with the 0 element. 0 Optional with the field width to specify that the field is right-justified and padded with zeros. This cannot be used with the - element. field A decimal integer that specifies the maximum width field width (continued on next page) REF-762 wcsftime Table REF-13 (Cont.) Optional Elements of wcsftime _____________________Conversion_Specifications_____________ Element___Meaning__________________________________________ .precisionA decimal integer that specifies the precision of data in a field. For the d, H, I, j, m, M, o, S, U, w, W, y and Y conversion specifiers, the precision specifier is the minimum number of digits to appear in the field. If the conversion specification has fewer digits than that specified by the precision, leading zeros are added. For the a, A, b, B, c, D, E, h, n, N, p, r, t, T, x, X, Z, and % conversion specifiers, the precision specifier is the maximum number of wide characters to appear in the field. If the conversion specification has more characters than that specified by the the precision, characters are truncated on the right. The default precision for the d, H, I, m, M, o, S, U, w, W, y and Y conversion specifiers is 2, and the default precision for the j conversion __________specifier_is_3.__________________________________ Note that the list of optional elements of conversion specifications from Table REF-13 are Compaq extensions to the XPG4 specification. Table REF-14 lists the conversion specifiers. The wcsftime function uses fields in the LC_TIME category of the program's current locale to provide a value. For example, if %B is specified, the function accesses the mon field in LC_TIME to find the full month name for the month specified in the tm structure. The result of using invalid conversion specifiers is undefined. REF-763 wcsftime Table_REF-14_wcsftime_Conversion_Specifiers________________ Specifier_Replaced_by______________________________________ a The locale's abbreviated weekday name A The locale's full weekday name b The locale's abbreviated month name B The locale's full month name c The locale's appropriate date and time representation C The century number (the year divided by 100 and truncated to an integer) as a decimal number (00 - 99) d The day of the month as a decimal number (01 - 31) D Same as %m/%d/%y e The day of the month as a decimal number (1 - 31) in a 2 digit field with the leading space character fill Ec The locale's alternative date and time representation EC The name of the base year (period) in the locale's alternative representation Ex The locale's alternative date representation Ey The offset from the base year (%EC) in the locale's alternative representation EY The locale's full alternative year representation h Same as %b H The hour (24-hour clock) as a decimal number (00 - 23) I The hour (12-hour clock) as a decimal number (01 - 12) j The day of the year as a decimal number (001 - 366) m The month as a decimal number (01 - 12) M The minute as a decimal number (00 - 59) (continued on next page) REF-764 wcsftime Table_REF-14_(Cont.)_wcsftime_Conversion_Specifiers________ Specifier_Replaced_by______________________________________ n The newline character Od The day of the month using the locale's alternative numeric symbols Oe The date of the month using the locale's alternative numeric symbols OH The hour (24-hour clock) using the locale's alternative numeric symbols OI The hour (12-hour clock) using the locale's alternative numeric symbols Om The month using the locale's alternative numeric symbols OM The minutes using the locale's alternative numeric symbols OS The seconds using the locale's alternative numeric symbols Ou The weekday as a number in the locale's alternative representation (Monday=1) OU The week number of the year (Sunday as the first day of the week) using the locale's alternative numeric symbols OV The week number of the year (Monday as the first day of the week) as a decimal number (01 -53) using the locale's alterntative numeric symbols. If the week containing January 1 has four or more days in the new year, it is considered as week 1. Otherwise, it is considered as week 53 of the previous year, and the next week is week 1. Ow The weekday as a number (Sunday=0) using the locale's alternative numeric symbols OW The week number of the year (Monday as the first day of the week) using the locale's alternative numeric symbols (continued on next page) REF-765 wcsftime Table_REF-14_(Cont.)_wcsftime_Conversion_Specifiers________ Specifier_Replaced_by______________________________________ Oy The year without the century using the locale's alternative numeric symbols p The locale's equivalent of the AM/PM designations associated with a 12-hour clock r The time in AM/PM notation R The time in 24-hour notation (%H:%M) S The second as a decimal number (00 - 61) t The tab character T The time (%H:%M:%S) u The weekday as a decimal number between 1 and 7 (Monday=1) U The week number of the year (the first Sunday as the first day of week 1) as a decimal number (00 - 53) V The week number of the year (Monday as the first day of the week) as a decimal number (00 - 53). If the week containing January 1 has four or more days in the new year, it is considered as week 1. Otherwise, it is considered as week 53 of the previous year, and the next week is week 1. w The weekday as a decimal number (0 [Sunday] - 6) W The week number of the year (the first Monday as the first day of week 1) as a decimal number (00 - 53) x The locale's appropriate date representation X The locale's appropriate time representation y The year without century as a decimal number (00 - 99) Y The year with century as a decimal number Z Time-zone name or abbreviation. If time-zone information is not available, no character is output. (continued on next page) REF-766 wcsftime Table_REF-14_(Cont.)_wcsftime_Conversion_Specifiers________ Specifier_Replaced_by______________________________________ %_________%________________________________________________ Return Values x The number of wide characters placed into the array pointed to by wcs, not including the terminating null character. 0 Indicates an error occurred. The contents of the array are indeterminate. Example /* Exersize the wcsftime formating routine. */ /* NOTE: the format string is an "L" (or wide character) */ /* string indicating that this call is NOT in */ /* the XPG4 format, but rather in ISO C format. */ #include #include #include #include #include #include #define NUM_OF_DATES 7 #define BUF_SIZE 256 /* This program formats a number of different dates, once using the */ /* C locale and then using the fr_FR.ISO8859- 1 locale. Date and time */ /* formatting is done using wcsftime(). */ main() REF-767 wcsftime { int count, i; wchar_t buffer[BUF_SIZE]; struct tm *tm_ptr; time_t time_list[NUM_OF_DATES] = {500, 68200000, 694223999, 694224000, 704900000, 705000000, 705900000}; /* Display dates using the C locale */ printf("\nUsing the C locale:\n\n"); setlocale(LC_ALL, "C"); for (i = 0; i < NUM_OF_DATES; i++) { /* Convert to a tm structure */ tm_ptr = localtime(&time_list[i]); /* Format the date and time */ count = wcsftime(buffer, BUF_ SIZE, L"Date: %A %d %B %Y%nTime: %T%n%n", tm_ptr); if (count == 0) { perror("wcsftime"); exit(EXIT_FAILURE); } /* Print the result */ printf("%S", buffer); } /* Display dates using the fr_FR.ISO8859-1 locale */ printf("\nUsing the fr_FR.ISO8859-1 locale:\n\n"); setlocale(LC_ALL, "fr_FR.ISO8859-1"); for (i = 0; i < NUM_OF_DATES; i++) { /* Convert to a tm structure */ tm_ptr = localtime(&time_list[i]); /* Format the date and time */ count = wcsftime(buffer, BUF_ REF-768 wcsftime SIZE, L"Date: %A %d %B %Y%nTime: %T%n%n", tm_ptr); if (count == 0) { perror("wcsftime"); exit(EXIT_FAILURE); } /* Print the result */ printf("%S", buffer); } } Running the example program produces the following result: Using the C locale: Date: Thursday 01 January 1970 Time: 00:08:20 Date: Tuesday 29 February 1972 Time: 08:26:40 Date: Tuesday 31 December 1991 Time: 23:59:59 Date: Wednesday 01 January 1992 Time: 00:00:00 Date: Sunday 03 May 1992 Time: 13:33:20 Date: Monday 04 May 1992 Time: 17:20:00 Date: Friday 15 May 1992 Time: 03:20:00 Using the fr_FR.ISO8859-1 locale: Date: jeudi 01 janvier 1970 Time: 00:08:20 Date: mardi 29 février 1972 Time: 08:26:40 Date: mardi 31 décembre 1991 Time: 23:59:59 Date: mercredi 01 janvier 1992 Time: 00:00:00 REF-769 wcsftime Date: dimanche 03 mai 1992 Time: 13:33:20 Date: lundi 04 mai 1992 Time: 17:20:00 Date: vendredi 15 mai 1992 Time: 03:20:00 REF-770 wcslen _________________________________________________________________ wcslen Returns the number of wide characters in a wide- character string. The returned length does not include the terminating null character. Format #include size_t wcslen (const wchar_t *wstr); Arguments wstr A pointer to a null-terminated wide-character string. Return Values x The length of the wide-character string, excluding the terminating null wide character. REF-771 wcsncat _________________________________________________________________ wcsncat Concatenates a counted number of wide-characters from one string to another. Format #include wchar_t *wcsncat (wchar_t *wstr_1, const wchar_t *wstr_2, size_t maxchar); Function Variants This function also has variants named _wcsncat32 and _ wcsncat64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr_1, wstr_2 Pointers to null-terminated wide-character strings. maxchar The maximum number of wide characters from wstr_2 that are copied to wstr_1. If maxchar is 0, no characters are copied from wstr_2. Description This function appends wide characters from the wide- character string wstr_2 to the end of wstr_1, up to a maximum of maxchar characters. A terminating null wide character is always appended to the result of the wcsncat function. Therefore, the maximum number of wide characters that can end up in wstr_1 is wcslen(wstr_1) + maxchar + 1). See also wcscat in this section. REF-772 wcsncat Return Values x The first argument, wstr_1, which is assumed to be large enough to hold the concatenated result. Example #include #include #include #include /* This program concatenates two wide- character strings using */ /* the wcsncat function, and then manually compares the result */ /* to the expected result */ #define S1LENGTH 10 #define S2LENGTH 8 #define SIZE 3 main() { int i; wchar_t s1buf[S1LENGTH + S2LENGTH]; wchar_t s2buf[S2LENGTH]; wchar_t test1[S1LENGTH + S2LENGTH]; /* Initialize the three wide-character strings */ if (mbstowcs(s1buf, "abcmnexyz", S1LENGTH) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } if (mbstowcs(s2buf, " orthis", S2LENGTH) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } if (mbstowcs(test1, "abcmnexyz orthis", S1LENGTH + SIZE) REF-773 wcsncat == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Concatenate s1buf with SIZE characters from s2buf, placing the */ /* result into s1buf. Then compare s1buf with the expected result */ /* in test1. */ wcsncat(s1buf, s2buf, SIZE); for (i = 0; i <= S1LENGTH + SIZE - 2; i++) { /* Check that each character is correct */ if (test1[i] != s1buf[i]) { printf("Error in wcsncat\n"); exit(EXIT_FAILURE); } } printf("Concatenated string: <%S>\n", s1buf); } Running the example produces the following result: Concatenated string: REF-774 wcsncmp _________________________________________________________________ wcsncmp Compares not more than maxchar characters of two wide- character strings. It returns an integer that indicates if the strings are different, and how they differ. Format #include int wcsncmp (const wchar_t *wstr_1, const wchar_t *wstr_2, size_t maxchar); Arguments wstr_1, wstr_2 Pointers to null-terminated wide-character strings. maxchar The maximum number of characters to search in both wstr_1 and wstr_2. If maxchar is 0, no comparison is performed and 0 is returned (the strings are considered equal). Description The strings are compared until a null character is encountered, the strings differ, or maxchar is reached. If characters differ, the function returns: o An integer less than 0 if the codepoint of the first differing character in wstr_1 is less than the codepoint of the corresponding character in wstr_2 o An integer greater than 0 if the codepoint of the first differing character in wstr_1 is greater than the codepoint of the corresponding character in wstr_2 If no differences are found after comparing maxchar characters, the function returns zero. See also wcscmp in this section. REF-775 wcsncmp Return Values < 0 Indicates that wstr_1 is less than wstr_2. 0 Indicates that wstr_1 equals wstr_2. > 0 Indicates that wstr_1 is greater than wstr_2. REF-776 wcsncpy _________________________________________________________________ wcsncpy Copies wide characters from source into dest. The function copies up to a maximum of maxchar characters. Format #include wchar_t *wcsncpy (wchar_t *dest, const wchar_t *source, size_t maxchar); Function Variants This function also has variants named _wcsncpy32 and _ wcsncpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest Pointer to the null-terminated wide-character destination string. source Pointer to the null-terminated wide-character source string. maxchar The maximum number of wide characters to copy from source to dest. Description This function copies no more than maxchar characters from source to dest. If source contains less than maxchar characters, null characters are added to dest until maxchar characters have been written to dest. If source contains maxchar or more characters, as many characters as possible are copied to dest. The null terminator of source is not copied to dest. See also wcscpy in this section. REF-777 wcsncpy Return Values x The address of dest. REF-778 wcspbrk _________________________________________________________________ wcspbrk Searches a wide-character string for the first occurrence of one of a specified set of wide characters. Format #include wchar_t *wcspbrk (const wchar_t *wstr, const wchar_t *charset); Function Variants This function also has variants named _wcspbrk32 and _ wcspbrk64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr A pointer to a wide-character string. If this is a null string, NULL is returned. charset A pointer to a wide-character string containing the set of wide characters for which the function will search. Description This function scans the wide characters in the string, stops when it encounters a wide character found in charset, and returns the address of the first character in the string that appears in the character set. REF-779 wcspbrk Return Values x The address of the first wide character in the string that is in the set. NULL Indicates that none of the characters are in charset. REF-780 wcsrchr _________________________________________________________________ wcsrchr Scans for the last occurrence of a wide-character in a given string. Format #include wchar_t *wcsrchr (const wchar_t *wstr, wchar_t wc); Function Variants This function also has variants named _wcsrchr32 and _ wcsrchr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr A pointer to a null-terminated wide-character string. wc A character of type wchar_t. Description This function returns the address of the last occurrence of a given wide character in a null-terminated wide-character string. The terminating null character is considered to be part of the string. See also wcschr in this section. Return Values x The address of the last occurrence of the specified wide character. NULL Indicates that the wide character does not occur in the string. REF-781 wcsrchr Example #include #include #include #include #define BUFF_SIZE 50 #define STRING_SIZE 6 main() { int i; wchar_t s1buf[BUFF_SIZE], w_string[STRING_SIZE]; wchar_t *status; wchar_t *pbuf = s1buf; /* Initialize the buffer */ if (mbstowcs(s1buf, "hijklabcdefg ytuhijklfedcba", BUFF_ SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Initialize the string to be searched for */ if (mbstowcs(w_string, "hijkl", STRING_ SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* This program checks the wcsrchr function by searching for the */ /* last occurrence of a string in the buffer s1buf and prints out */ /* the contents of s1buff from the location of the string found. */ status = wcsrchr(s1buf, w_string[0]); /* Check for pointer to start of rightmost character string. */ if (status == pbuf) { printf("Error in wcsrchr\n"); exit(EXIT_FAILURE); } REF-782 wcsrchr printf("Program completed successfully\n"); printf("String found : [%S]\n", status); } Running the example produces the following result: Program completed successfully String found : [hijklfedcba] REF-783 wcsrtombs _________________________________________________________________ wcsrtombs Converts a sequence of wide characters into a sequence of corresponding multibyte characters. Format #include size_t wcsrtombs (char *dst, const wchar_t **src, size_t len, mbstate_t *ps); Function Variants This function also has variants named _wcsrtombs32 and _ wcsrtombs64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dst A pointer to the destination array for converted multibyte character sequence. src An address of the pointer to an array containing the sequence of wide characters to be converted. len The maximum number of bytes that can be stored in the array pointed to by dst. ps A pointer to the mbstate_t object. If a NULL pointer is specified, the function uses its internal mbstate_t object. mbstate_t is an opaque datatype intended to keep the conversion state for the state-dependent codesets. REF-784 wcsrtombs Description This function converts a sequence of wide characters from the array indirectly pointed to by src into a sequence of corresponding multibyte characters, beginning in the conversion state described by the object pointed to by ps. If dst is a not NULL pointer, the converted characters are then stored into the array pointed to by dst. Conversion continues up to and including a terminating null wide character, which is also stored. Conversion stops earlier in two cases: o When a code is reached that does not correspond to a valid multibyte character o If dst is not a NULL pointer, when the next multibyte character would exceed the limit of len total bytes to be stored into the array pointed to by dst Each conversion takes place as if by a call to the wcrtomb function. If dst is not a NULL pointer, the pointer object pointed to by src is assigned either a NULL pointer, (if the conversion stopped because it reached a terminating null wide character) or the address just beyond the last wide character converted (if any). If conversion stopped because it reached a terminating null wide character, the resulting state described is the initial conversion state. If the wcsrtombs function is called as a counting function, which means that dst is a NULL pointer, the value of the internal mbstate_t object will remain unchanged. See also wcrtomb in this section. Return Values x The number of bytes stored in the resulting array, not including the terminating null (if any). REF-785 wcsrtombs -1 Indicates an encoding error-a character that does not correspond to a valid multibyte character was encountered; errno is set to EILSEQ; the conversion state is undefined. REF-786 wcsspn _________________________________________________________________ wcsspn Compares the characters in a wide-character string against a set of wide characters. The function returns the length of the first substring comprised entirely of characters in the set of wide characters. Format #include size_t wcsspn (const wchar_t *wstr1, const wchar_t *wstr2); Arguments wstr1 A pointer to a null-terminated wide-character string. If this string is a null string, 0 is returned. wstr2 A pointer to a null-terminated wide-character string that contains the set of wide characters for which the function will search. Description This function scans the wide characters in the wide- character string pointed to by wstr1 until it encounters a character not found in wstr2. The function returns the length of the first segment of wstr1 formed by characters found in wstr2. Return Values x The length of the segment. REF-787 wcsspn Example #include #include #include #include /* This test sets up 2 strings, buffer and w_ string. It then */ /* uses wcsspn() to calculate the maximum segment of w_ string */ /* that consists entirely of characters from buffer. */ #define BUFF_SIZE 20 #define STRING_SIZE 50 main() { wchar_t buffer[BUFF_SIZE]; wchar_t w_string[STRING_SIZE]; size_t result; /* Initialize the buffer */ if (mbstowcs(buffer, "abcdefg", BUFF_SIZE) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Initialize the string */ if (mbstowcs(w_ string, "abcedjklmabcjklabcdehjkl", STRING_SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Using wcsspn - work out the largest string in w_ string that */ /* consists entirely of characters from buffer */ REF-788 wcsspn result = wcsspn(w_string, buffer); printf("Longest segment found in w_ string is: %d", result); } Running the example program produces the following result: Longest segment found in w_string is: 5 REF-789 wcsstr _________________________________________________________________ wcsstr Locates the first occurrence in the string pointed to by s1 of the sequence of wide characters in the string pointed to by s2. Format #include wchar_t *wcsstr (const wchar_t *s1, const wchar_t *s2); Function Variants This function also has variants named _wcsstr32 and _ wcsstr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s1, s2 Pointers to null-terminated, wide-character strings. Description If s2 points to a wide-character string of zero length, the function returns s1. Return Values x A pointer to the located string. NULL Indicates an error; the string was not found. REF-790 wcstod _________________________________________________________________ wcstod Converts a given wide-character string to a double- precision number. Format #include double wcstod (const wchar_t *nptr, wchar_t **endptr); Arguments nptr A pointer to the wide-character string to be converted to a double-precision number. endptr The address of an object where the function can store the address of the first unrecognized wide character that terminates the scan. If endptr is a NULL pointer, the address of the first unrecognized wide character is not retained. Description This function recognizes an optional sequence of white- space characters (as defined by iswspace), then an optional plus or minus sign, then a sequence of digits optionally containing a radix character, then an optional letter (e or E) followed by an optionally signed integer. The first unrecognized character ends the conversion. The string is interpreted by the same rules used to interpret floating constants. The radix character is defined in the program's current locale (category LC_NUMERIC). This function returns the converted value. For wcstod, overflows are accounted for in the following manner: o If the correct value causes an overflow, HUGE_VAL (with a plus or minus sign according to the sign of the value) is returned and errno is set to ERANGE. REF-791 wcstod o If the correct value causes an underflow, 0 is returned and errno is set to ERANGE. If the string starts with an unrecognized wide character, *endptr is set to nptr and a 0 value is returned. Return Values x The converted string. 0 Indicates the conversion could not be performed. The function sets errno to one of: o EINVAL - No conversion could be performed. o ERANGE - The value would cause an underflow. o ENOMEM - Not enough memory available for internal conversion buffer. (+/ -)HUGE_VAL Indicates overflow. The function sets errno to ERANGE. REF-792 wcstok _________________________________________________________________ wcstok Locates text tokens in a given wide-character string. Format #include wchar_t *wcstok (wchar_t *ws1, const wchar_t *ws2); (XPG4) wchar_t *wcstok (wchar_t *ws1, const wchar_t *ws2, wchar_t **ptr); (ISO C) Function Variants This function also has variants named _wcstok32 and _ wcstok64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments ws1 A pointer to a wide-character string containing 0 or more text tokens. ws2 A pointer to a separator string consisting of one or more wide characters. The separator string can differ from call to call. ptr ISO C Standard only. Used only when ws1 is NULL, ptr is a caller-provided wchar_t pointer into which wcstok stores information necessary for it to continue scanning the same wide-character string. REF-793 wcstok Description A sequence of calls to wcstok breaks the wide-character string pointed to by ws1 into a sequence of tokens, each of which is delimited by a wide character from the wide- character string pointed to by ws2. The wcstok function keeps track of its position in the wide-character string between calls and, as successive calls are made, the function works through the wide- character string, identifying the text token following the one identified by the previous call. Tokens in ws1 are delimited by null characters that wcstok inserts into ws1. Therefore, ws1 cannot be a const object. The following sections describe differences between the XPG4 Standard and ISO C Standard interface to wcstok. XPG4 Standard Behavior The first call to the wcstok function searches the wide- character string for the first character that is not found in the separator string pointed to by ws2. The first call returns a pointer to the first wide character in the first token and writes a null wide character into ws1 immediately following the returned token. Subsequent calls to wcstok search for a wide character that is in the separator string pointed to by ws2. Each subsequent call (with the value of the first argument remaining NULL) returns a pointer to the next token in the string originally pointed to by ws1. When no tokens remain in the string, wcstok returns a NULL pointer. ISO C Standard Behavior For the first call in the sequence, ws1 points to a wide- character string. In subsequent calls for the same string, ws1 is NULL. When ws1 is NULL, the value pointed to by ptr matches that stored by the previous call for the same wide- character string. Otherwise, the value pointed to by ptr is ignored. REF-794 wcstok The first call in the sequence searches the wide-character string pointed to by ws1 for the first wide character that is not contained in the current separator wide-character string pointed to by ws2. If no such wide character is found, then there are no tokens in the wide-character string pointed to by ws1, and wcstok returns a NULL pointer. The wcstok function then searches from there for a wide character that is contained in the current separator wide- character string. If no such wide character is found, the current token extends to the end of the wide-character string pointed to by ws1, and subsequent searches in the same wide-character string for a token return a NULL pointer. If such a wide character is found, it is overwritten by a null wide character, which terminates the current token. In all cases, wcstok stores sufficient information in the pointer pointed to by ptr so that subsequent calls with a NULL pointer for ws1 and the unmodified pointer value for ptr start searching just past the element overwritten by a null wide character (if any). Return Values x A pointer to the first character of a token. NULL Indicates that no token was found. Examples 1./* XPG4 version of wcstok call */ #include #include #include main() { wchar_t str[] = L"...ab..cd,,ef.hi"; REF-795 wcstok printf("|%S|\n", wcstok(str, L".")); printf("|%S|\n", wcstok(NULL, L",")); printf("|%S|\n", wcstok(NULL, L",.")); printf("|%S|\n", wcstok(NULL, L",.")); } 2. /* ISO C version of wcstok call */ #include #include #include main() { wchar_t str[] = L"...ab..cd,,ef.hi"; wchar_t *savptr = NULL; printf("|%S|\n", wcstok(str, L".", &savptr)); printf("|%S|\n", wcstok(NULL, L",", &savptr)); printf("|%S|\n", wcstok(NULL, L",.", &savptr)); printf("|%S|\n", wcstok(NULL, L",.", &savptr)); } Running this example produces the following results: $ $ RUN WCSTOK_EXAMPLE |ab| |.cd| |ef| |hi| $ REF-796 wcstol _________________________________________________________________ wcstol Converts a wide-character string in a specified base to a long integer value. Format #include long int wcstol (const wchar_t *nptr, wchar_t **endptr, int base); Function Variants This function also has variants named _wcstol32 and _ wcstol64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the wide-character string to be converted to a long integer. endptr The address of an object where the function can store a pointer to the first unrecognized character encountered in the conversion process (the character that follows the last character processed in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. If base is 16, leading zeros after the optional sign are ignored, and 0x or 0X is ignored. If base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant-After the optional sign: o A leading 0 indicates octal conversion. REF-797 wcstol o A leading 0x or 0X indicates hexadecimal conversion. o Any other combination of leading characters indicates decimal conversion. Description This function recognizes strings in various formats, depending on the value of the base. This function ignores any leading white-space characters (as defined by the iswspace function) in the given string. It recognizes an optional plus or minus sign, then a sequence of digits or letters that can represent an integer constant according to the value of the base. The first unrecognized character ends the conversion. Return Values x The converted value. 0 Indicates that the string starts with an unrecognized wide character or that the value for base is invalid. If the string starts with an unrecognized wide character, *endptr is set to nptr. The function sets errno to EINVAL. LONG_MAX or LONG_MIN Indicates that the converted value would cause a positive or negative overflow, respectively. The function sets errno to ERANGE. REF-798 wcstombs _________________________________________________________________ wcstombs Converts a sequence of wide-character codes to a sequence of multibyte characters. Format #include size_t wcstombs (char *s, const wchar_t *pwcs, size_t n); Arguments s A pointer to the array containing the resulting multibyte characters. pwcs A pointer to the array containing the sequence of wide- character codes. n The maximum number of bytes to be stored in the array pointed to by s. Description This function converts a sequence of codes corresponding to multibyte characters from the array pointed to by pwcs to a sequence of multibyte characters that are stored into the array pointed to by s, up to a maximum of n bytes. The value returned is equal to the number of characters converted or a -1 if an error occurred. This function is affected by the LC_CTYPE category of the program's current locale. See also wctomb in this section. If s is NULL, this function call is a counting operation and n is ignored. REF-799 wcstombs Return Values x The number of bytes stored in s, not including the null terminating byte. If s is NULL, wcstombs returns the number of bytes required for the multibyte character array. (size_t) -1 Indicates an error occurred. The function sets errno to EILSEQ - invalid character sequence, or a wide-character code does not correspond to a valid character. REF-800 wcstoul _________________________________________________________________ wcstoul Converts the initial portion of the wide-character string pointed to by nptr to an unsigned long integer. Format #include unsigned long int wcstoul (const wchar_t *nptr, wchar_t **endptr, int base); Function Variants This function also has variants named _wcstoul32 and _ wcstoul64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments nptr A pointer to the wide-character string to be converted to an unsigned long. endptr The address of an object where the function can store the address of the first unrecognized character encountered in the conversion process (The character that follows the last character in the string being converted). If endptr is a NULL pointer, the address of the first unrecognized character is not retained. base The value, 2 through 36, to use as the base for the conversion. If base is 16, leading zeros after the optional sign are ignored, and 0x or 0X is ignored. If base is 0, the sequence of characters is interpreted by the same rules used to interpret an integer constant: after the optional sign, a leading 0 indicates octal conversion, a leading 0x or 0X indicates hexadecimal conversion, and REF-801 wcstoul any other combination of leading characters indicates decimal conversion. Description This function recognizes strings in various formats, depending on the value of the base. It ignores any leading white-space characters (as defined by the iswspace function) in the string. It recognizes an optional plus or minus sign, then a sequence of digits or letters that may represent an integer constant according to the value of the base. The first unrecognized wide character ends the conversion. Return Values x The converted value. 0 Indicates that the string starts with an unrecognized wide character or that the value for base is invalid. If the string starts with an unrecognized wide character, *endptr is set to nptr. The function sets errno to EINVAL. ULONG_MAX Indicates that the converted value would cause an overflow. The function sets errno to ERANGE. Example #include #include #include #include #include /* This test calls wcstoul() to convert a string to an unsigned long */ /* integer. wcstoul outputs the resulting integer and any characters */ /* that could not be converted. */ #define MAX_STRING 128 main() { REF-802 wcstoul int base = 10, errno; char *input_string = "1234.56"; wchar_t string_array[MAX_STRING], *ptr; size_t size; unsigned long int val; printf("base = [%d]\n", base); printf("String to convert = %s\n", input_string); if ((size = mbstowcs(string_array, input_ string, MAX_STRING)) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } printf("wchar_t string is = [%S]\n", string_array); errno = 0; val = wcstoul(string_array, &ptr, base); if (errno == 0) { printf("returned unsigned long int from wcstoul = [%u]\n", val); printf("wide char terminating scan(ptr) = [%S]\n\n", ptr); } if (errno == ERANGE) { perror("error value is :"); printf("ULONG_MAX = [%u]\n", ULONG_MAX); printf("wcstoul failed, val = [%d]\n\n", val); } } Running the example program produces the following result: base = [10] String to convert = 1234.56 wchar_t string is = [1234.56] returned unsigned long int from wcstoul = [1234] wide char terminating scan(ptr) = [.56] REF-803 wcswcs _________________________________________________________________ wcswcs Locates the first occurrence in the string pointed to by wstr1 of the sequence of wide characters in the string pointed to by wstr2. Format #include wchar_t *wcswcs (const wchar_t *wstr1, const wchar_t *wstr2); Function Variants This function also has variants named _wcswcs32 and _ wcswcs64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments wstr1, wstr2 Pointers to null-terminated wide-character strings. Return Values Pointer A pointer to the located wide- character string. NULL Indicates that the wide-character string was not found. Example #include #include #include /* This test uses wcswcs() to find the occurrence of each sub */ /* wide- character string, string1 and string2, within the main */ /* wide- character string, lookin. */ REF-804 wcswcs #define BUF_SIZE 50 main() { static char lookin[] = "that this is a test was at the end"; char string1[] = "this", string2[] = "the end"; wchar_t buffer[BUF_SIZE], input_buffer[BUF_SIZE]; /* Convert lookin to wide- character format. */ /* Buffer and print it out. */ if (mbstowcs(buffer, lookin, BUF_SIZE) == (size_ t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } printf("Buffer to look in: %S\n", buffer); /* Convert string1 to wide- character format and use wcswcs() to */ /* locate it within buffer */ if (mbstowcs(input_buffer, string1, BUF_ SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } printf("this: %S\n", wcswcs(buffer, input_buffer)); /* Convert string2 to wide- character format and use wcswcs() to */ /* locate it within buffer */ if (mbstowcs(input_buffer, string2, BUF_ SIZE) == (size_t)-1) { REF-805 wcswcs perror("mbstowcs"); exit(EXIT_FAILURE); } printf("the end: %S\n", wcswcs(buffer, input_ buffer)); exit(1); } Running this example produces the following results: Buffer to look in: that this is a test was at the end this: this is a test was at the end the end: the end REF-806 wcswidth _________________________________________________________________ wcswidth Determines the number of printing positions on a display device that are required for a wide-character string. Format #include int wcswidth (const wchar_t *pwcs, size_t n); Arguments pwcs A pointer to a wide-character string. n The maximum number of characters in the string. Description This function returns the number of printing positions required to display the first n characters of the string pointed to by pwcs. If there are less than n wide characters in the string, the function returns the number of positions required for the whole string. Return Values x The number of printing positions required. 0 If pwcs is a null character. -1 Indicates that one (or more) of the wide characters in the string pointed to by pwcs is not a printable character. REF-807 wcsxfrm _________________________________________________________________ wcsxfrm Changes a wide-character string such that the changed string can be passed to the wcscmp function and produce the same result as passing the unchanged string to the wcscoll function. Format #include size_t wcsxfrm (wchar_t *ws1, const wchar_t *ws2, size_t maxchar); Arguments ws1, ws2 Pointers to wide-character strings. maxchar The maximum number of wide-characters, including the null wide-character terminator, allowed to be stored in s1. Description This function transforms the string pointed to by ws2 and stores the resulting string in the array pointed to by ws1. No more than maxchar wide characters, including the null wide terminator, are placed into the array pointed to by ws1. If the value of maxchar is less than the required size to store the transformed string (including the terminating null), the contents of the array pointed to by ws1 is indeterminate. In such a case, the function returns the size of the transformed string. If maxchar is zero, then, ws1 is allowed to be a NULL pointer, and the function returns the required size of the ws1 array before making the transformation. REF-808 wcsxfrm The wide-character string comparison functions, wcscoll and wcscmp, can produce different results given the same two wide-character strings to compare. This is because wcscmp does a straightforward comparison of the code point values of the characters in the strings, whereas wcscoll uses the locale information to do the comparison. Depending on the locale, the wcscoll comparison can be a multi-pass operation, which is slower than wcscmp. The wcsxfrm function transforms wide character strings in such a way that if you pass two transformed strings to the wcscmp function, the result is the same as passing the two original strings to the wcscoll function. The wcsxfrm function is useful in applications that need to do a large number of comparisons on the same wide-character strings using wcscoll. In this case, it may be more efficient (depending on the locale) to transform the strings once using wcsxfrm and then use the wcscmp function to do comparisons. Return Values x Length of the resulting string pointed to by ws1, not including the terminating null character. (size_t) -1 Indicates an error occurred. The function sets errno to EINVAL - The string pointed to by ws2 contains characters outside the domain of the collating sequence. Example #include #include #include #include /* This program verifies that two transformed strings, when passed */ /* through wcsxfrm and then compared, provide the same result as */ /* if passed through wcscoll without any transformation. */ #define BUFF_SIZE 20 REF-809 wcsxfrm main() { wchar_t w_string1[BUFF_SIZE]; wchar_t w_string2[BUFF_SIZE]; wchar_t w_string3[BUFF_SIZE]; wchar_t w_string4[BUFF_SIZE]; int errno; int coll_result; int wcscmp_result; size_t wcsxfrm_result1; size_t wcsxfrm_result2; /* setlocale to French locale */ if (setlocale(LC_ALL, "fr_FR.ISO8859-1") == NULL) { perror("setlocale"); exit(EXIT_FAILURE); } /* Convert each of the strings into wide-character format. */ if (mbstowcs(w_string1, "bcd", BUFF_SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } if (mbstowcs(w_string2, "abcz", BUFF_SIZE) == (size_t)-1) { perror("mbstowcs"); exit(EXIT_FAILURE); } /* Collate string 1 and string 2 and store the result. */ errno = 0; coll_result = wcscoll(w_string1, w_string2); if (errno) { perror("wcscoll"); exit(EXIT_FAILURE); } else { /* Transform the strings (using wcsxfrm) into w_string3 */ /* and w_string4. */ wcsxfrm_result1 = wcsxfrm(w_string3, w_string1, BUFF_SIZE); REF-810 wcsxfrm if (wcsxfrm_result1 == ((size_t) - 1)) perror("wcsxfrm"); else if (wcsxfrm_result1 > BUFF_SIZE) { perror("\n** String is too long **\n"); exit(EXIT_FAILURE); } else { wcsxfrm_result2 = wcsxfrm(w_string4, w_string2, BUFF_ SIZE); if (wcsxfrm_result2 == ((size_t) - 1)) { perror("wcsxfrm"); exit(EXIT_FAILURE); } else if (wcsxfrm_result2 > BUFF_SIZE) { perror("\n** String is too long **\n"); exit(EXIT_FAILURE); } /* Compare the two transformed strings and verify that */ /* the result is the same as the result from wcscoll on */ /* the original strings. */ else { wcscmp_result = wcscmp(w_string3, w_string4); if (wcscmp_result == 0 && (coll_result == 0)) { printf("\nReturn value from wcscoll() and return value" " from wcscmp() are both zero."); printf("\nThe program was successful\n\n"); } else if ((wcscmp_result < 0) && (coll_result < 0)) { printf("\nReturn value from wcscoll() and return value" " from wcscmp() are less than zero."); printf("\nThe program was successful\n\n"); } else if ((wcscmp_result > 0) && (coll_result > 0)) { printf("\nReturn value from wcscoll() and return value" " from wcscmp() are greater than zero."); printf("\nThe program was successful\n\n"); } else { printf("** Error **\n"); printf("\nReturn values are not of the same type"); } } REF-811 wcsxfrm } } } Running the example program produces the following result: Return value from wcscoll() and return value from wcscmp() are less than zero. The program was successful REF-812 wctob _________________________________________________________________ wctob Determines if a wide character corresponds to a single-byte multibyte character and returns its multibyte character representation. Format #include #include int wctob (wint_t c); Arguments c The wide character to be converted to a single-byte multibyte character. Description This function determines whether the specified wide character corresponds to a single-byte multibyte character when in the initial shift state and, if so, returns its multibyte character representation. Return Values x The single-byte representation of the wide character specified. EOF Indicates an error. The wide character specified does not correspond to a single-byte multibyte character. REF-813 wctomb _________________________________________________________________ wctomb Converts a wide character to its multibyte character representation. Format #include int wctomb (char *s, wchar_t wchar); Arguments s A pointer to the resulting multibyte character. wchar The code for the wide character. Description This function converts the wide character specified by wchar to its multibyte character representation. If s is NULL, then 0 is returned. Otherwise, the number of bytes comprising the multibyte character is returned. At most, MB_CUR_MAX bytes are stored in the array object pointed to by s. This function is affected by the LC_CTYPE category of the program's current locale. Return Values x The number of bytes comprising the multibyte character corresponding to wchar. 0 If s is NULL. -1 If wchar is not a valid character. REF-814 wctrans _________________________________________________________________ wctrans Returns the description of a mapping, corresponding to specified property, that can later be used in a call to towctrans. Format #include wctrans_t wctrans (const char *property); Arguments property The name of the mapping. The following property names are defined for all locales: o "touppper" o "tolower" Additional property names may also be defined in the LC_ CTYPE category of the current locale. Description This function constructs a value with type wctrans_t that describes a mapping between wide characters identified by the property argument. See also towctrans in this section. Return Values nonzero According to the LC_CTYPE category of the current program locale, the string specified as a property argument is the name of an existing character mapping. The value returned can be used in a call to the towctrans function. REF-815 wctrans 0 Indicates an error. The property argument does not identify a character mapping in the current program's locale. REF-816 wctype _________________________________________________________________ wctype Used for defining a character class. The value returned by this function is used in calls to the iswctype function. Format #include (ISO C) #include (XPG4) wctype_t wctype (const char *char_class); Arguments char_class A pointer to a valid character class name. Description This function converts a valid character class defined for the current locale to an object of type wctype_t. The following character class names are defined for all locales: alnum cntrl lower space alpha digit print upper blank graph punct xdigit Additional character class names may also be defined in the LC_CTYPE category of the current locale. See also iswctype in this section. Return Values x An object of type wctype_t that can be used in calls to the iswctype function. 0 If the character class name is not valid for the current locale. REF-817 wctype Example #include #include #include #include #include #include /* This test will set up a number of character class using wctype() */ /* and then verify whether calls to iswctype() using these classes */ /* produce the same results as calls to the is**** routines. */ main() { wchar_t w_char; wctype_t ret_val; char *character = "A"; /* Convert character to wide character format - w_char */ if (mbtowc(&w_char, character, 1) == -1) { perror("mbtowc"); exit(EXIT_FAILURE); } /* Check if results from iswalnum() matches check on alnum */ /* character class */ if ((iswalnum((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("alnum")))) printf("[%C] is a member of the character class alnum\n", w_ char); else printf("[%C] is not a member of the character class alnum\n", w_ char); /* Check if results from iswalpha() matches check on alpha */ /* character class */ if ((iswalpha((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("alpha")))) printf("[%C] is a member of the character class alpha\n", w_ REF-818 wctype char); else printf("[%C] is not a member of the character class alpha\n", w_ char); /* Check if results from iswcntrl() matches check on cntrl */ /* character class */ if ((iswcntrl((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("cntrl")))) printf("[%C] is a member of the character class cntrl\n", w_ char); else printf("[%C] is not a member of the character class cntrl\n", w_ char); /* Check if results from iswdigit() matches check on digit */ /* character class */ if ((iswdigit((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("digit")))) printf("[%C] is a member of the character class digit\n", w_ char); else printf("[%C] is not a member of the character class digit\n", w_ char); /* Check if results from iswgraph() matches check on graph */ /* character class */ if ((iswgraph((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("graph")))) printf("[%C] is a member of the character class graph\n", w_ char); else printf("[%C] is not a member of the character class graph\n", w_ char); /* Check if results from iswlower() matches check on lower */ /* character class */ if ((iswlower((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("lower")))) printf("[%C] is a member of the character class lower\n", w_ char); else printf("[%C] is not a member of the character class lower\n", w_ REF-819 wctype char); /* Check if results from iswprint() matches check on print */ /* character class */ if ((iswprint((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("print")))) printf("[%C] is a member of the character class print\n", w_ char); else printf("[%C] is not a member of the character class print\n", w_ char); /* Check if results from iswpunct() matches check on punct */ /* character class */ if ((iswpunct((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("punct")))) printf("[%C] is a member of the character class punct\n", w_ char); else printf("[%C] is not a member of the character class punct\n", w_ char); /* Check if results from iswspace() matches check on space */ /* character class */ if ((iswspace((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("space")))) printf("[%C] is a member of the character class space\n", w_ char); else printf("[%C] is not a member of the character class space\n", w_ char); /* Check if results from iswupper() matches check on upper */ /* character class */ if ((iswupper((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("upper")))) printf("[%C] is a member of the character class upper\n", w_ char); else printf("[%C] is not a member of the character class upper\n", w_ char); /* Check if results from iswxdigit() matches check on xdigit */ /* character class */ REF-820 wctype if ((iswxdigit((wint_t) w_char)) && (iswctype((wint_t) w_char, wctype("xdigit")))) printf("[%C] is a member of the character class xdigit\n", w_ char); else printf("[%C] is not a member of the character class xdigit\n", w_ char); } Running this example produces the following result: [A] is a member of the character class alnum [A] is a member of the character class alpha [A] is not a member of the character class cntrl [A] is not a member of the character class digit [A] is a member of the character class graph [A] is not a member of the character class lower [A] is a member of the character class print [A] is not a member of the character class punct [A] is not a member of the character class space [A] is a member of the character class upper [A] is a member of the character class xdigit REF-821 wcwidth _________________________________________________________________ wcwidth Determines the number of printing positions on a display device required for the specified wide character. Format #include int wcwidth (wchar_t wc); Arguments wc A wide character. Description This function determines the number of column positions needed for the specified wide character wc. The value of wc must be a valid wide character in the current locale. Return Values x The number of printing positions required for wc. 0 If wc is a null character. -1 Indicates that wc does not represent a valid printing wide character. REF-822 wmemchr _________________________________________________________________ wmemchr Locates the first occurence of a specified wide character in an array of wide characters. Format #include wchar_t wmemchr (const wchar_t *s, wchar_t c, size_t n); Function Variants This function also has variants named _wmemchr32 and _ wmemchr64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s A pointer to an array of wide characters to be searched. c The wide character value to search for. n The maximum number of wide characters in the array to be searched. Description This function locates the first occurrence of the specified wide character in the initial n wide characters of the array pointed to by s. REF-823 wmemchr Return Values x A pointer to the first occurrence of the wide character in the array. NULL The specified wide character does not occur in the array. REF-824 wmemcmp _________________________________________________________________ wmemcmp Compares two arrays of wide characters. Format #include int wmemcmp (const wchar_t *s1, const wchar_t *s2, size_t n); Arguments s1, s2 Pointers to wide-character arrays. n The maximum number of wide characters to be compared. Description This function compares the first n wide characters of the array pointed to by s1 with the first n wide characters of the array pointed to by s2. The wide characters are compared not according to locale-dependent collation rules, but as integral objects of type wchar_t. Return Values 0 Arrays are equal. Positive value The first array is greater than the second. Negative value The first array is less than the second. REF-825 wmemcpy _________________________________________________________________ wmemcpy Copies a specified number of wide characters from one wide- character array to another. Format #include wchar_t wmemcpy (wchar_t *dest, const wchar_t *source, size_t n); Function Variants This function also has variants named _wmemcpy32 and _ wmemcpy64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest A pointer to the destination array. source A pointer to the source array. n The number of wide characters to be copied. Description This function copies n wide characters from the array pointed to by source to the array pointed to by dest. Return Values x The value of dest. REF-826 wmemmove _________________________________________________________________ wmemmove Copies a specified number of wide characters from one wide- character array to another. Format #include wchar_t wmemmove (wchar_t *dest, const wchar_t *source, size_t n); Function Variants This function also has variants named _wmemmove32 and _ wmemmove64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments dest A pointer to the destination array. source A pointer to the source array. n The number of wide characters to be moved. Description This function copies n wide characters from the location pointed to by source to the location pointed to by dest. The wmemmove and wmemcpy routines perform the same function, except that wmemmove ensures that the original contents of the source array are copied to the destination array even if the two arrays overlap. Where such overlap is possible, programs that require portability should use wmemmove, not wmemcopy. REF-827 wmemmove Return Values x The value of dest. REF-828 wmemset _________________________________________________________________ wmemset Sets a specified value to a specified number of wide characters in an array of wide characters. Format #include wchar_t wmemset (wchar_t *s, wchar_t c, size_t n); Function Variants This function also has variants named _wmemset32 and _ wmemset64 for use with 32-bit and 64-bit pointer sizes, respectively. See Section 1.8 for more information on using pointer-size-specific functions. Arguments s A pointer to the array of wide characters. c The value to be placed in the first n wide characters of the array. n The number of wide characters to be set to the specified value c. Description This function copies the value of c into each of the first n wide characters of the array pointed to by s. Return Values x The value of s. REF-829 wprintf _________________________________________________________________ wprintf Performs formatted output from the standard output (stdout). See Chapter 2 for information on format specifiers. Format #include int wprintf (const wchar_t *format, . . . ); Arguments format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose resultant types correspond to conversion specifications given in the format specification. If no conversion specifications are given, the output sources can be omitted. Otherwise, the function calls must have exactly as many output sources as there are conversion specifications, and the conversion specifications must match the types of the output sources. Conversion specifications are matched to output sources in left-to-right order. Excess output pointers, if any, are ignored. Description This function is equivalent to the fwprintf function with the stdout argument interposed before the wprintf arguments. REF-830 wprintf Return Values n The number of wide characters written. REF-831 wprintf Negative value Indicates an error. The function sets errno to one of the following: o EILSEQ - Invalid character detected. o EINVAL - Insufficient arguments. o ENOMEM - Not enough memory available for conversion. o ERANGE - Floating-point calculations overflow. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This might indicate that conversion to a numeric value failed because of overflow. The function can also set errno to the following as a result of errors returned from the I/O subsystem: o EBADF - The file descriptor is not valid. o EIO - I/O error. o ENOSPC - No free space on the device containing the file. o ENXIO - Device does not exist. o EPIPE - Broken pipe. o ESPIPE - Illegal seek in a file opened for append. o EVMSERR - Nontranslatable VMS error. vaxc$errno contains the VMS error code. This indicates that an I/O error occurred for which there is no equivalent C error code. REF-832 wrapok _________________________________________________________________ wrapok In the UNIX system environment, allows the wrapping of a word from the right border of the window to the beginning of the next line. This routine is provided only for UNIX software compatibility and serves no function in the OpenVMS environment. Format #include wrapok (WINDOW *win, bool boolf); Arguments win A pointer to the window. boolf A Boolean TRUE or FALSE value. If boolf is FALSE, scrolling is not allowed. This is the default setting. The bool type is defined in the header file as follows: #define bool int REF-833 write _________________________________________________________________ write Writes a specified number of bytes from a buffer to a file. Format #include ssize_t write (int file_desc, void *buffer, size_t nbytes); (ISO POSIX-1) int write (int file_desc, void *buffer, int nbytes); (Compatability) Arguments file_desc A file descriptor that refers to a file currently opened for writing or updating. buffer The address of contiguous storage from which the output data is taken. nbytes The maximum number of bytes involved in the write operation. Description If the write is to an RMS record file and the buffer contains embedded new-line characters, more than one record may be written to the file. Even if there are no embedded new-line characters, if nbytes is greater than the maximum record size for the file, more than one record will be written to the file. The write function always generates at least one record. If the write is to a mailbox and the third argument, nbytes, specifies a length of 0, an end-of-file message is written to the mailbox. This occurs for mailboxes created by the application using SYS$CREMBX, but not for mailboxes created to implement POSIX pipes. For more information, see Chapter 5. REF-834 write Return Values x The number of bytes written. -1 Indicates errors, including undefined file descriptors, illegal buffer addresses, and physical I/O errors. REF-835 writev _________________________________________________________________ writev Writes to a file. Format #include ssize_t writev (int fildes, const struct iovec *iov, int iovcnt); Argument filedes A file descriptor that refers to a file currently opened for writing or updating. iov Array of iovec structures from which the output data is gathered. iovcnt The number of buffers specified by the members of the iov array. Description The writev function is equivalent to write but gathers the output data from the iovcnt buffers specified by the members of the iov array: iov[0], iov[1], ..., iov[iovcnt- 1]. The iovcnt argument is valid if greater than 0 and less than or equal to {IOV_MAX}, defined in . Each iovec entry specifies the base address and length of an area in memory from which data should be written. The writev function writes a complete area before proceeding to the next. If filedes refers to a regular file and all of the iov_ len members in the array pointed to by iov are 0, writev returns 0 and has no other effect. For other file types, the behavior is unspecified. REF-836 writev If the sum of the iov_len values is greater than SSIZE_MAX, the operation fails and no data is transferred. Upon successful completion, writev returns the number of bytes actually written. Otherwise, it returns a value of -1, the file-pointer remains unchanged, and errno is set to indicate an error. Return Values x The number of bytes written. -1 Indicates an error. The file times do not change, and the function sets errno to one of the following values: o EBADF - The filedes argument is not a valid file descriptor open for writing. o EINTR - The write operation was terminated due to the receipt of a signal, and no data was transferred. o EINVAL - The sum of the iov_len values in the iov array would overflow an ssize_t, or the iovcnt argument was less than or equal to 0, or greater than {IOV_MAX}. o EIO - A physical I/O error has occurred. o ENOSPC - There was no free space remaining on the device containing the file. o EPIPE - An attempt is made to write to a pipe or FIFO that is not open for reading by any process, or that only has one end open. A SIGPIPE signal will also be sent to the thread. REF-837 wscanf _________________________________________________________________ wscanf Reads input from the standard input (stdin) under control of the wide-character format string. Format #include int wscanf (const wchar_t *format, . . . ); Arguments format A pointer to a wide-character string containing the format specifications. For more information about format and conversion specifications and their corresponding arguments, see Chapter 2. . . . Optional expressions whose results correspond to conversion specifications given in the format specification. If no conversion specifications are given, you can omit the input pointers. Otherwise, the function calls must have exactly as many input pointers as there are conversion specifications, and the conversion specifications must match the types of the input pointers. Conversion specifications are matched to input sources in left-to-right order. Excess input pointers, if any, are ignored. Description This function is equivalent to the fwscanf function with the stdin arguments interposed before the wscanf arguments. REF-838 wscanf Return Values n The number of input items assigned. The number can be less than provided for, even zero, in the event of an early matching failure. EOF Indicates an error. An input failure occurred before any conversion. REF-839 A _________________________________________________________________ Compaq C Socket Routine Reference This appendix describes the aspects of the Compaq C language that pertain to the writing of Internet application programs for the TCP/IP Services for OpenVMS product (formerly the VMS/ULTRIX Connection). TCP/IP Services for OpenVMS is the Compaq implementation of the TCP/IP (Transmission Control Protocol/Internet Protocol) protocol. For a description of Internet details, such as protocols, protocol types, and sockets, see the TCP/IP Services for OpenVMS System Management. For more information on how to write socket programs, see the UNIX Supplementary Documents, System Manager. A.1 Porting Considerations This section contains information that you should consider when writing Internet application programs for the TCP/IP Services for OpenVMS. These considerations will help to make your programs more portable. A.1.1 Calling an IPC Routine from an AST State Calls to various Interprocess Communication (IPC) routines use a static area within which they return information. The OpenVMS environment allows an asynchronous system trap (AST) routine to interrupt an IPC routine during its execution. In addition, the ASTs of more privileged modes can interrupt ASTs of less privileged modes. Therefore, caution needs to be observed when calling an IPC routine from an AST state, while a similar IPC routine is being called from a non-AST state or a less privileged mode. The IPC routines that use a static area are: o gethostbyaddr o gethostbyname Compaq C Socket Routine Reference A-1 o getnetbyaddr o getnetbyname In VMS Version 5.2, sockets should not be created or destroyed within ASTs. A.1.2 Calling from KERNEL or EXEC Modes Several IPC routines access files in order to retrieve their information. These routines should not be called from either the KERNEL or EXEC modes when ASTs are disabled. These IPC routines are: o gethostbyaddr o gethostbyname o getnetbyaddr o getnetbyname A.1.3 Event Flags IPC routines may use event flags during their operation. The event flags are assigned by using the library routine LIB$GET_EF and are released when the routine no longer needs them. A.1.4 Suppressing Compaq C Compilation Warnings Certain parameters to the IPC routines may require type casting to suppress Compaq C compilation warnings. Type casting is required because of parameter prototyping, which the Compaq C header (.h) files have in order to be ANSI compliant. These header files are unlike UNIX header files, whose IPC routines are not parameter prototyped. A.1.5 Header Files It is acceptable to include header files on an OpenVMS system without using angle brackets (< >) or double quotes (" "). For example, #include types. This form of the #include preprocessor directive is possible on OpenVMS systems because all header files are located in a text library in SYS$LIBRARY. On UNIX systems, however, header files must be specified with angle brackets (< >) or double quotes (" ") and any subdirectories that are needed to locate a header file. For example, to include the header A-2 Compaq C Socket Routine Reference file socket.h, use the following form of the #include directive: #include A.2 Compaq C Structures The socket routines make use of several Compaq C structures. Table A-1 lists these structures and the header files in which they are defined. Table_A-1_Structures_Used_by_Socket_Routines_______________ Structure Name________Header_File____________________________________ in_addr sock_addr_ in hostent netent servent linger sock_addr msghdr timeval iovec_______________________________________________ A.3 Internet Protocols The Internet protocol family is a collection of protocols layered on the Internet Protocol (IP) transport layer, and using the Internet address format. This section describes the Transmission Control Protocol and User Datagram Protocol. Compaq C Socket Routine Reference A-3 A.3.1 Transmission Control Protocol The Transmission Control Protocol (TCP) provides a reliable, flow-controlled, two-way transmission of data. It is a byte-stream protocol used to support the SOCK_STREAM abstraction. TCP uses the standard Internet address format and, in addition, provides a per host collection of port addresses. Thus, each address is composed of an Internet address specifying the host and network with a specific TCP port on the host identifying the peer entity. Sockets utilizing the TCP protocol are either active or passive. Active sockets initiate connections to passive sockets. By default, TCP sockets are created active; to create a passive socket the listen system call must be used after binding the socket with the bind system call. Only passive sockets may use the accept call to accept incoming connections. Only active sockets may use the connect call to initiate connections. Passive sockets may underspecify their location to match incoming connection requests from multiple networks. This technique, called wildcard addressing, allows a single server to provide service to clients on multiple networks. To create a socket that listens to all hosts on any network, the Internet address INADDR_ANY must be bound. The TCP port must be specified at this time. If the Internet address is not INADDR and the port is not specified, the system will assign a port. Once a connection has been established, the socket's address is fixed by the peer entity's location. The address assigned to the socket is the address associated with the network interface through which packets are being transmitted and received. Normally this address corresponds to the peer entity's network. TCP supports one socket option that is set with setsockopt and tested with getsockopt. Under most circumstances, TCP sends data when it is presented; when outstanding data has not yet been acknowledged, it gathers small amounts of output to be sent in a single packet once an acnowledgement is received. For a small number of clients, such as window systems that send a stream of mouse events that receive no replies, this packetization may cause significant delays. Therefore, TCP provides a Boolean option, TCP_NODELAY (from A-4 Compaq C Socket Routine Reference ), to defeat this algorithm. The option level for the setsockopt call is the protocol number for TCP, which is available from getprotobyname. A.3.2 User Datagram Protocol User Datagram Protocol (UDP) is a simple, unreliable datagram protocol used to support the SOCK_DGRAM abstraction for the Internet protocol family. UDP sockets are connectionless and are normally used with the sendto and recvfrom calls, though the connect call may also be used to fix the destination for future packets (in which case the recv or read or write system calls may be used). UDP address formats are identical to those used by TCP. In particular, UDP provides a port identifier in addition to the normal Internet address format. Note that the UDP port space is separate from the TCP port space (for example, a UDP port may not be connected to a TCP port). Also, broadcast packets may be sent (assuming the underlying network supports this) by using a reserved broadcast address; this address is network interface dependent. The SO_BROADCAST option must be set on the socket and the process must have the SYSPRV or BYPASS privilege for broadcasting to succeed. A.4 errno Values errno is an external variable whose value is set whenever an error occurs during a call to any of the Compaq C RTL routines. You can use this value to obtain a more detailed description of the error. errno is not cleared on successful calls, so its value should be checked only when an error has been indicated. Most calls to the Compaq C RTL routines have one or more returned values. Any error condition is indicated by an otherwise impossible return value. This is almost always -1; the individual routine descriptions specify the details. All return codes and values from routines are of type int unless otherwise noted. An error number is also made available in the external variable errno, which is not cleared on successful calls. The errno values may be translated to a message, similar to that found in UNIX Compaq C Socket Routine Reference A-5 systems, by using the perror routine. vaxc$errno may also be returned as an error. ________________________ NOTE ________________________ The notation [...] is used in this manual to denote an errno error. ______________________________________________________ Table A-2 lists the errno values. Table_A-2_errno_Values_____________________________________ Value_________________Meaning______________________________ EINPROGRESS Operation now in progress An operation that takes a long time to complete, such as connect, was attempted on a nonblocking object. EALREADY Operation already in progress An operation was attempted on a nonblocking object that already had an operation in progress. ENOTSOCK Socket operation on a non-socket EDESTADDRREQ Destination address required A required address was omitted from an operation on a socket. EMSGSIZE Message too long A message sent on a socket was larger than the internal message buffer. EPROTOTYPE Protocol wrong type for socket A protocol was specified that does not support the semantics of the socket type requested. For example, you cannot use the ARPA Internet UDP protocol with type SOCK_STREAM. ENOPROTOOPT Protocol not available (continued on next page) A-6 Compaq C Socket Routine Reference Table_A-2_(Cont.)_errno_Values_____________________________ Value_________________Meaning______________________________ A bad option was specified in a getsockopt or setsocketopt call. EPROTONOSUPPORT Protocol not supported The protocol has not been configured into the system or no implementation for it exists. ESOCKTNOSUPPORT Socket type not supported The support for the socket type has not been configured into the system or no implementation for it exists. EOPNOTSUPP Error-operation not supported For example, trying to accept a connection on a datagram socket. EPFNOSUPPORT Protocol family not supported The protocol family has not been configured into the system or no implementation for it exists. EAFNOSUPPORT Address family not supported by protocol family An address incompatible with the requested protocol was used. EADDRINUSE Address already in use Each address can be used only once. EADDRNOTAVAIL Cannot assign requested address Normally, results from an attempt to create a socket with an address not on this machine. ENETDOWN Network is down A socket operation encountered a dead network. ENETUNREACH Network is unreachable (continued on next page) Compaq C Socket Routine Reference A-7 Table_A-2_(Cont.)_errno_Values_____________________________ Value_________________Meaning______________________________ A socket operation was attempted to an unreachable network. ENETRESET Network dropped connection on reset The host you were connected to crashed and rebooted. ECONNABORTED Software caused connection abort A connection abort was caused internal to your host machine. ECONNRESET Connection reset by peer A connection was forcibly closed by a peer. This usually results from the peer executing a shutdown call. ENOBUFS No buffer space available An operation on a socket or pipe was not performed because the system lacked sufficient buffer space. EISCONN Socket is already connected A connect request was made on an already connected socket; or, a sendto or sendmsg request on a connected socket specified a destination other than the connected party. ENTOTCONN Socket is not connected Request to send or receive data was disallowed because the socket is not connected. ESHUTDOWN Cannot send after socket shutdown A request to send data was disallowed because the socket had already been shut down with a previous shutdown call. ETOOMANYREFS Too many references: cannot splice (continued on next page) A-8 Compaq C Socket Routine Reference Table_A-2_(Cont.)_errno_Values_____________________________ Value_________________Meaning______________________________ ETIMEDOUT Connection timed out A connect request failed because the connected party did not properly respond after a period of time. (The timeout period is dependent on the communication protocol.) A connect request or remote file operation failed because the connected party did not properly respond after a period of time that is dependent on the communication protocol. ECONNREFUSED Connection refused No connection could be made because the target machine actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host. ELOOP Too many levels of symbolic links A path name lookup involved more than eight symbolic links. ENAMETOOLONG File name too long A component of a path name exceeded 255 characters, or an entire path name exceeded 1023 characters. EHOSTDOWN Host is down A socket operation failed because the destination host was down. EHOSTUNREACH No route to host A socket operation was attempted to an unreachable host. EVMSERR OpenVMS system-specific error code ______________________that_is_nontranslatable______________ Compaq C Socket Routine Reference A-9 A.5 h_errno Values The external integer h_errno is available only with OpenVMS Version 7.0, and is set only by a 4.4BSD TCP/IP interface. Specifically, The gethostbyname and gethostbyaddr functions require 4.4BSD semantics to set h_errno. The gethostbyname and gethostbyaddr functions indicate an error condition by returning a null pointer and setting the external integer h_errno to indicate the error return status. When gethostbyname or gethostbyaddr returns an error status, h_errno, which is very similar to errno, can be checked to determine whether the error is the result of a temporary failure or an invalid or unknown host. Use the herror routine to print the error message describing the failure. If the argument string to herror is not NULL, it is printed, followed by a colon (:) and a space. The error message is printed with a trailing new- line character. ________________________ Note ________________________ The h_errno error codes are not available with the errno variable. ______________________________________________________ The header file declares h_errno on a per-thread basis as: #define h_errno (*decc$h_errno_get_addr()) The header file also symbolically defines the error code values that h_errno can accept, as follows: HOST_NOT_FOUND No such host is known. TRY_AGAIN Usually a temporary error that means the local server did not receive a response from an authoritative server. A retry at some later time can succeed. NO_RECOVERY An unexpected server failure is encountered. This is a nonrecoverable error. A-10 Compaq C Socket Routine Reference NO_DATA The requested name is valid but does not have an IP address; this is not a temporary error. The name is known to the name server but there is no address associated with this name. Another type of request to the name server using this domain name results in an answer; for example, a mail-forwarder registered for this domain. NO_ADDRESS No address; look for MX record Like errno, the value of h_errno is zero at program startup. Checking h_errno is valid only when a failure status is returned by a Compaq C RTL routine that is defined to set it. A.6 Relationship Between errno and h_errno Since the routines that set h_errno can also set errno, this section explains the relationship between the two variables. A given routine failure does not set both h_errno and errno for the same failure. A routine failure sets either h_errno or errno depending on which is appropriate for the failing condition. For example, consider the following program: /* Demonstrate relationship between errno and h_errno */ /* from Appendix A of the reference manual */ #include #include #include main() { static char hostname[256]; struct hostent *hostentptr; Compaq C Socket Routine Reference A-11 errno = 0; h_errno = 0; if ((hostentptr = gethostbyname("hndy")) == NULL) { printf("unknown host name errno is: %d h_errno is: %d\n", errno, h_errn perror("p_gethostbyname"); herror("h_gethostbyname"); } errno = 0; h_errno = 0; if ((hostentptr = gethostbyname(0)) == NULL) { printf("illegal host name errno is: %d h_errno is: %d\n", errno, h_errn perror("p_gethostbyname"); herror("h_gethostbyname"); } } In the first call to gethostbyname, the host name parameter "hndy" does not represent a known host. In this case, gethostbyname sets h_errno to HOST_NOT_FOUND, but does not set errno. The call to perror in this example would output: p_gethostbyname: Error 0 The call to herror in this example would print a message describing the failure: h_gethostbyname: Unknown In the second call to gethostbyname, the host name parameter is 0 (zero), an invalid argument. In this case, gethostbyname sets errno to EINVAL, but does not set h_ errno. A call to perror would print a message describing the failure: p_gethostbyname: Invalid A call to herror would print: h_gethostbyname: Error 0 A-12 Compaq C Socket Routine Reference A.7 TCP/IP Interface Enhancements The Compaq C RTL provides the language bindings for a 4.4BSD-compatible TCP/IP implementation. The underlying 4.4BSD semantics for the specific TCP/IP routines are the responsibility of the TCP/IP back-end vendors. With 4.4BSD semantics, gethostbyname and gethostbyaddr set the external variable h_errno. Other routines (see Table A-3) deal with 4.4BSD versions of the sockaddr and msghdr data structures. See the header file for a description of these structures. The TCP/IP backend routines need to know the following: o Whether gethostbyname and gethostbyaddr should set h_ errno. o What type of sockaddr and msghdr structures the Compaq C RTL is passing them-those defined by 4.4BSD systems, or those defined by pre-4.4BSD systems). This information is controlled by the _SOCKADDR_LEN feature-test macro (see Section 1.5). Compiling with _SOCKADDR_LEN defined will enable the entry points that have 4.4BSD semantics. See Table A-3. Otherwise, entry points expecting pre-4.4BSD semantics are enabled. Table_A-3_4.4BSD_Entry_Points______________________________ __bsd44_ __bsd44_ __bsd44_recvfrom accept gethostbyaddr __bsd44_ __bsd44_ __bsd44_recvmsg bind gethostbyname __bsd44_ __bsd44_ __bsd44_sendto connect getpeername __bsd44_ __bsd44_sendmsg ______________getsockname__________________________________ Compaq C Socket Routine Reference A-13 A.8 Summary of Socket Routines This section groups and briefly describes the socket routines. For complete descriptions, see the routine reference section that follows in this appendix. A.8.1 Basic Communication Routines Table A-4 lists the basic communication routines that make up the building blocks of Internet programs. Table_A-4_Basic_Communication_Routines_____________________ Routine__________Description_______________________________ accept Accepts a connection on a socket. bind Binds a name to a socket. close Closes a connection and deletes a socket descriptor. connect Initiates a connection on a socket. ioctl Controls socket operations only. listen Sets the maximum limit of outstanding connection requests for a socket. read Reads bytes from a file or socket and places them into a buffer. readv Not implemented. recv Receives bytes from a socket and places them into a buffer. recvfrom Receives bytes for a socket from any source. recvmsg Receives bytes from a socket and places them into scattered buffers. select Allows the polling or checking of a group of sockets. send Sends bytes through a socket to a connected peer. sendmsg Sends gathered bytes through a socket to any other socket. (continued on next page) A-14 Compaq C Socket Routine Reference Table_A-4_(Cont.)_Basic_Communication_Routines_____________ Routine__________Description_______________________________ sendto Sends bytes through a socket to any other socket. shutdown Shuts down all or part of a bidirectional socket. socket Creates an endpoint for communication by returning a socket descriptor. write Writes bytes from a buffer to a file or socket. writev___________Not_implemented.__________________________ A.8.2 Auxiliary Communication Routines Table A-5 lists the auxiliary communication routines. These routines are used to provide information about a socket and to set the options on a socket. Table_A-5_Auxiliary_Communication_Routines_________________ Routine_______Description__________________________________ getpeername Returns the name of the connected peer. getsockname Returns the name associated with a socket. getsockopt Returns the options set on a socket. setsockopt____Sets_options_on_a_socket.____________________ A.8.3 h_errno Support Routines Table A-6 lists the h_errno support routines. These routines map and write error-message strings generated by the external integer h_errno. Compaq C Socket Routine Reference A-15 Table_A-6_Supported_h_errno_Routines_______________________ Routine__________Description_______________________________ herror Writes a message explaining a routine error. hstrerror Accesses message explaining routine _________________errors.___________________________________ A.8.4 Communication Support Routines Table A-7 lists the communication support routines. These routines perform operations such as searching databases, converting byte order of network and host addresses, reading records, and returning Internet addresses. Table_A-7_Supported_Communication_Routines_________________ Routine__________Description_______________________________ decc$get_sdc Returns the socket device's OpenVMS I/O channel associated with a socket descriptor. vaxc$get_sdc and decc$get_ sdc are synonyms for the same routine. endhostent Closes retrieval of network host entries and closes the network host file. endnetent Closes the networks database file. endprotoent Closes the protocols database file. endservent Closes the network services database file. gethostaddr Returns the standard host address for the processor. gethostbyaddr Searches the host database for a host record with a given address. gethostbyname Searches the host database for a host record with a given name or alias. gethostname Returns the name of the current host. gethostent Opens the network host entry by name from the network host database file. (continued on next page) A-16 Compaq C Socket Routine Reference Table_A-7_(Cont.)_Supported_Communication_Routines_________ Routine__________Description_______________________________ getnetbyaddr Searches the network database for a network record with a given address. getnetbyname Searches the network database for a network record with a given name or alias. getnetent Gets a network file entry from the networks database file. getprotobyname Searches the protocols database until a matching protocol name is found or until EOF is encountered. getprotobynumber Searches the protocols database until a matching protocol number is found or until EOF is encountered. getprotoent Gets a protocol database entry from the protocols database file. getservbyname Gets information on the named service from the network services database. getservbyport Gets information on the named port from the network services database. getservent Gets a services file entry from the network services database file. hostalias Searches for host aliases associated with a name. htonl Converts longwords from network to host byte order. htons Converts short integers from network to host byte order. inet_addr Converts Internet addresses in text form into numeric Internet addresses. inet_lnaof Returns the local network address portion of an Internet address. inet_makeaddr Returns an Internet address given a network address and a local address on that network. (continued on next page) Compaq C Socket Routine Reference A-17 Table_A-7_(Cont.)_Supported_Communication_Routines_________ Routine__________Description_______________________________ inet_netof Returns the Internet network address portion of an Internet address. inet_network Converts a null-terminated text string representing an Internet network address into a network address in network byte order. inet_ntoa Converts an Internet address into an ASCIZ (null-terminated) string. ntohl Converts longwords from host to network byte order. ntohs Converts short integers from host to network byte order. sethostent Opens, rewinds, and closes the network host database file. setnetent Opens, rewinds, and closes the networks database file. setprotoent Opens, rewinds, and closes the protocols database file. setservent Opens, rewinds, and closes the network services database file. decc$socket_fd Returns the socket descriptor associated with a Socket Device Channel for direct use with the Compaq C RTL. vaxc$get_sdc Returns the socket device's OpenVMS I/O channel associated with a socket descriptor. vaxc$get_sdc and decc$get_ _________________sdc_are_synonyms_for_the_same_routine.____ A-18 Compaq C Socket Routine Reference accept _________________________________________________________________ accept Accepts a connection on a socket. Format #include int accept (int s, struct sockaddr *addr, int *addrlen); (_DECC_V4_SOURCE) int accept (int s, struct sockaddr *addr, size_t *addrlen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_accept. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been returned by socket, subsequently bound to an address with bind, and that is listening for connections after a listen. addr A result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the structure to which the address parameter points is determined by the domain in which the communication is occurring. This version of Compaq C supports only the Internet domain (AF_INET). addrlen A value-result parameter; it should initially contain the size of the structure pointed to by addr. On return it will contain the actual length, in bytes, of the structure that has been filled in by the communication layer. See for a description of the sockaddr structure. Compaq C Socket Routine Reference A-19 accept Description This routine completes the first connection on the queue of pending connections, creates a new socket with the same properties as s, and allocates and returns a new descriptor for the socket. If no pending connections are present on the queue, and the socket is not marked as nonblocking, accept blocks the caller until a connection request is present. If the socket is marked nonblocking by using a setsockopt call and no pending connections are present on the queue, accept returns an error. The accepted socket may not be used to accept connections. The original socket s remains open (listening) for other connection requests. This call is used with connection-based socket types, currently with SOCK_STREAM. It is possible to select a socket for the purposes of performing an accept by selecting it for read. See also bind, connect, listen, select, and socket in this section. Return Values x A nonnegative integer that is a descriptor for the accepted socket. A-20 Compaq C Socket Routine Reference accept -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EOPNOTSUPP - The reference socket is not of type SOCK_STREAM. o EFAULT - The addr parameter is not in a writable part of the user address space. o EWOULDBLOCK - The socket is marked nonblocking and no connections are present to be accepted. Compaq C Socket Routine Reference A-21 bind _________________________________________________________________ bind Binds a name to a socket. Format #include int bind (int s, struct sockaddr *name, int namelen); (_DECC_V4_SOURCE) int bind (int s, const struct sockaddr *name, size_t namelen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_bind. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket. name Address of a structure used to assign a name to the socket in the format specific to the family (AF_INET) socket address. See for a description of the sockaddr structure. namelen The size, in bytes, of the structure pointed to by name. Description This routine assigns a name to an unnamed socket. When a socket is created with socket it exists in a name space (address family) but has no name assigned. The bind routine requests that a name be assigned to the socket. See also connect, getsockname, listen, and socket in this appendix. A-22 Compaq C Socket Routine Reference bind Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following values: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EADDRNOTAVAIL - specified address is not available from the local machine. o EADDRINUSE - The specified Internet address and ports are already in use. o EINVAL - The socket is already bound to an address. o EACCESS - The requested address is protected, and the current user has inadequate permission to access it. o EFAULT - The name parameter is not a valid part of the user address space. Compaq C Socket Routine Reference A-23 close _________________________________________________________________ close Closes a connection and deletes a socket descriptor. Format #include int close (s); Argument s A socket descriptor. Description This routine deletes a descriptor from the per-process object reference table. If this is the last reference to the underlying object, then it will be deactivated. See also accept, socket, and write in this section. Return Values 0 Indicates success. -1 Indicates an error; errno is set to EBADF (The socket descriptor is invalid.) A-24 Compaq C Socket Routine Reference connect _________________________________________________________________ connect Initiates a connection on a socket. Format #include int connect (int s, struct sockaddr *name, int namelen); (_DECC_V4_SOURCE) int connect (int s, const struct sockaddr *name, size_t namelen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_connect. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket. name The address of a structure that specifies the name of the remote socket in the format specific to the address family (AF_INET). namelen The size, in bytes, of the structure pointed to by name. Description If s is a socket descriptor of type SOCK_DGRAM, then this call permanently specifies the peer to which data is to be sent. If it is of type SOCK_STREAM, then this call attempts to make a connection to another socket. Each communications space interprets the name parameter in its own way. This argument specifies the socket to which the socket specified in s is to be connected. Compaq C Socket Routine Reference A-25 connect See also accept, select, socket, getsockname, and shutdown in this appendix. Return Values 0 Indicates success. A-26 Compaq C Socket Routine Reference connect -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EADDRNOTAVAIL - specified address is not available from the local machine. o EAFNOSUPPORT - Address in the specified address family cannot be used with this socket. o EISCONN - The socket is already connected. o ETIMEOUT - Connection establishment timed out without establishing a connection. o ECONNREFUSED - The attempt to connect was forcefully rejected. o ENETUNREACH - The network is not reachable from this host. o EADDRINUSE - The specified Internet address and ports are already in use. o EFAULT - The name parameter is not a valid part of the user address space. o EWOULDBLOCK - The socket is nonblocking and the connection cannot be completed immediately. It is possible to select the socket while it is connecting by selecting it for writing. Compaq C Socket Routine Reference A-27 decc$get_sdc _________________________________________________________________ decc$get_sdc Returns the Socket Device Channel (SDC) associated with a socket descriptor for direct use with the TCP/IP Services for OpenVMS product. Format #include short int decc$get_sdc (int s); Argument s A socket descriptor. Description This routine returns the SDC associated with a socket. C socket descriptors are normally used either as file descriptors or with one of the routines that take an explicit socket descriptor as its argument. C sockets are implemented using TCP/IP Services for OpenVMS Socket Device Channels. This routine returns the SDC used by a given socket descriptor so that you can use the TCP/IP Services for OpenVMS's facilities directly by means of various I/O system services ($QIO). Return Values 0 Indicates that s is not an open socket descriptor. x The SDC number. A-28 Compaq C Socket Routine Reference endhostent _________________________________________________________________ endhostent Closes host database file. Format #include void endhostent (void); Description The endhostent routine closes the network host database file, previously opened with the gethostbyaddr or gethostbyname routine. See also gethostbyaddr, and gethostbyname in this section. Errors If the endhostent routine does not exist in your TCP/IP library, then errno is set to ENOSYS. Compaq C Socket Routine Reference A-29 endnetent _________________________________________________________________ endnetent Closes the networks database file. Format #include void endnetent (void); Description The endentent routine closes the networks database file, previously opened with the getnetent, setnetent, getnetbyaddr or getnetbyname routine. See also getnetent, getnetbyaddr, getnetbyname, and setnetent in this section. Errors If the endnetent routine does not exist in your TCP/IP library, then errno is set to ENOSYS. A-30 Compaq C Socket Routine Reference endprotoent _________________________________________________________________ endprotoent Closes the protocols database file. Format #include void endprotoent (void); Description The endprotoent routine closes the network protocols database file, previously opened with the getprotoent, getprotobyname, or getprotobynumber routine. See also getprotobyname, getprotoent and getprotobynumber in this section. Errors If the endprotoent routine does not exist in your TCP/IP library, then errno is set to ENOSYS. Compaq C Socket Routine Reference A-31 endservent _________________________________________________________________ endservent Closes the network services database file. Format #include void endservent (void); Description The endservent routine closes the network services database file, previously opened with the getservent, getservbyname, or getservbyport routine. See also getservent, getservbyname, and getservbyport in this section. Errors If the endservent routine does not exist in your TCP/IP library, then errno is set to ENOSYS. A-32 Compaq C Socket Routine Reference gethostaddr _________________________________________________________________ gethostaddr Returns the standard host address for the processor. Format #include int gethostaddr (char *addr); Arguments addr A pointer to the buffer in which the standard host address for the current processor is returned. Description This system call returns the standard host address for the current processor. The returned address is null-terminated. The addr parameter must point to at least 16 bytes of free space. Host addresses are limited to 16 characters. Return Values 0 Indicates success. -1 Indicates that an error has occurred and is further specified in the global errno. Compaq C Socket Routine Reference A-33 gethostbyaddr _________________________________________________________________ gethostbyaddr Searches the host database sequentially from the beginning of the database for a host record with a given address. Format #include struct hostent *gethostbyaddr (char *addr, int len, int type); Routine Variants This socket routine has a variant named __bsd44_ gethostbyaddr. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments addr A pointer to a series of bytes in network order specifying the address of the host sought. This argument does not point to an ASCII string. len The number of bytes in the address pointed to by the addr argument. type The type of address format being sought. Currently, only AF_INET (defined in ) is supported.) Description This routine finds the first host record in the host database with the given address. The gethostbyaddr routine uses a common static area for its return values. This means that subsequent calls this routine will overwrite any existing host entry. You must make a copy of the host entry if you wish to save it. A-34 Compaq C Socket Routine Reference gethostbyaddr Return Values NULL Indicates an error. x A pointer to an object having the hostent structure. See for a description of the hostent structure. Depending on the error condition and the socket implementation selected, errno or h_errno might be set to further indicate the error. (See sections A.5 and A.6.) Compaq C Socket Routine Reference A-35 gethostbyname _________________________________________________________________ gethostbyname Searches the host database sequentially from the beginning of the database for a host record with a given name or alias. Format #include struct hostent *gethostbyname (char *name); Routine Variants This socket routine has a variant named __bsd44_ gethostbyname. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Argument name A pointer to a null-terminated character string containing the name or an alias of the host sought. Description This routine finds the first host in the host database with the given name or alias. The gethostbyname routine uses a common static area for its return values. This means that subsequent calls to this routine will overwrite any existing host entry. You must make a copy of the host entry if you wish to save it. Return Values NULL Indicates an error. A-36 Compaq C Socket Routine Reference gethostbyname x A pointer to an object having the hostent structure. See for a description of the hostent structure. Depending on the error condition and the socket implementation selected, errno or h_errno might be set to further indicate the error. (See sections A.5 and A.6.) Compaq C Socket Routine Reference A-37 gethostent _________________________________________________________________ gethostent Gets a host file entry from the network host database file. Format #include struct hostent *gethostent (void); Description The gethostent routine reads the next entry of the database, opening a connection to the database, if necessary. See the header file for a description of the hostent structure. This routine uses a common static area for its return values. Therefore, subsequent calls to this routine overwrite any existing network entry. You must make a copy of the network services entry, if you wish to save it. Return Values x A pointer to the hostent structure. NULL Indicates an error. A-38 Compaq C Socket Routine Reference gethostname _________________________________________________________________ gethostname Returns the name currently associated to the host. Format #include int gethostname (char *name, int namelen); (_DECC_V4_SOURCE) int gethostname (char *name, size_t namelen); (not _DECC_V4_SOURCE) Arguments name The address of a buffer into which the name should be written. The returned name is null-terminated unless sufficient space is not provided. namelen The size of the buffer pointed to by name. Description This routine returns the hostname maintained by the TCP/IP Services for OpenVMS or compatible TCP/IP product. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EFAULT - The buffer decribed by name and namelen is not a valid, writable part of the user address space. o EINVAL - The returned name is an invalid address. Compaq C Socket Routine Reference A-39 getnetbyaddr _________________________________________________________________ getnetbyaddr Searches the network database sequentially from the beginning of the database for a network record with a given address. Format #include struct netent *getnetbyaddr (long net, int type); Arguments net The network number, in host byte order, of the network database entry required. type The type of network sought. Currently, only AF_INET (defined in ) is supported.) Description This routine finds the first network record in the network database with the given address. The getnetent, getnetbyaddr, and getnetbyname routines all use a common static area for their return values. This means that subsequent calls to any of these routines will overwrite any existing network entry. You must make a copy of the network entry if you wish to save it. Return Values NULL Indicates EOF or an error. x A pointer to an object having the netent structure. See the header file for a description of the netent structure. A-40 Compaq C Socket Routine Reference getnetbyname _________________________________________________________________ getnetbyname Searches the network database sequentially from the beginning of the database for a network record with a given name or alias. Format #include struct netent *getnetbyname (char *name); Argument name A pointer to a null-terminated character string of the name or an alias of the network sought. Description This routine finds the first host in the network database with the given name or alias. The getnetent, getnetbyaddr, and getnetbyname routines all use a common static area for their return values. This means that subsequent calls to any of these routines will overwrite any existing network entry. You must make a copy of the network entry if you wish to save it. Return Values NULL Indicates EOF or an error; errno is set to EFAULT (The buffer described by name is not a valid, writable part of the user address space.) Compaq C Socket Routine Reference A-41 getnetbyname x A pointer to an object having the netent structure. See the header file for a description of the netent structure. Depending on the error condition and the socket implementation selected, errno or h_errno might be set to further indicate the error. (See sections A.5 and A.6.) A-42 Compaq C Socket Routine Reference getnetent _________________________________________________________________ getnetent Gets a network file entry from the networks database file. Format #include struct netent *getnetnet (void); Description The getnetent routine opens and sequentially reads the networks database file to retrieve network information. See the header file for a description of the netent structure. The getnetent routine uses a common static area for its return values, so subsequent calls to this routine overwrite any existing network entry. You must make a copy of the network services entry, if you wish to save it. See also setnetent, and endnetent in this section. Return Values x A pointer to a netent structure. 0 Indicates an error or EOF. Compaq C Socket Routine Reference A-43 getpeername _________________________________________________________________ getpeername Returns the name of the connected peer. Format #include int getpeername (int s, struct sockaddr *name, int *namelen); (_DECC_V4_SOURCE) int getpeername (int s, struct sockaddr *name, size_t *namelen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_ getpeername. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created using socket. name A pointer to a buffer within which the peer name is to be returned. namelen An address of an integer that specifies the size of the name buffer. On return, it will be modified to reflect the actual length, in bytes, of the name returned. Description This routine returns the name of the peer connected to the socket descriptor specified. See also bind, getsockname, and socket in this appendix. A-44 Compaq C Socket Routine Reference getpeername Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EBADF - The descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o ENOTCONN - The socket is not connected. o ENOBUFS - Resources were insufficient in the system to perform the operation. o EFAULT - The name parameter is not a valid part of the user address space. Compaq C Socket Routine Reference A-45 getprotobyname _________________________________________________________________ getprotobyname Searches the protocols database until a matching protocol name is found or until EOF is encountered. Format #include struct protoent *getprotobyname (char *name); Argument name A pointer to a string containing the desired protocol name. Description This routine returns a pointer to a protoent structure containing the broken-out fields of the requested line from the protocols database. See the header file for a description of the protoent structure. See also getprotoent and getprotobynumber in this section. Return Values NULL Indicates EOF or an error. x A pointer to a protoent structure. A-46 Compaq C Socket Routine Reference getprotobynumber _________________________________________________________________ getprotobynumber Searches the protocols database until a matching protocol number is found or until an EOF is encountered. Format #include struct protoent *getprotobynumber (int *proto); Argument proto A pointer to a string containing the desired protocol number. Description This routine returns a pointer to a protoent structure containing the broken-out fields of the requested line from the protocols database. See the header file for a description of the protoent structure. See also getprotoent and getprotobyname in this section. Return Values NULL Indicates EOF or an error. x A pointer to a protoent structure. Compaq C Socket Routine Reference A-47 getprotoent _________________________________________________________________ getprotoent Gets a protocol database entry from the protocols database file. Format #include struct protoent *getprotoent (void); Description The getprotoent routine reads the next entry of the database, opening a connection to the database, if necessary. See the header file for a description of the protoent structure. See also getprotobyname, getprotobynumber, setprotoent, and endprotoent in this section. Return Values x A pointer to a protoent structure. NULL Indicates an error or EOF. A-48 Compaq C Socket Routine Reference getservbyname _________________________________________________________________ getservbyname Gets information on the named service from the network services database. Format #include struct servent *getservbyname (char *name, char *proto); Arguments name A pointer to a string containing the name of the service about which information is required. proto A pointer to a string containing the name of the protocol to search for. Description This routine searches sequentially from the beginning of the file until a matching service name is found, or until an EOF is encountered. If a protocol name is also supplied (non-NULL), searches must also match the protocol. This routine returns a pointer to a servent structure containing the broken-out fields of the requested line in the network services database. See the header file for a description of the servent structure. All information is contained in a static area, so it must be copied if it is to be saved. See also getservbyport in this section. Compaq C Socket Routine Reference A-49 getservbyname Return Values NULL Indicates EOF or an error. x A pointer to a servent structure. A-50 Compaq C Socket Routine Reference getservbyport _________________________________________________________________ getservbyport Gets information on the specified port from the network services database. Format #include struct servent *getservbyport (int port, char *proto); Arguments port The port number to search for. proto A pointer to a string containing the name of the protocol to search for. Description This routine searches sequentially from the beginning of the file until a matching port is found, or until an EOF is encountered. If a protocol name is also supplied (non- NULL), searches must also match the protocol. This routine returns a pointer to a servent structure containing the broken-out fields of the requested line in the network services database. See the header file for a description of the servent structure. All information is contained in a static area, so it must be copied if it is to be saved. See also getservbyname in this section. Return Values NULL Indicates EOF or an error. x A pointer to a servent structure. Compaq C Socket Routine Reference A-51 getservent _________________________________________________________________ getservent Gets a services file entry from the network services database file. Format #include struct servent *getservent (void); Description The getservent routine reads the next line of the network services database file, opening a connection to the database, if necessary. This routine returns a servent structure that contains fields for a line of information from the network services database file. See the header file for a description of the hostent structure. This routine uses a common static area for its return values, so subsequent calls to this routine overwrite any existing network entry. You must make a copy of the network services entry, if you wish to save it. See also setservent, and endservent in this section. Return Values x A pointer to a servent structure. NULL Indicates an error or EOF. A-52 Compaq C Socket Routine Reference getsockname _________________________________________________________________ getsockname Returns the name associated with a socket. Format #include int getsockname (int s, struct sockaddr *name, int *namelen); (_DECC_V4_SOURCE) int getsockname (int s, struct sockaddr *name, size_t *namelen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_ getsockname. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor created with socket and bound to the socket name with bind. name A pointer to the buffer in which getsockname should return the socket name. namelen A pointer to an integer specifying the size of the buffer pointed to by name. On return, the integer contains the actual size of the name returned, in bytes. Description This routine returns the current name for the specified socket descriptor. The name is a format specific to the address family (AF_INET) assigned to the socket. bind makes the association of the name to the socket, not getsockname. Compaq C Socket Routine Reference A-53 getsockname See also bind and socket in this appendix. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EBADF - The descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o ENOBUFS - Resources were insufficient in the system to perform the operation. o EFAULT - The name parameter is not a valid part of the user address space. A-54 Compaq C Socket Routine Reference getsockopt _________________________________________________________________ getsockopt Returns the options set on a socket. Format #include int getsockopt (int s, int level, int optname, char *optval, int *optlen); (_DECC_V4_SOURCE) int getsockopt (int s, int level, int optname, void *optval, size_t *optlen); (not _DECC_V4_SOURCE) Arguments s A socket descriptor created by socket. level The protocol level for which the socket options are desired. It may have one of the following values: SOL_SOCKET Get the options at the socket level. p Any protocol number. Get the options for protocol level p. See the file for the various IPPROTO values. optname Is interpreted by the protocol that is specified in the level. Options at each protocol level are documented with the protocol. See setsockopt in this section for socket level options. optval Points to a buffer in which the value of the specified option should be placed by getsockopt. optlen Points to an integer containing the size of the buffer pointed to by optval. On return, the integer will be modified to contain the actual size of the option value returned. Compaq C Socket Routine Reference A-55 getsockopt Description This routine gets information on socket options. See the appropriate protocol for information on available options at each protocol level. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EBADF - The descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o ENOPROTOOPT - The option is unknown or the protocol is unsupported. A-56 Compaq C Socket Routine Reference herror _________________________________________________________________ herror Writes a message to standard error explaining h_error. Format #include void herror (const char *string); Arguments string A user-printable string. Description The herror routine maps the error number in the external variable h_errno to a locale-dependent error message. Compaq C Socket Routine Reference A-57 hstrerror _________________________________________________________________ hstrerror Returns an error message string. Format #include char *hstrerror (int errnum); Arguments errnum An error number specifying a value of h_errno. Description The hstrerror routine maps the error number specified by the errnum parameter to a locale-dependent error message string and returns a pointer to the string. The string pointed to by the return value cannot be modified by the program, but could be overwritten by subsequent calls to this routine. Return Values x A pointer to the generated message string. -1 On error, errno might be set, but no return value is reserved to indicate an error. Errors If the hstrerror routine fails, errno is set to one of the following values: o EINVAL - The errnum parameter is an invalid error number. A-58 Compaq C Socket Routine Reference hostalias _________________________________________________________________ hostalias Searches for host aliases associated with a name. Format #include char *hostalias (const char *name); Arguments name Points to the name of the host that you want to retrieve aliases from. Description The hostalias routine searches for the alias associated with the name parameter. The HOSTALIASES environment variable defines the name of a file where you can find the host aliases, in the form: host alias Return Values x The host alias. NULL Indicates an error. Compaq C Socket Routine Reference A-59 htonl _________________________________________________________________ htonl Converts longwords from host to network byte order. Format #include unsigned long int htonl (unsigned long int hostlong); Argument hostlong A longword in host (VAX system) byte order. All integers on VAX systems are in host byte order unless otherwise specified. Description This routine converts 32-bit unsigned integers from host byte order to network byte order. The network byte order is the format in which data bytes are supposed to be transmitted through a network. All hosts on a network must send data in network byte order. Not all hosts have an internal data representation format that is identical to the network byte order. The host byte order is the format in which bytes are ordered internally on a specific host. The host byte order on VAX systems differs from the network order. This routine is most often used with Internet addresses and ports as returned by gethostent and getservent, and when manipulating values in the structures. Network byte-order places the byte with the most significant bits at lower addresses; VAX systems place the most significant bits at the highest address. A-60 Compaq C Socket Routine Reference htonl Return Value x A longword in network byte order. Compaq C Socket Routine Reference A-61 htons _________________________________________________________________ htons Converts short integers from host to network byte order. Format #include unsigned short int htons (unsigned short int hostshort); Argument hostshort A short integer in host (VAX system) byte order. All short integers on VAX systems are in host byte order unless otherwise specified. Description This routine converts 16-bit unsigned integers from host byte order to network byte order. The network byte order is the format in which data bytes are supposed to be transmitted through a network. All hosts on a network must send data in network byte order. Not all hosts have an internal data representation format that is identical to the network byte order. The host byte order is the format in which bytes are ordered internally on a specific host. The host byte order on VAX systems differs from the network order. This routine is most often used with Internet addresses and ports as returned by gethostent and getservent, and when manipulating values in the structures. Network byte order places the byte with the most significant bits at lower addresses; VAX systems place the most significant bits at the highest address. A-62 Compaq C Socket Routine Reference htons Return Value x A short integer in network byte order. Integers in network byte order cannot be used for arithmetic computation on VAX systems. Compaq C Socket Routine Reference A-63 inet_addr _________________________________________________________________ inet_addr Converts Internet addresses in text form into numeric (binary) Internet addresses. Format #include #include int inet_addr (char *cp); Argument cp A pointer to a null-terminated character string containing an Internet address in the standard Internet "." format. Description This routine returns an Internet address in network byte order when given as its argument an ASCIZ (null-terminated) string representing the address in the Internet standard "." notation. Internet addresses specified using the "." notation take one of the following forms: a.b.c.d a.b.c a.b a When four parts are specified, each is interpreted as a byte of data and assigned, from left to right, to the four bytes of an Internet address. Note that when an Internet address is viewed as a 32-bit integer quantity on VAX systems, the bytes previously referred to appear in binary as "d.c.b.a". That is, VAX bytes are ordered from least significant to most significant. When only one part is given, the value is stored directly in the network address without any byte rearrangement. A-64 Compaq C Socket Routine Reference inet_addr All numbers supplied as "parts" in a "." address expression may be decimal, octal, or hexadecimal, as specified in the C language (that is, a leading 0x or 0X implies hexadecimal; a leading 0 implies octal; otherwise, the number is interpreted as decimal). Return Values -1 Indicates that cp does not point to a proper Internet address. x An Internet address in network byte order. Compaq C Socket Routine Reference A-65 inet_lnaof _________________________________________________________________ inet_lnaof Returns the local network address portion of an Internet address. Format #include #include int inet_lnaof (struct in_addr in); Argument in An Internet address. Description This routine returns the local network address (LNA) portion of a full Internet address. Return Value x The LNA portion of an Internet address in host byte order. A-66 Compaq C Socket Routine Reference inet_makeaddr _________________________________________________________________ inet_makeaddr Returns an Internet address given a network address and a local address on that network. Format #include #include struct in_addr inet_makeaddr (int net, int lna); Arguments net An Internet network address in host byte order. lna A local network address on network net in host byte order. Description This routine combines the net and lna arguments into a single Internet address. Return Value x An Internet address in network byte order. Compaq C Socket Routine Reference A-67 inet_netof _________________________________________________________________ inet_netof Returns the Internet network address portion of an Internet address. Format #include #include int inet_netof (struct in_addr in); Argument in An Internet address. Description This routine returns the Internet network address (NET) portion of a full Internet address. Return Value x The Internet network portion of an Internet address in host byte order. A-68 Compaq C Socket Routine Reference inet_network _________________________________________________________________ inet_network Converts a text string representing an Internet network address in the standard Internet "." notation into an Internet network address as machine-format integer values. Format #include #include int inet_network (char *cp); Argument cp A pointer to an ASCIZ (null-terminated) character string containing a network address in the standard Internet "." format. Description This routine returns an Internet network address as machine-format integer values when given as its argument an ASCIZ string representing the address in the Internet standard "." notation. Return Values -1 Indicates that cp does not point to a proper Internet network address. x An Internet network address as machine-format integer values. Compaq C Socket Routine Reference A-69 inet_ntoa _________________________________________________________________ inet_ntoa Converts an Internet address into a text string representing the address in the standard Internet "." notation. Format #include #include char *inet_ntoa (struct in_addr in); Argument in An Internet address in network byte order. Description This routine converts an Internet address into an ASCIZ (null-terminated) string representing that address in the standard Internet "." notation. _______________________ Warning _______________________ Arguments should not be passed as integers because of how Compaq C handles struct arguments. ______________________________________________________ Because the string is returned in a static buffer that will be overwritten by successive calls to inet_ntoa, it is recommended to copy the string to a safe place. Return Value x A pointer to a string containing the Internet address in "." notation. A-70 Compaq C Socket Routine Reference ioctl _________________________________________________________________ ioctl Controls socket operations only. Format #include int ioctl (int d, unsigned long request, void *arg); Arguments d Specifies the file descriptor of the requested device. request Specifies the ioctl command performed on the device. arg Specifies parameters for this request. The type of arg is dependent on the specific ioctl request and device to which the ioctl is targeted. Description The ioctl routine performs a variety of operations on sockets. An ioctl request has encoded in it, whether the parameter is an "in" parameter or "out" parameter, and the size of the arg parameter in bytes. The ioctl request is defined in the header file. Return Values 0 Indicates success. -1 Indicates an error; further specified in the global errno. Compaq C Socket Routine Reference A-71 ioctl Errors If the ioctl routine fails, errno is set to one of the following values: o EBADF - The d parameter is not a valid descriptor. o ENOTTY - The d parameter is not associated with a character special device, or the specified request does not apply to the kind of object that the d parameter references. o EINVAL - Either the request or the arg parameter is not valid. A-72 Compaq C Socket Routine Reference listen _________________________________________________________________ listen Sets the maximum limit of outstanding connection requests for a socket that is connection-oriented. Format int listen (int s, int backlog); Arguments s A socket descriptor of type SOCK_STREAM that has been created using socket. backlog The maximum number of pending connections that may be queued on the socket at any given time. The maximum cannot exceed 5. Description This routine creates a queue for pending connection requests on socket s with a maximum size of backlog. Connections may then be accepted with accept. If a connection request arrives with the queue full (more than backlog connection requests pending), the client will receive a timeout. See also accept, connect, and socket in this section. Return Values 0 Indicates success. Compaq C Socket Routine Reference A-73 listen -1 Indicates an error; errno is set to one of the following values: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EOPNOTSUPP - The socket is not of a type that supports the operation listen. A-74 Compaq C Socket Routine Reference ntohl _________________________________________________________________ ntohl Converts longwords from network to host byte order. Format #include unsigned long int ntohl (unsigned long int netlong); Argument netlong A longword in network byte order. Integers in network byte order cannot be used for arithmetic computation on VAX systems. Description This routine converts 32-bit unsigned integers from network byte order to host byte order. The network byte order is the format in which data bytes are supposed to be transmitted through a network. All hosts on a network must send data in network byte order. Not all hosts have an internal data representation format that is identical to the network byte order. The host byte order is the format in which bytes are ordered internally on a specific host. The host byte order on VAX systems differs from the network order. This routine is most often used with Internet addresses and ports as returned by gethostent and getservent, and when manipulating values in the structures. Network byte order places the byte with the most significant bits at lower addresses; VAX systems place the most significant bits at the highest address. Compaq C Socket Routine Reference A-75 ntohl Return Value x A longword in host byte order. A-76 Compaq C Socket Routine Reference ntohs _________________________________________________________________ ntohs Converts short integers from network to host byte order. Format #include unsigned short int ntohs (unsigned short int netshort); Argument netshort A short integer in network byte order. Integers in network byte order cannot be used for arithmetic computation on VAX systems. Description This routine converts 16-bit unsigned integers from network byte order to host byte order. The network byte order is the format in which data bytes are supposed to be transmitted through a network. All hosts on a network must send data in network byte order. Not all hosts have an internal data representation format that is identical to the network byte order. The host byte order is the format in which bytes are ordered internally on a specific host. The host byte order on VAX systems differs from the network order. This routine is most often used with Internet addresses and ports as returned by gethostent and getservent, and when manipulating values in the structures. Network byte order places the byte with the most significant bits at lower addresses; VAX systems place the most significant bits at the highest address. Compaq C Socket Routine Reference A-77 ntohs Return Value x A short integer in host (VAX) byte order. A-78 Compaq C Socket Routine Reference read _________________________________________________________________ read Reads bytes from a socket or file and places them in a buffer. Format #include int read (int d, void *buffer, int nbytes); Arguments d A descriptor that must refer to a socket or file currently opened for reading. buffer The address of contiguous storage in which the input data is placed. nbytes The maximum number of bytes involved in the read operation. Description If the end-of-file is not reached, the read routine returns nbytes. If the end-of-file occurs during the read routine, it returns the number of bytes read. Upon successful completion, read returns the number of bytes actually read and placed in the buffer. See also socket in this section. Return Values x The number of bytes read and placed in the file. Compaq C Socket Routine Reference A-79 read -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o EFAULT - The buffer points outside the allocated address space. o EINVAL - The nbytes argument is negative. o EWOULDBLOCK - The NBIO socket option (nonblocking) flag is set for the socket or file descriptor and the process would be delayed in the read operation. A-80 Compaq C Socket Routine Reference recv _________________________________________________________________ recv Receives bytes from a connected socket and places them into a buffer. Format #include int recv (int s, char *buf, int len, int flags); (_DECC_V4_SOURCE) ssize_t recv (int s, void *buf, size_t len, int flags); (not _DECC_V4_SOURCE) Arguments s A socket descriptor that was created as the result of a call to accept or connect. buf A pointer to a buffer into which received data will be placed. len The size of the buffer pointed to by buf. flags A bit mask that may contain one or more of MSG_OOB and MSG_ PEEK. It is built by ORing the appropriate values together. The MSG_OOB flag allows out-of-band data to be received. If out-of-band data is available, it will be read before any other data that is available. If no out-of-band data is available, the MSG_OOB flag is ignored. Out-of-band data can be sent using send, sendmsg, and sendto. The MSG_PEEK flag allows you to peek at the data that is next in line to be received without removing it from the system's buffers. Compaq C Socket Routine Reference A-81 recv Description This routine receives data from a connected socket. To receive data on an unconnected socket, use the recvfrom or recvmsg routines. The received data is placed in the buffer buf. Data is sent by the socket's peer using the send, sendmsg, or sendto routines. You may use the select routine to determine when more data arrives. If no data is available at the socket, the receive call waits for data to arrive, unless the socket is nonblocking in which case a -1 is returned with the external variable errno set to EWOULDBLOCK. See also read, send, sendmsg, sendto, and socket in this section. Return Values x The number of bytes received and placed in buf. 0 Indicates that a connection is broken or reset by its peer. A-82 Compaq C Socket Routine Reference recv -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The descriptor references a file, not a socket. o EPIPE - An attempt was made to write to a socket that is not open for reading by any process. o EWOULDBLOCK - The NBIO socket option (nonblocking) flag is set for the socket or file descriptor and the process would be delayed in the read operation. o EFAULT - The data was specified to be received into a non-existent or protected part of the process address space. Compaq C Socket Routine Reference A-83 recvfrom _________________________________________________________________ recvfrom Receives bytes from a socket from any source. Format #include int recvfrom (int s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen) ; (_DECC_V4_SOURCE) ssize_t recvfrom (int s, void *buf, size_t len, int flags, struct sockaddr *from, size_t *fromlen) ; (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_recvfrom. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket and bound to a name using bind or as a result of accept. buf A pointer to a buffer into which received data will be placed. len The size of the buffer pointed to by buf. flags A bit mask that may contain one or more of MSG_OOB and MSG_ PEEK. It is built by ORing the appropriate values together. The MSG_OOB flag allows out-of-band data to be received. If out-of-band data is available, it will be read before any other data that is available. If no out-of-band data A-84 Compaq C Socket Routine Reference recvfrom is available, the MSG_OOB flag is ignored. Out-of-band data can be sent using send, sendmsg, and sendto. The MSG_PEEK flag allows you to peek at the data that is next in line to be received without actually removing it from the system's buffers. from If from is nonzero, from is a buffer into which recvfrom places the address (structure) of the socket from which the data is received. If from was 0, the address will not be returned. fromlen Points to an integer containing the size of the buffer pointed to by from. On return, the integer is modified to contain the actual length of the socket address structure returned. Description This routine allows a named, unconnected socket to receive data. The data is placed in the buffer pointed to by buf, and the address of the sender of the data is placed in the buffer pointed to by from if from is non-NULL. The structure that from points to is assumed to be as large as the sockaddr structure. See for a description of the sockaddr structure. To receive bytes from any source, the sockets need not be connected to another socket. You may use the select routine to determine if data is available. If no data is available at the socket, the recv call waits for data to arrive, unless the socket is nonblocking, in which case a -1 is returned with the external variable errno set to EWOULDBLOCK. See also read, send, sendmsg, sendto, and socket in this section. Compaq C Socket Routine Reference A-85 recvfrom Return Values x The number of bytes of data received and placed in buf. -1 Indicates an error; errno is set to one of the following values: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EPIPE - An attempt was made to write to a socket that is not open for reading by any process. o EWOULDBLOCK - The NBIO (nonblocking) flag is set for the socket descriptor and the process would be delayed in the write operation. o EFAULT - The data was specified to be received into a non-existent or protected part of the process address space. A-86 Compaq C Socket Routine Reference recvmsg _________________________________________________________________ recvmsg Receives bytes on a socket and places them into scattered buffers.. Format #include int recvmsg (int s, struct msghdr msg[], int flags); Routine Variants This socket routine has a variant named __bsd44_recvmsg. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket. msg A msghdr structure. See for a description of the msghdr structure. flags A bit mask that may contain one or more of MSG_OOB and MSG_ PEEK. It is built by ORing the appropriate values together. The MSG_OOB flag allows out-of-band data to be received. If out-of-band data is availiable, it will be read before any normal data that is available. If no out-of-band data is available, the MSG_OOB flag is ignored. Out-of-band data can be sent using send, sendmsg, and sendto. The MSG_PEEK flag allows you to peek at the data that is next in line to be received without actually removing it from the system's buffers. Compaq C Socket Routine Reference A-87 recvmsg Description This routine may be used with any socket, whether it is in a connected state or not. It receives data sent by a call to sendmsg, send, or sendto. The message is scattered into several user buffers if such buffers are specified. To receive data, the socket need not be connected to another socket. When the iovec[iovcnt] array specifies more than one buffer, the input data is scattered into iovcnt buffers as specified by the members of the iovec array: iov[0], iov[1], ..., iov[iovcnt] When a message is received, it is split among the buffers by filling the first buffer in the list, then the second, and so on, until either all of the buffers are full or there is no more data to be placed in the buffers. When a message is sent, the first buffer is copied to a system buffer and then the second buffer is copied, followed by the third buffer and so on, until all the buffers are copied. After the data is copied, the protocol will send the data to the remote host at the appropriate time, depending upon the protocol. You may use the select routine to determine when more data arrives. See also read, send, and socket in this section. Return Values x The number of bytes returned in the msg_iov buffers. A-88 Compaq C Socket Routine Reference recvmsg -1 Indicates an error; errno is set to one of the following values: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o EPIPE - An attempt was made to write to a socket that is not open for reading by any process. o EWOULDBLOCK - The NBIO (nonblocking) flag is set for the socket descriptor and the process would be delayed in the write operation. o EINTR - The receive was interrupted by delivery of a signal before any data was available for the receive. o EFAULT - The data was specified to be received into a non-existent or protected part of the process address space. Compaq C Socket Routine Reference A-89 select _________________________________________________________________ select Allows the user to poll or check a group of sockets for I/O activity. It can check what sockets are ready to be read or written, or what sockets have a pending exception. As of OpenVMS Version 7.0, this routine can operate on any number of sockets up to the limit of open files supported by the Compaq C RTL (65535 on OpenVMS Alpha; 2047 on OpenVMS VAX). However, for select to use more than 32 sockets, the TCP/IP Services for OpenVMS used with the Compaq C RTL must offer the same support. Format #include int select (int nfds, int *readfds, int *writefds, int *exceptfds, struct timeval *timeout); (_DECC_V4_SOURCE) int select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); (not _DECC_V4_SOURCE) Arguments nfds The highest numbered socket descriptor to search for. That is, the highest numbered bit + 1 in readfds, writefds, and exceptfds that should be examined. Descriptor s is represented by 1<< s (1 shifted to the left s number of times). ________________________ Note ________________________ You must increase the value of FD_SETSIZE if your application will use more sockets in the call to select than the value of FD_SETSIZE in the or header files. Do this by defining a larger value for FD_SETSIZE within the application before including or . ______________________________________________________ A-90 Compaq C Socket Routine Reference select readfds A pointer to an array of bits, organized as integers (each integer describing 32 descriptors), that should be examined for read readiness. If bit n of the longword is set, socket descriptor n will be checked to see if it is ready to be read. All bits set in the bit mask must correspond to the file descriptors of sockets. The select routine cannot be used on normal files. On return, the array of bits to which readfds points contains a bit mask of the sockets that are ready for reading. Only bits that are set on entry to select will be set on exit. If this pointer is NULL, select ignores the array. writefds A pointer to a longword bit mask of the socket descriptors that should be examined for write readiness. If bit n of the longword is set, socket descriptor n will be checked to see if it is ready to be written to. All bits set in the bit mask must correspond to socket descriptors. On return, the array of bits that writefds points to contains a bit mask of the sockets that are ready for writing. Only bits that are set on entry to select will be set on exit. If this pointer is NULL, select ignores the array. exceptfds A pointer to a longword bit mask of the socket descriptors that should be examined for exceptions. If bit n of the longword is set, socket descriptor n will be checked to see if it has any pending exceptions. All bits set in the bit mask must correspond to the file descriptors of sockets. On return, the array of bits pointer exceptfds contains a bit mask of the sockets that have exceptions pending. Only bits that are set on entry to select will be set on exit. If this pointer is NULL, select ignores the array. Compaq C Socket Routine Reference A-91 select timeout The length of time that select should examine the sockets before returning. If one of the sockets specified in the readfds, writefds, and exceptfds bit masks is ready for I/O, select will return before the timeout period has expired. The timeout structure points to a timeval structure. See for a description of the timeval structure. Description This routine determines the I/O status of the sockets specified in the various mask arguments. It returns either when a socket is ready to be read or written, or when the timeout period expires. If timeout is a nonzero integer, it specifies a maximum interval to wait for the selection to complete. If the timeout argument is NULL, select will block indefinitely. In order to effect a poll, timeout should be non-NULL, and should point to a zero-valued structure. If a process is blocked on a select while waiting for input from a socket and the sending process closes the socket, the select notes this as an event and will unblock the process. The descriptors are always modified on return if select returns because of the timeout. When the socket option SO_OOBINLINE is set on the device_ socket, a select on both read and exception events returns the socket mask set on both the read and exception mask. Otherwise, only the exception mask is set. ________________________ Note ________________________ Beginning with OpenVMS Version 7.2-1, the select function fails if one of the specified file descriptor sets contains an invalid file descriptor (errno is set to EBADF) or a file descriptor not associated with a socket (errno is set to ENOTSOCK). Previously, select set errno as described, but was otherwise ignoring invalid file descriptors and file descriptors not associated with sockets. To request this old behavior, define the logical name A-92 Compaq C Socket Routine Reference select DECC$SELECT_IGNORES_INVALID_FD to any value before invoking the application. ______________________________________________________ See also accept, connect, read, recv, recvfrom, recvmsg, send, sendmsg, sendto, and write in this section. Return Values n The number of sockets that were ready for I/O or that had pending exceptions. This value matches the number of returned bits that are set in all output masks. 0 Indicates that select timed out before any socket became ready for I/O. -1 Indicates an error; errno is set to one of the following values: o EBADF - One of the bit masks specified an invalid descriptor. o EINVAL - The specified time limit is unacceptable. One of its components is negative or too large. o ENOTSOCK - A file descriptor not associated with a socket was found in one of the specified file descriptor sets. Compaq C Socket Routine Reference A-93 send _________________________________________________________________ send Sends bytes though a socket to its connected peer. Format #include int send (int s, char *msg, int len, int flags); (_DECC_V4_SOURCE) ssize_t send (int s, const void *msg, size_t len, int flags); (not _DECC_V4_SOURCE) Arguments s A socket descriptor that was created with socket, and connected to another socket using accept or connect. msg A pointer to a buffer containing the data to be sent. len The length, in bytes, of the data pointed to by msg. flags May be either 0 or MSG_OOB. If it is equal to MSG_OOB, the data will be sent out-of-band. This means that the data can be received before other pending data on the receiving socket if the receiver also specifies a MSG_OOB in the flag parameter of the call. Description This routine may only be used on connected sockets. To send data on an unconnected socket, use the sendmsg or sendto routines. The send routine passes data along to its connected peer, which may receive the data by using recv. If there is no space available to buffer the data being sent on the receiving end of the connection, send will normally block until buffer space becomes available. If the socket is defined as nonblocking, however, send will fail with an errno indication of EWOULDBLOCK. If the A-94 Compaq C Socket Routine Reference send message is too large to be sent in one piece and the socket type requires that messages be sent atomically (using SOCK_DGRAM), send will fail with an errno indication of EMSGSIZE. No indication of failure to deliver is implicit in a send. All errors (except EWOULDBLOCK) are detected locally. You may use the select routine to determine when it is possible to send more data. See also read, recv, recvmsg, recvfrom, getsocketopt, and socket in this appendix. Return Values n The number of bytes sent. This value will normally equal len. -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The descriptor references a file, not a socket. o EFAULT - An invalid user space address was specified for a parameter. o EMSGSIZE -The socket requires that messages be sent atomically, and the size of the message to be sent made this impossible. o EWOULDBLOCK - Blocks if the system does not have enough space for buffering the user data. Compaq C Socket Routine Reference A-95 sendmsg _________________________________________________________________ sendmsg Sends gathered bytes through a socket to any other socket. Format #include int sendmsg (int s, struct msghdr msg[], int flags); Routine Variants This socket routine has a variant named __bsd44_sendmsg. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket. msg A pointer to a msghdr structure containing the message to be sent. See for a description of the msghdr structure. The msg_iov field of the msghdr structure is used as a series of buffers from which data is read in order until msg_iovlen bytes have been obtained. flags May be either 0 or MSG_OOB. If it is equal to MSG_OOB, the data will be sent out-of-band. This means that the data can be received before other pending data on the receiving socket if the receiver also specifies a flag of MSG_OOB. A-96 Compaq C Socket Routine Reference sendmsg Description This routine may be used on any socket to send data to any named socket. The data in the msg_iovec field of the msg structure is sent to the socket whose address is specified in the msg_name field of the structure. The receiving socket gets the data using either the read, recv, recvfrom, or recvmsg routine. When the iovec array specifies more than one buffer, the data is gathered from all specified buffers before being sent. See for a description of the iovec structure. If there is no space available to buffer the data being sent on the receiving end of the connection, sendmsg will normally block until buffer space becomes available. If the socket is defined as nonblocking, however, sendmsg will fail with an errno indication of EWOULDBLOCK. If the message is too large to be sent in one piece and the socket type requires that messages be sent atomically (SOCK_DGRAM), sendmsg will fail with an errno indication of EMSGSIZE. If the address specified is a INADDR_BROADCAST address, then the SO_BROADCAST option must be set and the process must have SYSPRV or BYPASS privilege for the I/O operation to succeed. No indication of failure to deliver is implicit in a sendmsg. All errors (except EWOULDBLOCK) are detected locally. You may use the select routine to determine when it is possible to send more data. See also read, recv, recvfrom, recvmsg, and socket in this section, and getsockopt in this appendix. Return Values n The number of bytes sent. Compaq C Socket Routine Reference A-97 sendmsg -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The descriptor references a file, not a socket. o EFAULT - An invalid user space address was specified for a parameter. o EMSGSIZE -The socket requires that messages be sent atomically, and the size of the message to be sent made this impossible. o EWOULDBLOCK - Blocks if the system does not have enough space for buffering the user data. A-98 Compaq C Socket Routine Reference sendto _________________________________________________________________ sendto Sends bytes through a socket to any other socket. Format #include int sendto (int s, char *msg, int len, int flags, struct sockaddr *to, int tolen); (_DECC_V4_SOURCE) ssize_t sendto (int s, const void *msg, size_t len, int flags, const struct sockaddr *to, size_t tolen); (not _DECC_V4_SOURCE) Routine Variants This socket routine has a variant named __bsd44_sendto. Enabled by defining _SOCKADDR_LEN, this variant implements 4.4BSD-compatible semantics. See Section A.7 for more information. Arguments s A socket descriptor that has been created with socket. msg A pointer to a buffer containing the data to be sent. len The length of the data pointed to by msg. flags May be either 0 or MSG_OOB. If it is equal to MSG_OOB, the data will be sent out-of-band. This means that the data can be received before other pending data on the receiving socket if the receiver also specifies a MSG_OOB in its flag parameter of the call. to Points to the address structure of the socket to which the data is to be sent. Compaq C Socket Routine Reference A-99 sendto tolen The length of the address structure to points to. Description This routine may be used on any socket to send data to any named socket. The data in the msg buffer is sent to the socket whose address is specified in to, and the address of socket s is provided to the receiving socket. The receiving socket gets the data using either the read, recv, recvfrom, or recvmsg routine. If there is no space available to buffer the data being sent on the receiving end of the connection, sendto will normally block until buffer space becomes available. If the socket is defined as nonblocking, however, sendto will fail with an errno indication of EWOULDBLOCK. If the message is too large to be sent in one piece and the socket type requires that messages be sent atomically (using SOCK_ DGRAM), sendto will fail with an errno indication of EMSGSIZE. No indication of failure to deliver is implicit in a sendto. All errors (except EWOULDBLOCK) are detected locally. You may use the select routine to determine when it is possible to send more data. If the address specified is a INADDR_BROADCAST address, then the SO_BROADCAST option must be set and the process must have SYSPRV or BYPASS privilege for the I/O operation to succeed. See also read, recv, recvfrom, recvmsg, and socket in this section, and getsockopt in this appendix. Return Values n The number of bytes sent. This value will normally equal len. A-100 Compaq C Socket Routine Reference sendto -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The descriptor references a file, not a socket. o EFAULT - An invalid user space address was specified for a parameter. o EMSGSIZE -The socket requires that messages be sent atomically, and the size of the message to be sent made this impossible. o EWOULDBLOCK - Blocks if the system does not have enough space for buffering the user data. Compaq C Socket Routine Reference A-101 sethostent _________________________________________________________________ sethostent Opens and rewinds the network host database file. Format #include void sethostent (int stay_open); Arguments stay_open Specifies a value used to indicate when to close the host database file: o 0 (zero) to close the host database file after each call to the gethostbyname or gethostbyaddr routine. o nonzero to keep the host database file open after each call. Description The sethostent routine opens or rewinds the network host database file and resets the file marker to the beginning of the file. Passing a nonzero value to the stay_open parameter keeps the connection open until the endhostent or exit routine is called. See also endhostent in this section. A-102 Compaq C Socket Routine Reference setnetent _________________________________________________________________ setnetent Opens and rewinds the networks database file. Format #include void setnetent (int stay_open); Arguments stay_open Specifies a value used to indicate when to close the networks database file: o 0 (zero) to close the networks database file after each call to the getnetent. o nonzero to keep the networks database file open after each call. Description The setnetent routine opens the networks database file and resets the file marker to the beginning of the file. Passing a nonzero value to the stay_open parameter keeps the connection open until you call the endnetent or exit routine. See also endnetent, getnetent, and exit in this section. Compaq C Socket Routine Reference A-103 setprotoent _________________________________________________________________ setprotoent Opens, rewinds, or closes the protocols database file. Format #include void setprotoent (int stay_open); Arguments stay_open Specifies a value used to indicate when to close the protocols database file: o 0 (zero) to close the host database file after each call to the getprotoent routine. o nonzero to keep the host database file open after each call. Description The setprotoent routine opens, or rewinds the protocols database file and sets the file marker to the beginning of the file. Passing a nonzero value to the stay_open parameter keeps the connection open until you call the endprotoent, or exit routine. See also endprotoent, exit, and getprotoent in this section. Return Values 1 Indicates success. 0 Indicates an error; unable to open the protocols database file. A-104 Compaq C Socket Routine Reference setprotoent Errors If the setprotoent routine fails, the error is further specified in the global errno. Compaq C Socket Routine Reference A-105 setservent _________________________________________________________________ setservent Opens and rewinds the network services database file. Format #include void setservent (int stay_open); Arguments stay_open Specifies a value used to indicate when to close the network services database file: o 0 (zero) to close the network services database file after each call to the getservent routine. o nonzero to keep the network services database file open after each call to getservent. Description The setservent routine opens the network services database file and resets the file marker to the beginning of the file. Passing a nonzero value to the stay_open parameter keeps the connection open until you call the endservent, or exit routine. See also endservent, exit, and getservent in this section. A-106 Compaq C Socket Routine Reference setsockopt _________________________________________________________________ setsockopt Sets options on a socket. Format #include int setsockopt (int s, int level, int optname, char *optval, int optlen); (_DECC_V4_SOURCE) int setsockopt (int s, int level, int optname, const void *optval, size_t optlen); (not _DECC_V4_SOURCE) Arguments s A socket descriptor created by socket. level The protocol level for which the socket options are to be modified. It may have one of the following values: SOL_SOCKET Set the options at the socket level. p Any protocol number. Set the options for protocol level p. See the header file for the various IPPROTO values. optname Is interpreted by the protocol specified in level. Options at each protocol level are documented with the protocol. The following options are available at the socket level: SO_REUSEADDR indicates the rules used in validating addresses supplied in a bind call should allow reuse of local addresses. SO_KEEPALIVE keeps connections alive by enabling the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified through an EPIPE error. Compaq C Socket Routine Reference A-107 setsockopt SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address. SO_LINGER delays the internal socket deletion portion of close until either the data has been transmitted, or the device times out (approximately eight minutes). SO_BROADCAST is used to enable or disable broadcasting on the socket. optval Points to a buffer containing the parameters of the specified option. All socket level options other than SO_LINGER take an integer parameter that should be nonzero if the option is to be enabled, or zero if it is to be disabled. SO_LINGER uses a linger structure parameter defined in the file. This structure specifies the desired state of the option and the linger interval. The option value for the SO_LINGER command is the address of a linger structure. See the header file for a description of the linger structure. If the socket promises reliable delivery of data and l_ onoff is nonzero, the system will block the process on the close attempt until it is able to transmit the data or until it decides it is unable to deliver the information. A timeout period, called the linger interval, is specified in l_linger. If l_onoff is set to 0 and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible. optlen An integer containing the size of the buffer pointed to by optval. A-108 Compaq C Socket Routine Reference setsockopt Description This routine manipulates options associated with a socket. Options may exist at multiple protocol levels; they are always present at the uppermost socket level. When manipulating socket options, the level at which the option resides and the name of the option must be specified. To manipulate options at the socket level, specify level as SOL_SOCKET. To manipulate options at any other level, the protocol number of the appropriate protocol controlling the option must be supplied. For example, to indicate an option is to be interpreted by the TCP protocol, level should be set to the protocol number (IPPROTO_TCP) of TCP. See for the various IPPROTO values. Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EBADF - The descriptor is invalid. o ENOTSOCK - The socket descriptor references a file, not a socket. o ENOTCONN - The socket is not connected. o ENOPROTOOPT - The option is unknown. o EFAULT - The optname parameter is not a valid part of the user address space. Compaq C Socket Routine Reference A-109 shutdown _________________________________________________________________ shutdown Shuts down all or part of a bidirectional connection on a socket. It can disallow further receives, further sends, or both. Format #include int shutdown (int s, int how); Arguments s A socket descriptor that is in a connected state as a result of a previous call to either connect or accept. how How the socket is to be shut down. Use one of the following values: 0 Disallows further calls to recv on the socket. 1 Disallows further calls to send on the socket. 2 Disallows further calls to both send and recv. Description This routine allows communications on a socket to be shut down one piece at a time rather than all at once. It can be used to create unidirectional connections rather than the normal bidirectional (full-duplex) connections. See also connect and socket in this section. A-110 Compaq C Socket Routine Reference shutdown Return Values 0 Indicates success. -1 Indicates an error; errno is set to one of the following: o EBADF - The socket descriptor is invalid. o ENOTSOCK - The descriptor references a file, not a socket. o ENOTCONN - The specified socket is not connected. Compaq C Socket Routine Reference A-111 socket _________________________________________________________________ socket Creates an endpoint for communication by returning a special kind of file descriptor called a socket descriptor, which is associated with a TCP/IP Services for OpenVMS Socket Device Channel. Format #include int socket (int af, int type, int protocol); Arguments af The address format to be used in later references to the socket. Addresses specified in subsequent operations using the socket are interpreted according to this format. Currently, only AF_INET (Internet style) addresses are supported. type The semantics of communication. The type may be SOCK_ STREAM, SOCK_DGRAM, or SOCK_RAW. SOCK_STREAM type sockets provide sequenced, reliable, two-way connection based byte streams with an available out-of-band data transmission mechanism. SOCK_DGRAM sockets support datagrams (connectionless, unreliable data transmission mechanism). SOCK_RAW sockets provide access to internal network interfaces, and are available only to users with SYSPRV privilege. protocol The protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type using a given address format. However, it is possible that many protocols may exist, in which case a particular protocol must be specified with this argument. The protocol number to use is particular to the communication domain in which communication is to take place. A-112 Compaq C Socket Routine Reference socket Description This routine provides the primary mechanism for creating sockets. The type and protocol of the socket affect the way the socket behaves and how it can be used. The operation of sockets is controlled by socket-level options, defined in the file . The setsockopt and getsockopt calls are used to set and get options. Options other than SO_LINGER take an integer parameter that should be nonzero if the option is to be enabled, or 0 if it is to be disabled. SO_LINGER uses a linger structure parameter defined in . The members of this structure specify the desired state of the option and the linger interval in the following manner: SO_REUSEADDR indicates that the rules used in validating addresses supplied in a bind call should allow reuse of local addresses. SO_KEEPALIVE keeps connections alive by enabling the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified through the error code SS$_ LINKDISCON. SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address. SO_LINGER lingers on close if data is present. It controls the actions taken when unsent messages are queued on the socket and a close is performed. When using the setsockopt to set the linger values, the option value for the SO_ LINGER command is the address of a linger structure: ++++++++++++ struct linger { int l_onoff; /* option on/off */ int l_linger; /* linger time */ }; Compaq C Socket Routine Reference A-113 socket If the socket promises reliable delivery of data and l_ onoff is nonzero, the system will block the process on the attempt until it is able to transmit the data or until it decides it is unable to deliver the information. A timeout period, called the linger interval, is specified in l_ linger. If l_onoff is set to 0 and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible. SO_BROADCAST is used to enable or disable broadcasting on the socket. See also accept, bind, connect, getsockname, getsockopt, listen, read, recv, recvfrom, recvmgs, select, send, sendmsg, sendto, shutdown, and write in this appendix. Return Values x A file descriptor that refers to the socket descriptor. -1 Indicates an error; errno is set to one of the following: o EAFNOSUPPORT - The specified address family is not supported in this version of the system. o ESOCKTNOSUPPORT - The specified socket type is not supported in this address family. o EPROTONOSUPPORT - The specified protocol is not supported. o EPROTOTYPE - Request for a type of socket for which there is no supporting protocol. o EMFILE - The per-process descriptor table is full. o ENOBUFS - No buffer space is available. The socket cannot be created. A-114 Compaq C Socket Routine Reference decc$socket_fd _________________________________________________________________ decc$socket_fd Returns the socket descriptor associated with a Socket Device Channel for direct use with the Compaq C RTL. Format #include int decc$socket_fd (int channel); Arguments channel A valid Socket Device Channel. Description The decc$socket_fd routine associates a valid socket channel with a Compaq C RTL file descriptor, and returns the file descriptor. The file descriptor can then be used with one of the Compaq C routines that take a file descriptor or socket descriptor as an input parameter. Return Values x The socket descriptor. -1 Indicates an error; the socket descriptor cannot be allocated. Compaq C Socket Routine Reference A-115 vaxc$get_sdc _________________________________________________________________ vaxc$get_sdc Returns the Socket Device Channel (SDC) associated with a socket descriptor for direct use with the TCP/IP Services for OpenVMS product. Format #include short int vaxc$get_sdc (int s); Argument s A socket descriptor. Description This routine returns the SDC associated with a socket. C socket descriptors are normally used either as file descriptors or with one of the routines that takes an explicit socket descriptor as its argument. C sockets are implemented using TCP/IP Services for OpenVMS Socket Device Channels. This routine returns the SDC used by a given socket descriptor so that you can use the TCP/IP Services for OpenVMS's facilities directly by means of various I/O system services ($QIO). Return Values 0 Indicates that s is not an open socket descriptor. x The SDC number. A-116 Compaq C Socket Routine Reference write _________________________________________________________________ write Writes a buffer of data to a socket or file. Format #include int write (int d, void *buffer, int nbytes); Arguments d A descriptor that must refer to a socket or file. buffer The address of contiguous storage from which the output data is taken. nbytes The maximum number of bytes involved in the write operation. Description This routine attempts to write a buffer of data to a socket or file. See also socket in this section. Return Values x The number of bytes written to the socket or file. 0 Indicates an error. Compaq C Socket Routine Reference A-117 write -1 Indicates an error; errno is set to one of the following: o EBADF - The d argument is not a valid descriptor open for writing. o EPIPE - An attempt was made to write to a socket that is not open for reading by any process. o EFAULT - Part of the array pointed to by iov or data to be written to the file points outside the process's allocated address space. o EWOULDBLOCK - The NBIO (nonblocking) flag is set for the socket descriptor and the process would be delayed in the write operation. o EINVAL - The nbytes argument is negative. A-118 Compaq C Socket Routine Reference A.9 Programming Examples This section provides Compaq C socket communications programming examples. Example A-1 is an example of a TCP/IP Server. Example A-1 TCP/IP Server /*==================================================================== * * Copyright (C) 1999 by * Digital Equipment Corporation, Maynard, Massachusetts * * This software is furnished under a license and may be used and copied * only in accordance with the terms of such license and with the * inclusion of the above copyright notice. This software or any other * copies thereof may not be provided or otherwise made available to any * other person. No title to and ownership of the software is hereby * transferred. * * The information in this software is subject to change without notice * and should not be construed as a commitment by Digital Equipment * Corporation. * * DIGITAL assumes no responsibility for the use or reliability of its * software on equipment that is not supplied by DIGITAL. * * * * FACILITY: * INSTALL * * * ABSTRACT: * This is an example of a TCP/IP server using the IPC * socket interface. * (continued on next page) Compaq C Socket Routine Reference A-119 Example A-1 (Cont.) TCP/IP Server * * ENVIRONMENT: * UCX V1.2 or higher, VMS V5.2 or higher * * This example is portable to ULTRIX. The include * files are conditionally defined for both systems, and * "perror" is used for error reporting. * BUILD INSTRUCTIONS: * * To link in VAXC/VMS you must have the following * entries in your .opt file: * sys$library:ucx$ipc.olb/lib * sys$share:vaxcrtl.exe/share * * For Compaq C or Compaq C++, compile /PREFIX=ALL and link via * $ link UCX$TCP_SERVER_IPC * * To build this example program, use commands of the following form: * * using the Compaq C compiler: * * $ cc/prefix=all UCX$TCP_SERVER_IPC.C * $ link UCX$TCP_SERVER_IPC * * using the Compaq C++ compiler: * * $ cxx/prefix=all/define=VMS UCX$TCP_SERVER_IPC.C * $ link UCX$TCP_SERVER_IPC * * using the VAX C compiler: * * $ cc /vaxc UCX$TCP_SERVER_IPC.C * $ link UCX$TCP_SERVER_IPC, - * SYS$LIBRARY:UCX$IPC/LIB, - * SYS$INPUT/OPTIONS * SYS$SHARE:UCX$IPC_SHR/SHARE * SYS$SHARE:VAXCRTL.EXE/SHARE (continued on next page) A-120 Compaq C Socket Routine Reference Example A-1 (Cont.) TCP/IP Server * * AUTHORS: * UCX Developer * * CREATION DATE: May 23, 1989 * * MODIFICATION HISTORY: * * 16 May 1996 Joseph J. Vlcek * Make compatible with the Compaq C and Compaq C++ compilers. * Add directions on how to build this example modules. * */ /* * * INCLUDE FILES * */ #ifdef VMS #include /* VMS descriptor stuff */ #include /* internet system Constants and structures. */ #include /* Network address info. */ #include /* I/O FUNCTION CODE DEFS */ #include /* LIB$ RTL-routine signatures. */ #include /* Network database library info. */ #include /* UNIX style Signal Value Definitions */ #include /* TCP/IP socket definitions. */ #include /* SS$_ sys ser return statistics */ #include /* Sys ser calls */ #include /* UNIX 'Standard I/O' Definitions */ #include /* General Utilities */ #include /* String handling function definitions */ #include /* UCX network definitions */ #include /* Prototypes for UNIX emulation functions */ (continued on next page) Compaq C Socket Routine Reference A-121 Example A-1 (Cont.) TCP/IP Server #else #include #include #include #include #include #include #include #include #endif /* * Functional Description * * This example creates a socket of type SOCK_STREAM (TCP), * binds and listens on the socket, receives a message, * and closes the connection. * Error messages are printed to the screen. * * IPC calls used: * accept * bind * close * gethostbyname * listen * recv * shutdown * socket * * * Formal Parameters * The server program expects one parameter: * portnumber ... port number where it will listen * * * Routine Value * * Status */ (continued on next page) A-122 Compaq C Socket Routine Reference Example A-1 (Cont.) TCP/IP Server /*--------------------------------------------------------------------*/ cleanup( int how_many, int sock1, int sock2 ) { int retval; /* * Shutdown and close sock1 completely. */ retval = shutdown(sock1,2); if (retval == -1) perror ("shutdown"); retval = close (sock1); if (retval) perror ("close"); /* * If given, shutdown and close sock2. */ if (how_many == 2) { retval = shutdown(sock2,2); if (retval == -1) perror ("shutdown"); retval = close (sock2); if (retval) perror ("close"); } exit( 1 ); } /* end cleanup*/ (continued on next page) Compaq C Socket Routine Reference A-123 Example A-1 (Cont.) TCP/IP Server /*--------------------------------------------------------------------*/ main( int argc, char **argv ) { int sock_2, sock_3; /* sockets */ static char message[BUFSIZ]; static struct sockaddr_in sock2_name; /* Address struct for socket2.*/ static struct sockaddr_in retsock2_name; /* Address struct for socket2.*/ struct hostent hostentstruct; /* Storage for hostent data. */ struct hostent *hostentptr; /* Pointer to hostent data. */ static char hostname[256]; /* Name of local host. */ int flag; int retval; /* helpful for debugging */ int namelength; /* * Check input parameters. */ if (argc != 2 ) { printf("Usage: server portnumber.\n"); exit( 1 ); } /* * Open socket 2: AF_INET, SOCK_STREAM. */ if ((sock_2 = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror( "socket"); exit( 1 ); } (continued on next page) A-124 Compaq C Socket Routine Reference Example A-1 (Cont.) TCP/IP Server /* * Get the host local name. */ retval = gethostname(hostname,sizeof hostname); if (retval) { perror ("gethostname"); cleanup (1, sock_2, 0); } /* * Get pointer to network data structure for socket 2. */ if ((hostentptr = gethostbyname (hostname)) == NULL) { perror( "gethostbyname"); cleanup(1, sock_2, 0); } /* * Copy hostent data to safe storage. */ hostentstruct = *hostentptr; /* * Fill in the name & address structure for socket 2. */ sock2_name.sin_family = hostentstruct.h_addrtype; sock2_name.sin_port = htons(atoi(argv[1])); sock2_name.sin_addr = * ((struct in_addr *) hostentstruct.h_addr); /* * Bind name to socket 2. */ retval = bind ( sock_2, (struct sockaddr*)&sock2_name, sizeof sock2_name ); (continued on next page) Compaq C Socket Routine Reference A-125 Example A-1 (Cont.) TCP/IP Server if (retval) { perror("bind"); cleanup(1, sock_2, 0); } /* * Listen on socket 2 for connections. */ retval = listen (sock_2, 5); if (retval) { perror("listen"); cleanup(1, sock_2, 0); } /* * Accept connection from socket 2: * accepted connection will be on socket 3. */ namelength = sizeof (sock2_name); sock_3 = accept (sock_2, (struct sockaddr*)&sock2_name, &namelength); if (sock_3 == -1) { perror ("accept"); cleanup( 2, sock_2, sock_3); } /* * Receive message from socket 1. */ flag = 0; /* maybe 0 or MSG_OOB or MSG_PEEK */ retval = recv(sock_3, message, sizeof (message), flag); if (retval == -1) { perror ("receive"); cleanup( 2, sock_2, sock_3); } (continued on next page) A-126 Compaq C Socket Routine Reference Example A-1 (Cont.) TCP/IP Server else printf (" %s\n", message); /* * Call cleanup to shutdown and close sockets. */ cleanup(2, sock_2, sock_3); } /* end main */ Compaq C Socket Routine Reference A-127 Example A-2 is an example of a TCP/IP Client. Example A-2 TCP/IP Client /*==================================================================== * * Copyright (C) 1999 by * Digital Equipment Corporation, Maynard, Massachusetts * * This software is furnished under a license and may be used and copied * only in accordance with the terms of such license and with the * inclusion of the above copyright notice. This software or any other * copies thereof may not be provided or otherwise made available to any * other person. No title to and ownership of the software is hereby * transferred. * * The information in this software is subject to change without notice * and should not be construed as a commitment by Digital Equipment * Corporation. * * DIGITAL assumes no responsibility for the use or reliability of its * software on equipment that is not supplied by DIGITAL. * * * * FACILITY: * INSTALL * * * ABSTRACT: * This is an example of a TCP/IP client using the IPC * socket interface. * * * ENVIRONMENT: * UCX V1.2 or higher, VMS V5.2 or higher * * This example is portable to ULTRIX. The include * files are conditionally defined for both systems, and * "perror" is used for error reporting. (continued on next page) A-128 Compaq C Socket Routine Reference Example A-2 (Cont.) TCP/IP Client * BUILD INSTRUCTIONS: * * To link in VAXC/VMS you must have the following * entries in your .opt file: * sys$library:ucx$ipc.olb/lib * sys$share:vaxcrtl.exe/share * * For Compaq C or Compaq C++, compile /PREFIX=ALL and link via * $ link UCX$TCP_CLIENT_IPC * * To build this example program, use commands of the following form: * * using the Compaq C compiler: * * $ cc/prefix=all UCX$TCP_CLIENT_IPC.C * $ link UCX$TCP_CLIENT_IPC * * using the Compaq C++ compiler: * * $ cxx/prefix=all/define=VMS UCX$TCP_CLIENT_IPC.C * $ link UCX$TCP_CLIENT_IPC * * using the VAX C compiler: * * $ cc /vaxc UCX$TCP_CLIENT_IPC.C * $ link UCX$TCP_CLIENT_IPC, - * SYS$LIBRARY:UCX$IPC/LIB, - * SYS$INPUT/OPTIONS * SYS$SHARE:UCX$IPC_SHR/SHARE (continued on next page) Compaq C Socket Routine Reference A-129 Example A-2 (Cont.) TCP/IP Client * * AUTHORS: * UCX Developer * * CREATION DATE: May 23, 1989 * * MODIFICATION HISTORY: * * 16 May 1996 Joseph J. Vlcek * Make compatible with the Compaq C and Compaq C++ compilers. * Add directions on how to build this example modules. * */ /* * * INCLUDE FILES * */ #if defined(VMS) || defined(__VMS) #include #include #include #include #include #include #include #include /* change hostent to comply with BSD 4.3*/ #include #include /* INET symbol definitions */ (continued on next page) A-130 Compaq C Socket Routine Reference Example A-2 (Cont.) TCP/IP Client #else #include #include #include #include #include #include #include #include #endif /* * * MACRO DEFINITIONS * */ #ifndef vms #define TRUE 1 #define FALSE 0 #endif void cleanup(int shut, int socket); /* * Functional Description * * This example creates a socket of type SOCK_STREAM (TCP), * initiates a connection to the remote host, sends * a message to the remote host, and closes the connection. * Error messages are printed to the screen. * * IPC calls used: * close * connect * gethostbyname * send * shutdown * socket * * (continued on next page) Compaq C Socket Routine Reference A-131 Example A-2 (Cont.) TCP/IP Client * Formal Parameters * The client program expects two parameters: * hostname ... name of remote host * portnumber ... port where remote host(server) is listening * * * Routine Value * * Status */ /*--------------------------------------------------------------------*/ main(int argc, char **argv) { int sock_1; /* socket */ static char message[] = "Hi there."; static struct sockaddr_in sock2_name; /* Address struct for socket2.*/ struct hostent hostentstruct; /* Storage for hostent data. */ struct hostent *hostentptr; /* Pointer to hostent data. */ static char hostname[256]; /* Name of local host. */ int flag; int retval; /* Helpful for debugging. */ int shut = FALSE; /* Flag to cleanup. */ /* * Check input parameters. */ if (argc != 3 ) { printf("Usage: client hostname portnumber.\n"); exit(EXIT_FAILURE); } (continued on next page) A-132 Compaq C Socket Routine Reference Example A-2 (Cont.) TCP/IP Client /* * Open socket 1: AF_INET, SOCK_STREAM. */ if ((sock_1 = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror( "socket"); exit(EXIT_FAILURE); } /* *Get pointer to network data structure for socket 2 (remote host). */ if ((hostentptr = gethostbyname (argv[1])) == NULL) { perror( "gethostbyname"); cleanup(shut, sock_1); } /* * Copy hostent data to safe storage. */ hostentstruct = *hostentptr; /* * Fill in the name & address structure for socket 2. */ sock2_name.sin_family = hostentstruct.h_addrtype; sock2_name.sin_port = htons(atoi(argv[2])); sock2_name.sin_addr = * ((struct in_addr *) hostentstruct.h_addr); (continued on next page) Compaq C Socket Routine Reference A-133 Example A-2 (Cont.) TCP/IP Client /* * Connect socket 1 to sock2_name. */ retval = connect(sock_1, (struct sockaddr *)&sock2_name, sizeof (sock2_name)); if (retval) { perror("connect"); cleanup(shut, sock_1); } /* * Send message to socket 2. */ flag = 0; /* maybe 0 or MSG_OOB */ retval = send(sock_1, message ,sizeof (message), flag); if (retval < 0) { perror ("send"); shut = TRUE; } /* * Call cleanup to shutdown and close socket. */ cleanup(shut, sock_1); } /* end main */ /*-----------------------------------------------------------*/ void cleanup(int shut, int socket) { int retval; (continued on next page) A-134 Compaq C Socket Routine Reference Example A-2 (Cont.) TCP/IP Client /* * Shutdown socket completely -- only if it was connected. */ if (shut) { retval = shutdown(socket,2); if (retval == -1) perror ("shutdown"); } /* * Close socket. */ retval = close (socket); if (retval) perror ("close"); exit(EXIT_SUCCESS); } /* end main */ Compaq C Socket Routine Reference A-135 Example A-3 is an example of a UDP/IP Server. Example A-3 UDP/IP Server /*==================================================================== * * Copyright (C) 1999 by * Digital Equipment Corporation, Maynard, Massachusetts * * This software is furnished under a license and may be used and copied * only in accordance with the terms of such license and with the * inclusion of the above copyright notice. This software or any other * copies thereof may not be provided or otherwise made available to any * other person. No title to and ownership of the software is hereby * transferred. * * The information in this software is subject to change without notice * and should not be construed as a commitment by Digital Equipment * Corporation. * * DIGITAL assumes no responsibility for the use or reliability of its * software on equipment that is not supplied by DIGITAL. * * * * FACILITY: * INSTALL * * * ABSTRACT: * This is an example of a UDP/IP server using the IPC * socket interface. * * * ENVIRONMENT: * UCX V1.2 or higher, VMS V5.2 or higher * * This example is portable to ULTRIX. The include * files are conditionally defined for both systems, and * "perror" is used for error reporting. (continued on next page) A-136 Compaq C Socket Routine Reference Example A-3 (Cont.) UDP/IP Server * BUILD INSTRUCTIONS: * * To link in VAXC/VMS you must have the following * entries in your .opt file: * sys$library:ucx$ipc.olb/lib * sys$share:vaxcrtl.exe/share * * For Compaq C or Compaq C++, compile /PREFIX=ALL and link via * $ link UCX$UDP_SERVER_IPC * * To build this example program, use commands of the following form: * * using the Compaq C compiler: * * $ cc/prefix=all UCX$UDP_SERVER_IPC.C * $ link UCX$UDP_SERVER_IPC * * using the Compaq C++ compiler: * * $ cxx/prefix=all/define=VMS UCX$UDP_SERVER_IPC.C * $ link UCX$UDP_SERVER_IPC * using the VAX C compiler: * * $ cc /vaxc UCX$UDP_SERVER_IPC.C * $ link UCX$UDP_SERVER_IPC, - * SYS$LIBRARY:UCX$IPC/LIB, - * SYS$INPUT/OPTIONS * SYS$SHARE:UCX$IPC_SHR/SHARE * SYS$SHARE:VAXCRTL.EXE/SHARE * (continued on next page) Compaq C Socket Routine Reference A-137 Example A-3 (Cont.) UDP/IP Server * * AUTHORS: * UCX Developer * * CREATION DATE: May 23, 1989 * * MODIFICATION HISTORY: * * 16 May 1996 Joseph J. Vlcek * Make compatible with the Compaq C and Compaq C++ compilers. * Add directions on how to build this example modules. * */ /* * * INCLUDE FILES * */ #ifdef VMS #include /* VMS descriptor stuff */ #include /* Unix style error codes for IO routines. */ #include /* internet system Constants and structures. */ #include /* Network address info. */ #include /* I/O FUNCTION CODE DEFS */ #include /* LIB$ RTL-routine signatures. */ #include /* Network database library info. */ #include /* UNIX style Signal Value Definitions */ #include /* TCP/IP socket definitions. */ #include /* SS$_ sys ser return statistics */ #include /* Sys ser calls */ #include /* UNIX 'Standard I/O' Definitions */ #include /* General Utilities */ #include /* String handling function definitions */ #include /* UCX network definitions */ #include /* Prototypes for UNIX emulation functions */ (continued on next page) A-138 Compaq C Socket Routine Reference Example A-3 (Cont.) UDP/IP Server #else #include #include #include #include #include #include #include #include #include /* timeval declared here */ #endif cleanup( int socket ) { int retval; /* * Shutdown socket completely. */ retval = shutdown(socket,2); if (retval == -1) perror ("shutdown"); /* * Close socket. */ retval = close (socket); if (retval) perror ("close"); exit( 1 ); } /* end cleanup */ (continued on next page) Compaq C Socket Routine Reference A-139 Example A-3 (Cont.) UDP/IP Server /* * Functional Description * * This example creates a socket of type SOCK_DGRAM (UDP), binds * it, and selects to receive a message on the socket. * Error messages are printed to the screen. * * IPC calls used: * bind * close * gethostbyname * recvfrom * select * shutdown * socket * * * Formal Parameters * The server program expects one parameter: * portnumber ... port where it is listening * * * Routine Value * * Status */ /*--------------------------------------------------------------------*/ main( int argc, char **argv ) { (continued on next page) A-140 Compaq C Socket Routine Reference Example A-3 (Cont.) UDP/IP Server int rmask, wmask, emask; int sock_2; /* Socket2 descriptor. */ int buflen,fromlen; char recvbuf[BUFSIZ]; static struct sockaddr_in sock1_name; /* Address struct for socket1.*/ static struct sockaddr_in sock2_name; /* Address struct for socket2.*/ int namelength; struct hostent hostentstruct; /* Storage for hostent data. */ struct hostent *hostentptr; /* Pointer to hostent data. */ static char hostname[256]; /* Name of local host. */ int retval; int flag; struct timeval timeout; /* * Check input parameters. */ if (argc != 2 ) { printf("Usage: server portnumber.\n"); exit( 1 ); } /* * Open socket 2: AF_INET, SOCK_DGRAM. */ if ((sock_2 = socket (AF_INET, SOCK_DGRAM, 0)) == -1) { perror( "socket"); exit( 1 ); } (continued on next page) Compaq C Socket Routine Reference A-141 Example A-3 (Cont.) UDP/IP Server /* * Get the local host name. */ retval = gethostname(hostname,sizeof hostname); if (retval) { perror ("gethostname"); cleanup(sock_2); } /* * Get pointer to network data structure for local host. */ if ((hostentptr = gethostbyname (hostname)) == NULL) { perror( "gethostbyname"); cleanup(sock_2); } /* * Copy hostent data to safe storage. */ hostentstruct = *hostentptr; /* * Fill in the address structure for socket 2. */ sock2_name.sin_family = hostentstruct.h_addrtype; sock2_name.sin_port = htons(atoi(argv[1])); sock2_name.sin_addr = * ((struct in_addr *) hostentstruct.h_addr); (continued on next page) A-142 Compaq C Socket Routine Reference Example A-3 (Cont.) UDP/IP Server /* * Bind name to socket 2. */ retval = bind ( sock_2, (struct sockaddr*)&sock2_name, sizeof sock2_name ); if (retval) { perror("bind"); cleanup(sock_2); } /* * Select socket to receive message. */ emask = wmask = 0; rmask = (1< /* VMS descriptor stuff */ #include /* Unix style error codes for IO routines. */ #include /* internet system Constants and structures. */ #include /* Network address info. */ #include /* I/O FUNCTION CODE DEFS */ #include /* LIB$ RTL-routine signatures. */ #include /* Network database library info. */ #include /* UNIX style Signal Value Definitions */ #include /* TCP/IP socket definitions. */ #include /* SS$_ sys ser return statistics */ #include /* Sys ser calls */ #include /* UNIX 'Standard I/O' Definitions */ #include /* General Utilities */ #include /* String handling function definitions */ #include /* UCX network definitions */ #include /* Prototypes for UNIX emulation functions */ (continued on next page) Compaq C Socket Routine Reference A-147 Example A-4 (Cont.) UDP/IP Client #else #include #include #include #include #include #include #include #include #endif /*-----------------------------------------------------------*/ cleanup(int socket) { int retval; /* * Shutdown socket completely. */ retval = shutdown(socket,2); if (retval == -1) perror ("shutdown"); /* * Close socket. */ retval = close (socket); if (retval) perror ("close"); exit( 1 ); } /* end cleanup */ (continued on next page) A-148 Compaq C Socket Routine Reference Example A-4 (Cont.) UDP/IP Client /* * Functional Description * * This example creates a socket of type SOCK_DGRAM (UDP), * binds it, and sends a message to the given host and port number. * Error messages are printed to the screen. * * IPC calls used: * bind * close * gethostbyname * sendto * shutdown * socket * * Formal Parameters * The client program expects two parameters: * hostname ... name of remote host * portnumber ... port where remote host(server) is listening * * * Routine Value * * Status */ /*--------------------------------------------------------------------*/ main( int argc, char **argv ) { int sock_1; /* Socket 1 descriptor. */ int sendlen, tolen; static char sendbuf[] = "Hi there."; static struct sockaddr_in sock2_name; /* Address struct for socket2.*/ int namelength; struct hostent hostentstruct; /* Storage for hostent data. */ struct hostent *hostentptr; /* Pointer to hostent data. */ static char hostname[256]; /* Name of local host. */ int flag; int retval; (continued on next page) Compaq C Socket Routine Reference A-149 Example A-4 (Cont.) UDP/IP Client /* * Check input parameters. */ if (argc != 3 ) { printf("Usage: client hostname portnumber.\n"); exit( 1 ); } /* * Open socket 1: AF_INET, SOCK_DGRAM. */ if ((sock_1 = socket (AF_INET, SOCK_DGRAM, 0)) == -1) { perror( "socket"); exit( 1 ); } /* *Get pointer to network data structure for given host. */ if ((hostentptr = gethostbyname (argv[1])) == NULL) { perror( "gethostbyname"); cleanup(sock_1); } /* * Copy hostent data to safe storage. */ hostentstruct = *hostentptr; /* * Fill in the address structure for socket 2 (to receive message). */ sock2_name.sin_family = hostentstruct.h_addrtype; sock2_name.sin_port = htons(atoi(argv[2])); sock2_name.sin_addr = * ((struct in_addr *) hostentstruct.h_addr); (continued on next page) A-150 Compaq C Socket Routine Reference Example A-4 (Cont.) UDP/IP Client /* * Initialize send block. */ sendlen = sizeof sendbuf; tolen = sizeof sock2_name; flag = 0; /* flag may be MSG_OOB */ /* * Send message from socket 1 to socket 2. */ retval = sendto( sock_1, sendbuf, sendlen, flag, (struct sockaddr*)&sock2_name, tolen); if (retval == -1) { perror ( "sendto"); cleanup(sock_1); } /* * Call cleanup to shut down and close socket. */ cleanup(sock_1); } /* end main */ Compaq C Socket Routine Reference A-151 B _________________________________________________________________ Version-Dependency Tables Many functions were added to the DEC C Run-Time Library in DEC C Version 5.0 and 5.2. These functions are implemented and shipped with the OpenVMS operating system, while the documentation and header files containing their prototypes are shipped with versions of Compaq C. You might have a newer version of Compaq C that has header files and documentation for functions that are not supported on your older OpenVMS system. For example, if your target operating system platform is OpenVMS Version 6.2, you cannot use Compaq C RTL functions that were introduced on OpenVMS Version 7.0, even though they are documented in this manual. This appendix contains several tables that list what Compaq C RTL functions are supported on recent OpenVMS versions. This is helpful for determining the functions to avoid using on your target OpenVMS platforms. B.1 Functions Available on all OpenVMS VAX and OpenVMS Alpha Versions Table B-1 lists functions available on all OpenVMS VAX and OpenVMS Alpha versions. Table_B-1_Functions_Available_on_All_OpenVMS_Systems_______ abort abs access acos alarm asctime asin assert atan2 atan atexit atof atoi atoll (Alpha) atol atoq (Alpha) (continued on next page) Version-Dependency Tables B-1 Table B-1 (Cont.) Functions Available on All OpenVMS __________________Systems__________________________________ box brk bsearch cabs calloc ceil cfree chdir chmod chown clearerr clock close cosh cos creat ctermid ctime cuserid decc$crtl_init decc$fix_ decc$from_vms decc$match_ decc$record_read time wild decc$record_ decc$set_ decc$to_vms decc$translate_ write reentrancy vms delete delwin difftime div dup2 dup ecvt endwin execle execlp execl execve execvp execv exit _exit exp fabs fclose fcvt fdopen feof ferror fflush fgetc fgetname fgetpos fgets fileno floor fmod fopen fprintf fputc fputs fread free freopen frexp fscanf fseek fsetpos fstat fsync ftell ftime fwait fwrite gcvt getchar getcwd getc getegid getenv geteuid getgid getname getpid getppid gets getuid getw gmtime gsignal hypot initscr isalnum isalpha isapipe isascii isatty iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit kill labs ldexp ldiv (continued on next page) B-2 Version-Dependency Tables Table B-1 (Cont.) Functions Available on All OpenVMS __________________Systems__________________________________ llabs lldiv (Alpha) localeconv localtime (Alpha) log10 log longjmp longname lseek lwait malloc mblen mbstowcs mbtowc memchr memcmp memcpy memmove memset mkdir mktemp mktime modf mvwin mv[w]addstr newwin nice open overlay overwrite pause perror pipe pow printf putchar putc puts putw qabs (Alpha) qdiv (Alpha) qsort raise rand read realloc remove rename rewind sbrk scanf scroll setbuf setgid setjmp setlocale setuid setvbuf sigblock signal sigpause sigstack sigvec sinh (VAX) sin sleep sprintf sqrt srand sscanf ssignal stat strcat strchr strcmp strcoll strcpy strcspn strerror strftime strlen strncat strncmp strncpy strpbrk strrchr strspn strstr strtod strtok strtoll strtol (Alpha) strtoq strtoull strtoul strtouq (Alpha) (Alpha) (Alpha) strxfrm subwin system tanh tan times time tmpfile (continued on next page) Version-Dependency Tables B-3 Table B-1 (Cont.) Functions Available on All OpenVMS __________________Systems__________________________________ tmpnam toascii tolower _tolower touchwin toupper _toupper ttyname umask ungetc vaxc$calloc_ vaxc$cfree_opt opt vaxc$crtl_ vaxc$establish vaxc$free_ vaxc$malloc_opt init opt vaxc$realloc_ va_arg va_count va_end opt va_start va_start_1 vfork vfprintf vprintf vsprintf wait wcstombs wctomb write [w]addch [w]addstr [w]clear [w]clrattr [w]clrtobot [w]clrtoeol [w]delch [w]deleteln [w]erase [w]getch [w]getstr [w]inch [w]insch [w]insertln [w]insstr [w]move [w]printw [w]refresh [w]scanw______[w]setattr_____[w]standend__[w]standout______ B.2 Functions Available on OpenVMS Version 6.2 and Higher Table B-2 lists functions available on OpenVMS Version 6.2 and higher. Table_B-2_Functions_Added_in_OpenVMS_Version_6.2___________ catclose catgets catopen fgetwc fgetws fputwc fputws getopt getwc getwchar iconv iconv_close iconv_open iswalnum iswalpha iswcntrl iswctype iswdigit iswgraph iswlower iswprint iswpunct iswspace iswupper iswxdigit nl_langinfo putwc putwchar (continued on next page) B-4 Version-Dependency Tables Table_B-2_(Cont.)_Functions_Added_in_OpenVMS_Version_6.2___ strnlen strptime towlower towupper ungetwc wcscat wcschr wcscmp wcscoll wcscpy wcscspn wcsftime wcslen wcsncat wcsncmp wcsncpy wcspbrk wcsrchr wcsspn wcstol wcstoul wcswcs wcswidth wcsxfrm wcstod_________wctype_________wcwidth________wcstok________ B.3 Functions Available on OpenVMS Version 7.0 and Higher Table B-3 lists functions available on OpenVMS VAX and OpenVMS Alpha Version 7.0 and higher. Table_B-3_Functions_Added_in_OpenVMS_Version_7.0___________ basename bcmp bcopy btowc bzero closedir confstr dirname drand48 erand48 ffs fpathconf ftruncate ftw fwide fwprintf fwscanf getclock getdtablesize getitimer getlogin getpagesize getpwnam getpwuid gettimeofday index initstate jrand48 lcong48 lrand48 mbrlen mbrtowc mbsinit mbsrtowcs memccpy mkstemp mmap mprotect mrand48 msync munmap nrand48 opendir pathconf pclose popen putenv random readdir rewinddir rindex rmdir seed48 seekdir setenv setitimer setstate sigaction sigaddset sigdelset sigemptyset sigfillset sigismember siglongjmp sigpending sigprocmask sigsetjmp sigsuspend (continued on next page) Version-Dependency Tables B-5 Table_B-3_(Cont.)_Functions_Added_in_OpenVMS_Version_7.0___ srand48 srandom strcasecmp strdup strfmon strncasecmp strsep swab swprintf swscanf sysconf telldir tempnam towctrans truncate tzset ualarm uname unlink unsetenv usleep vfwprintf vswprintf vwprintf wait3 wait4 waitpid wcrtomb wcsrtombs wcsstr wctob wctrans wmemchr wmemcmp wmemcpy wmemmove wmemset________wprintf________wscanf_______________________ B-6 Version-Dependency Tables B.4 Functions Available on OpenVMS Alpha Version 7.0 and Higher Table B-4 lists functions available on OpenVMS Alpha Version 7.0 and higher. Table_B-4_Functions_Added_in_OpenVMS_Alpha_Version_7.0_____ _basename32 _basename64 _bsearch32 _bsearch64 _calloc32 _calloc64 _catgets32 _catgets64 _ctermid32 _ctermid64 _cuserid32 _cuserid64 _dirname32 _dirname64 _fgetname32 _fgetname64 _fgets32 _fgets64 _fgetws32 _fgetws64 _gcvt32 _gcvt64 _getcwd32 _getcwd64 _getname32 _getname64 _gets32 _gets64 _index32 _index64 _longname32 _longname64 _malloc32 _malloc64 _mbsrtowcs32 _mbsrtowcs64 _memccpy32 _memccpy64 _memchr32 _memchr64 _memcpy32 _memcpy64 _memmove32 _memmove64 _memset32 _memset64 _mktemp32 _mktemp64 _mmap32 _mmap64 _qsort32 _qsort64 _realloc32 _realloc64 _rindex32 _rindex64 _strcat32 _strcat64 _strchr32 _strchr64 _strcpy32 _strcpy64 _strdup32 _strdup64 _strncat32 _strncat64 _strncpy32 _strncpy64 _strpbrk32 _strpbrk64 _strptime32 _strptime64 _strrchr32 _strrchr64 _strsep32 _strsep64 _strstr32 _strstr64 _strtod32 _strtod64 _strtok32 _strtok64 _strtol32 _strtol64 _strtoll32 _strtoll64 _strtoq32 _strtoq64 _strtoul32 _strtoul64 _strtoull32 _strtoull64 _strtouq32 _strtouq64 _tmpnam32 _tmpnam64 _wcscat32 _wcscat64 _wcschr32 _wcschr64 _wcscpy32 _wcscpy64 _wcsncat32 _wcsncat64 _wcsncpy32 _wcsncpy64 _wcspbrk32 _wcspbrk64 (continued on next page) Version-Dependency Tables B-7 Table B-4 (Cont.) Functions Added in OpenVMS Alpha Version __________________7.0______________________________________ _wcsrchr32 _wcsrchr64 _wcsrtombs32 _wcsrtombs64 _wcsstr32 _wcsstr64 _wcstok32 _wcstok64 _wcstol32 _wcstol64 _wcstoul32 _wcstoul64 _wcswcs32 _wcswcs64 _wmemchr32 _wmemchr64 _wmemcpy32 _wmemcpy64 _wmemmove32 _wmemmove64 _wmemset32______wmemset64__________________________________ B-8 Version-Dependency Tables B.5 Functions Available on OpenVMS Version 7.2 and Higher Table B-5 lists functions available on OpenVMS VAX and OpenVMS Alpha Version 7.2 and higher. Table_B-5_Functions_Added_in_OpenVMS_Version_7.2___________ asctime_r ctime_r decc$set_ decc$write_ child_ eof_to_mbx standard_ streams decc$validate_ dlclose dlerror dlopen wchar dlsym__________fcntl__________gmtime_r_______localtime_r___ B.6 Functions Available on OpenVMS Version 7.3 and Higher Table B-6 lists functions available on OpenVMS VAX and OpenVMS Alpha Version 7.3 and higher. Table_B-6_Functions_Added_in_OpenVMS_Version_7.3___________ fchown link utime utimes writev_____________________________________________________ Version-Dependency Tables B-9 C _________________________________________________________________ Prototypes Duplicated to Non-Standard Headers The various standards dictate which header file must define each of the standard functions. This is the included header file documented with each function prototype in the Reference Section of this manual. However, many of the functions defined by the standards already existed on several operating systems and were defined in different header files. This is especially true on OpenVMS systems with the header files , , and . So, to provide upward compatibility for these functions, their prototypes are duplicated in both the expected header file as well as the header file defined by the standards. Table C-1 lists these functions. Table_C-1_Duplicated_Prototypes____________________________ Duplicated Function_____in____________Standard_says___________________ access alarm bcmp bcopy bzero chdir chmod chown close (continued on next page) Prototypes Duplicated to Non-Standard Headers C-1 Table_C-1_(Cont.)_Duplicated_Prototypes____________________ Duplicated Function_____in____________Standard_says___________________ creat ctermid cuserid dirname dup dup2 ecvt execl execle execlp execv execve execvp _exit fcvt ffs fsync ftime gcvt getcwd getegid getenv geteuid getgid getopt getpid getppid getuid (continued on next page) C-2 Prototypes Duplicated to Non-Standard Headers Table_C-1_(Cont.)_Duplicated_Prototypes____________________ Duplicated Function_____in____________Standard_says___________________ index isatty lseek mkdir mktemp nice open pause pipe read rindex sbrk setgid setuid sleep strcasecmp strncasecmp system times umask vfork wait write__________________________________ Prototypes Duplicated to Non-Standard Headers C-3 _________________________________________________________________ Index 64-bit pointer support, 1-60 assert function, REF-15 AST reentrancy, 1-56, REF-102 A______________________________ atan function, REF-17 abort function, 4-1, REF-3 atan2 function, REF-18 abs function, REF-4 atexit function, REF-19 accept socket routine, A-19 atof function, REF-21 access function, REF-5 atoi function, REF-22 ACCVIO atol function, REF-22 hardware error, 1-54 atoll function, REF-23 sigbus signal, 4-14 atoq function, REF-23 sigsegv signal, 4-16 Auxiliary communication acos function, REF-7 routines, A-15 addch function, REF-8 addstr function, REF-10 B______________________________ alarm function, 4-1, 4-14, basename function, REF-24 REF-11 Basic communication routines, program example, 4-20 A-14 Allocate memory bcmp function, REF-26 calloc function, REF-37 bcopy function, REF-27 malloc function, REF-355 bind socket routine, A-22 realloc function, REF-478 box function, REF-28 _ANSI_C_SOURCE macro, 1-30 brk function, 8-1, REF-29 Argument list functions, 3-17 _BSD44_CURSES macro, 1-37 to 3-21 bsearch function, REF-31 Arguments btowc function, 10-15, REF-34 variable-length lists, 3-17 bzero function, REF-35 ASCII table of values, 3-7 C asctime function, REF-12 _______________________________ asctime_r function, REF-12 C language asin function, REF-14 I/O background, 1-39 asm calls, 1-54 C$_LONGJMP exception, 4-17 Index-1 cabs function, REF-36 Character-classification calloc function, 8-1, REF-37, functions (cont'd) REF-48 isdigit, REF-302 Carriage control isgraph, REF-303 FORTRAN, 1-46 islower, REF-304 translation isprint, REF-305 by Compaq C, 1-44 to 1-48 ispunct, REF-306 Case conversion functions, isspace, REF-307 10-14 isupper, REF-308 Case preservation in file iswalnum, REF-309 names, xxx iswalpha, REF-310 catclose function, 10-8, iswcntrl, REF-311 REF-38 iswctype, REF-312 Categories iswdigit, REF-315 locale, 10-5 iswgraph, REF-316 Category iswlower, REF-317 LC_ALL, 10-6 iswprint, REF-318 LC_COLLATE, 10-5 iswpunct, REF-319 LC_CTYPE, 10-5 iswspace, REF-320 LC_MESSAGES, 10-5 iswupper, REF-321 LC_MONETARY, 10-5 iswxdigit, REF-322 LC_NUMERIC, 10-5 isxdigit, REF-323 LC_TIME, 10-5 program example, 3-12 catgets function, 10-8, REF-39 wctype, REF-817 catopen function, 10-8, REF-43 Character-conversion functions ceil function, REF-47 , 3-14 to 3-16 cfree function, 8-1, REF-48 ecvt, REF-133 Character definition files fcvt, REF-159 location of, 10-9 gcvt, REF-233 Character set conversion toascii, REF-670 functions tolower, REF-671 iconv, REF-281 _tolower, REF-672 iconv_close, REF-283 toupper, REF-674 iconv_open, REF-284 _toupper, REF-675 Character sets towlower, REF-677 converting between, 10-9 towupper, REF-678 supported by Compaq C RTL, wcswidth, REF-807 10-8 wcwidth, REF-822 Character-classification Charmap file functions, 3-7 to 3-13, location, 10-9 10-13 chdir function, REF-49 isalnum, REF-296 Child process isalpha, REF-297 creating with vfork, REF-716 isascii, REF-299 executing image iscntrl, REF-301 with exec functions, 5-4 Index-2 Child process (cont'd) cos function, REF-69 implementation of, 5-2 cosh function, REF-70 introduction to, 5-1 cot function, REF-71 program examples, 5-7 creat function, REF-72, sharing data with pipe, 5-7, REF-131, REF-155, REF-161 REF-441 crmode function, REF-81 synchronization with wait, ctermid function, REF-83 5-7 ctime function, REF-12, REF-84 chmod function, REF-51 using with tzset function, chown function, REF-53 REF-681 clear function, REF-54, REF-56 ctime_r function, REF-84 clearerr function, REF-55 Cultural information clearok function, REF-56 stored in locale, 10-11 clock function, REF-57 curscr window, 6-8 close function, REF-58 Curses, 6-1 to 6-20 close socket routine, A-24 cursor movement, 6-16 closedir function, REF-60 getting started, 6-11 to clrattr function, REF-63 6-14 clrattr macro, 6-3 introduction to, 6-1 clrtobot function, REF-64 program example, 6-18 clrtoeol function, REF-65 terminology, 6-7 to 6-11 Codeset converter functions, curscr, 6-8 10-9 stdscr, 6-8 Codesets, 10-8 windows, 6-9 Communication support routines using predefined variables , A-16 and constants, 6-15 Compaq C RTL Curses functions See Run-Time Library (RTL) box, REF-28 confstr function, REF-66 clearok, REF-56 connect socket routine, A-25 delwin, REF-119 Conversion specifications endwin, REF-135 for I/O functions, 2-10 to getyx, REF-275 2-38 initscr, REF-290 input leaveok, REF-333 table of conversion longname, REF-349 specifiers, 2-13 mvcur, REF-407 table of optional mvwin, REF-414 mv[w]addch, REF-403 characters, 2-12 mv[w]addstr, REF-405 output mv[w]delch, REF-408 table of characters, 2-30 mv[w]getch, REF-409 Converter functions mv[w]getstr, REF-410 filenaming conventions for, mv[w]inch, REF-411 10-9 mv[w]insch, REF-412 mv[w]insstr, REF-413 Index-3 Curses functions (cont'd) Date/time functions, 11-1 to newwin, REF-415 11-9 [no]crmode, REF-81 DECC$CRTL_INIT function, [no]echo, REF-132 REF-87, REF-690 [no]nl, REF-417 decc$fix_time file [no]raw, REF-470 specification conversion overlay, REF-432 routine, 1-25, REF-88 overwrite, REF-433 decc$from_vms file scroll, REF-493 specification conversion scrollok, REF-494 routine, 1-25, REF-90 subwin, REF-640 decc$get_sdc socket routine, touchwin, REF-673 A-28 wrapok, REF-833 decc$match_wild file [w]addch, REF-8 specification conversion [w]addstr, REF-10 routine, 1-25, REF-92 [w]clear, REF-54 decc$record_read function, [w]clrattr, REF-63 REF-94 [w]clrtobot, REF-64 decc$record_write function, [w]clrtoeol, REF-65 REF-95 [w]delch, REF-115 decc$set_child_standard_ [w]deleteln, REF-118 [w]erase, REF-138 streams function, REF-96 [w]getch, REF-236 decc$set_reentrancy function, [w]getstr, REF-268 1-57, REF-102 [w]inch, REF-288 DECC$SHR.EXE, 1-4 [w]insch, REF-293 decc$socket_fd socket routine, [w]insertln, REF-294 A-115 [w]insstr, REF-295 decc$to_vms file specification [w]move, REF-393 conversion routine, 1-25, [w]printw, REF-451 REF-104 [w]refresh, REF-480 decc$translate_vms file [w]scanw, REF-491 specification conversion [w]setattr, REF-498 routine, 1-25, REF-107 [w]standend, REF-565 decc$validate_wchar function, [w]standout, REF-566 REF-109 header file, 6-3 decc$write_eof_to_mbx function cuserid function, REF-86 , REF-111 D _DECC_V4_SOURCE macro, 1-36 _______________________________ DEC/SHELL Date and time functions, 10-12 See UNIX file specifications Date/time delch function, REF-115 introduction to, 11-1 Index-4 delete function, REF-116, errno variable, 4-3, 4-7, 7-5 REF-481 header file, 4-3, deleteln function, REF-118 4-7 delwin function, REF-119 header file, 4-17 difftime function, REF-120 Error-handling functions, 4-3 dirname function, REF-121 abort, 4-1, 4-8, 4-14, REF-3 div function, REF-123 error codes, 4-3 dlcose function, REF-124 exit, 4-1, 5-7, REF-148 dlerror function, REF-125 _exit, 4-1, 5-7, REF-148 dlopen function, REF-126 perror, 4-1, REF-439 dlsym function, REF-128 strerror, 4-1, REF-582 drand48 function, REF-129 etext global symbol, 1-53 using with lcong48 function, Exact-case argv arguments, REF-329 xxxi using with seed48 function, exec function, REF-443 REF-495 exec functions, 5-4 using with srand48 function, error conditions, 5-6 REF-559 processing, 5-5 dup function, REF-131, REF-161 execl function, REF-139 dup2 function, REF-131, execle function, REF-141 REF-161, REF-444 execlp function, REF-143 execv function, REF-144 E______________________________ execve function, REF-145 echo function, REF-132 execvp function, REF-147 ecvt function, 3-14, REF-133 _exit function, 5-7 edata global symbol, 1-53 exit function, 5-7, REF-148 end global symbol, 1-53 _exit function, REF-148 endhostent socket routine, exit, _exit function using with wait3 function, A-29 REF-733 endnetent socket routine, A-30 using with wait4 function, endprotoent socket routine, REF-739 A-31 using with waitpid function, endservent socket routine, REF-744 A-32 exp function, REF-150 endwin function, REF-135 Extended file specifications, erand48 function, REF-136 xxx erase function, REF-138 ERR predefined macro, 6-15 F errno _______________________________ external variable, A-5 fabs function, REF-151 relationship to h_errno, fchown function, REF-152 A-11 Index-5 fclose function, REF-154, fopen function, REF-181 REF-182 fork function, REF-716 fcntl function, REF-155 Format fcvt function, 3-14, REF-159 specification string for fdopen function, REF-161, input functions, 2-11 REF-444 specification string for Feature-test macros, 1-29 output functions, 2-24 feof function, REF-162 fpathconf function, REF-186 ferror function, REF-163 fprintf function, REF-189 fflush function, REF-164 fputc function, REF-192 using with popen function, fputs function, REF-193 REF-446 fputwc function, REF-194 ffs function, REF-165 fputws function, REF-196 fgetc function, REF-166 fp_class function, REF-184 fgetname function, REF-167 fp_classf function, REF-184 fgetpos function, REF-169 fp_classl function, REF-184 fgets function, REF-171 fread function, REF-197 fgetwc function, REF-173 free function, 8-1, REF-48, fgetws function, REF-175 REF-199, REF-240 File using with tempnam function, header, 1-1 REF-664 FILE, 2-8 freopen function, REF-200 File descriptor, 2-7, 2-39 frexp function, REF-202 Compaq C defaults fscanf function, REF-204 for OpenVMS logical names, fseek function, 1-43, REF-207, 1-28 REF-693, REF-694 File pointer, 2-7, 2-38 fsetpos function, REF-209 File protection, REF-51, fstat function, REF-210 REF-690 fsync function, REF-214 File specification conversion ftell function, REF-215 routines ftime function, REF-216 decc$fix_time, REF-88 ftruncate function, REF-218 decc$from_vms, REF-90 ftw function, REF-219 decc$match_wild, REF-92 Function prototype, 1-23 decc$to_vms, REF-104 Functions decc$translate_vms, REF-107 argument list-handling, 3-17 fileno function, REF-178 case conversion, 10-14 Fixed-length record files character classification, accessing in record mode, 10-13 1-49 character-classification, Floating-point support, 1-6 3-7 floor function, REF-179 character-conversion, 3-14, fmod function, REF-180 3-15 Curses, 6-1 to 6-7 Date/time, 11-1 to 11-9 Index-6 Functions (cont'd) getname function, REF-252, error-handling, 4-3 to 4-7 REF-443 signal-handling, 4-7 to 4-20 getnetbyaddr socket routine, Standard I/O, 2-1, 2-7 A-40 string-handling, 3-16 getnetbyname socket routine, Terminal I/O, 2-38 A-41 Time, 11-1 to 11-9 getnetent socket routine, A-43 UNIX I/O, 2-7 getopt function, REF-254 fwait function, REF-222 getpagesize function, REF-259 fwide function, REF-223 getpeername socket routine, fwprintf function, REF-225 A-44 fwrite function, REF-229 getpid function, REF-260 fwscanf function, REF-231 getppid function, REF-261 getprotobyname socket routine, G______________________________ A-46 gcvt function, 3-14, REF-233 getprotobynumber socket GENCAT command, 10-8 routine, A-47 getc function, REF-235 getprotoent socket routine, getch function, REF-236 A-48 getchar function, REF-237 getpwnam function, REF-262 getclock function, REF-238 getpwuid function, REF-264 getcwd function, REF-240 gets function, REF-171, getdtablesize function, REF-175, REF-266 REF-242 getservbyname socket routine, getegid function, REF-243 A-49 getenv function, REF-244 getservbyport socket routine, using with putenv function, A-51 REF-455 getservent socket routine, geteuid function, REF-246 A-52 getgid function, REF-248 getsockname socket routine, gethostaddr socket routine, A-53 A-33 getsockopt socket routine, gethostbyaddr socket routine, A-55 A-34 getstr function, REF-268 gethostbyname socket routine, gettimeofday function, REF-269 A-36 getuid function, REF-270 gethostent socket routine, getw function, REF-272 A-38 getwc function, REF-273 gethostname socket routine, getwchar function, REF-274 A-39 getyx function, REF-275 getitimer function, REF-249 gmtime function, REF-276 getlogin function, REF-251 gmtime_r function, REF-276 Index-7 gsignal function, 4-7, 4-14, Input and output (I/O), 1-38 REF-278 to 1-48 conversion specifications, H______________________________ 2-10 to 2-38 Header files, 1-1, 1-23 format specification string, displaying on Alpha systems, 2-11, 2-24 1-1 OpenVMS system services, displaying on VAX systems, 1-39 1-2 record access herror socket routine, A-57 in Compaq C, 1-45 hostalias socket routine, A-59 Record Management Services hstrerror socket routine, A-58 (RMS), 1-39 htonl socket routine, A-60 Standard, 1-39 htons socket routine, A-62 stream access hypot function, REF-280 in Compaq C, 1-44 h_errno UNIX, 1-39 external variable, A-10 Wide-character, 2-9 relationship to errno, A-11 insch function, REF-293 support routines, A-15 insertln function, REF-294 insstr function, REF-295 I insstr macro, 6-3 _______________________________ International software iconv function, 10-9, REF-281 description of, 10-2 iconv_close function, 10-9, Internationalization support, REF-283 10-1 iconv_open function, 10-9, Internet REF-284 application programs, A-1 IMAGELIB.OLB, 1-4 protocols, A-3 inch function, REF-288 Interprocess communication, index function, REF-289 5-2 inet_addr socket routine, A-64 ioctl socket routine, A-71 inet_lnaof socket routine, isalnum function, REF-296 A-66 isalpha function, REF-297 inet_makeaddr socket routine, isapipe function, REF-298 A-67 isascii function, REF-299 inet_netof socket routine, isatty function, REF-300 A-68 iscntrl function, REF-301 inet_network socket routine, isdigit function, REF-302 A-69 isgraph function, REF-303 inet_ntoa socket routine, A-70 islower function, REF-304 initscr function, REF-290 isprint function, REF-305 initstate function, REF-291 ispunct function, REF-306 using with setstate function, isspace function, REF-307 REF-514 Index-8 isupper function, REF-308 LIB$SIGNAL, 4-14 iswalnum function, REF-309 Libraries iswalpha function, REF-310 Compaq C RTL object-module iswcntrl function, REF-311 linking order, 1-13 iswctype function, REF-312 Library iswdigit function, REF-315 main function, 1-3 iswgraph function, REF-316 link function, REF-334 iswlower function, REF-317 Linker iswprint function, REF-318 search libraries, 1-3 iswpunct function, REF-319 Linking iswspace function, REF-320 with RTL object libraries, iswupper function, REF-321 1-6 iswxdigit function, REF-322 Linking with the C RTL, 1-4 to isxdigit function, REF-323 1-22 itimerval structure, REF-249, List-handling functions REF-504 va_arg, REF-710 va_count, REF-711 J______________________________ va_end, REF-712 jrand48 function, REF-324 va_start, REF-713 va_start_1, REF-713 K listen socket routine, A-73 _______________________________ llabs function, REF-461 kill function, REF-326 lldiv function, REF-462 LNK$LIBRARY logical name, 1-4, L______________________________ 1-13 labs function, REF-328 Locale LANG logical name, 10-7 categories, 10-5 lcong48 function, REF-329 description of, 10-4 using with drand48 function, extracting information from, REF-129 10-12 using with lrand48 function, Locale support functions REF-350 localeconv, REF-336 using with mrand48 function, nl_langinfo, REF-418 REF-396 setlocale, REF-509 LC_ALL category, 10-6 localeconv function, 10-12, LC_ALL logical name, 10-7 REF-336 LC_CTYPE category, 10-13 localtime function, REF-342 LC_NUMERIC logical name, 10-7 using with tzset function, ldexp function, REF-331 REF-681 ldiv function, REF-332 localtime_r function, REF-342 leaveok function, REF-333 log function, REF-345 LIB$ESTABLISH function, 4-17, log10 function, REF-345 REF-708 Logical name for default locale, 10-7 Index-9 Logical name (cont'd) main function (cont'd) for default locale categories using with waitpid function, , 10-7 REF-744 for international environment Main function, 1-3, 4-16 , 10-7 main_program option, 1-3 for locale directory, 10-5 malloc function, 8-1, REF-48, for system default locale, REF-355 10-7 using with ftw function, LANG, 10-7 REF-220 LC_ALL, 10-7 using with putenv function, LC_NUMERIC, 10-7 REF-455 SYS$I18N_LOCALE, 10-5 Math functions, 7-1 to 7-8 SYS$LANG, 10-7 abs, REF-4 SYS$LC_ALL, 10-7 acos, REF-7 Long file names asin, REF-14 arguments to C RTL functions, atan, REF-17 xxxi atan2, REF-18 longjmp function, 4-17, cabs, REF-36 REF-346, REF-708, REF-717 ceil, REF-47 longjmp member cos, REF-69 using with ftw function, cosh, REF-70 REF-220 cot, REF-71 longname function, REF-349 div, REF-123 lrand48 function, REF-350 errno values, 7-1 using with lcong48 function, exp, REF-150 REF-329 fabs, REF-151 using with seed48 function, floor, REF-179 REF-495 fp_class, REF-184 using with srand48 function, fp_classf, REF-184 REF-559 fp_classl, REF-184 lseek function, 1-43, REF-352 frexp, REF-202 lstat function hypot, REF-280 using with ftw function, labs, REF-328 REF-220 ldexp, REF-331 lwait function, REF-354 ldiv, REF-332 llabs, REF-461 M lldiv, REF-462 _______________________________ log, REF-345 Macros log10, REF-345 feature-test, 1-29 modf, REF-392 main function pow, REF-448 using with wait3 function, qabs, REF-461 REF-733 qdiv, REF-462 using with wait4 function, rand, REF-467 REF-739 sin, REF-552 Index-10 Math functions (cont'd) mkdir function, REF-377 sinh, REF-553 mkstemp function, REF-381 sqrt, REF-557 mktemp function, REF-382 srand, REF-558 mktime function, REF-383 tan, REF-660 using with tzset function, tanh, REF-661 REF-681 mblen function, REF-357 mmap function, REF-385 mbrlen function, REF-358 modf function, REF-392 mbrtowc function, 3-14, 10-15, Modules REF-360 Compaq C RTL object linking mbsinit function, REF-366 order, 1-13 mbsrtowcs function, 3-14, Monetary formatting function 10-15, REF-367 strfmon, REF-584 mbstate_t, 10-16, REF-358, Monetary function, 10-12 REF-360, REF-366, REF-367, move function, REF-393 REF-747, REF-784 mprotect function, REF-394 mbstowcs function, 10-15, mrand48 function, REF-396 REF-362 using with lcong48 function, mbtowc function, 3-14, 10-15, REF-329 REF-364 using with seed48 function, memccpy function, REF-369 REF-495 memchr function, REF-371 using with srand48 function, memcmp function, REF-372 REF-559 memcpy function, REF-373 msync function, REF-398 memmove function, REF-374 Multibyte character Memory allocation conversion to wide character, introduction to, 8-1 10-15 program examples, 8-2 Multibyte character support Memory allocation functions btowc, REF-34 brk, REF-29 mblen, REF-357 calloc, REF-37 mbrlen, REF-358 cfree, REF-48 mbrtowc, REF-360 free, REF-199 mbsinit, REF-366 malloc, REF-355 mbtowc, REF-364 realloc, REF-478 wcrtomb, REF-747 sbrk, REF-488 wctob, REF-813 Memory reallocation, REF-199 wctomb, REF-814 memset function, REF-376 Multibyte string support Message catalog, 10-4 mbsrtowcs, REF-367 creating, 10-8 mbstowcs, REF-362 Messaging functions wcsrtombs, REF-784 catclose, REF-38 wcstombs, REF-799 catgets, REF-39 catopen, REF-43 Index-11 MULTITHREAD reentrancy, 1-56, REF-102 O______________________________ Multithread Restrictions, 1-59 Object libraries munmap function, REF-401 RTL, 1-6 mvaddch function, REF-403 Object library mvaddstr function, REF-405 VAXCRTL.OLB, 1-6 mvcur function, REF-407 VAXCRTLD.OLB, 1-6 mvdelch function, REF-408 VAXCRTLDX.OLB, 1-6 mvgetch function, REF-409 VAXCRTLT.OLB, 1-6 mvgetstr function, REF-410 VAXCRTLTX.OLB, 1-6 mvinch function, REF-411 VAXCRTLX.OLB, 1-6 mvinsch function, REF-412 Object module mvinsstr function, REF-413 Compaq C RTL linking order, mvinsstr macro, 6-3 1-13 mvwaddch function, REF-403 Occlusion, 6-7 mvwaddstr function, REF-405 open function, REF-131, mvwdelch function, REF-408 REF-155, REF-161, REF-426 mvwgetch function, REF-409 opendir function, REF-430 mvwgetstr function, REF-410 using with readdir function, mvwin function, REF-414 REF-476 mvwinch function, REF-411 using with rewinddir function mvwinsch function, REF-412 , REF-485 mvwinsstr function, REF-413 OpenVMS system services mvwinsstr macro, 6-3 in Compaq C programs, 1-39 N OpenVMS versions, B-1 _______________________________ Operating system version Nested directory limitation dependency, B-1 lifted, xxx overlay function, REF-28, New functions, xxxiii REF-432 newwin function, REF-415 overwrite function, REF-28, nice function, REF-416 REF-433 nl function, REF-417 nl_langinfo function, 10-12, P REF-418 _______________________________ nocrmode function, REF-81 passwd structure, REF-262, noecho function, REF-132 REF-264 NONE reentrancy, REF-102 pathconf function, REF-434 nonl function, REF-417 pause function, REF-437 noraw function, REF-470 pclose function, REF-438 nrand48 function, REF-424 using with popen function, ntohl socket routine, A-75 REF-446 ntohs socket routine, A-77 perror function, 4-7, REF-439 Index-12 pipe function, REF-131, printf function, REF-450 REF-155, REF-161, REF-441 printw function, REF-451 Pointers Process permanent files, 2-38 64-bit support, 1-60 Protocols popen function, REF-446 Internet, A-3 Portability concerns, 1-40 putc function, REF-453 arguments to mkdir, REF-378 putchar function, REF-454 _exit function, REF-148 putenv function, REF-455 gsignal function, REF-279 puts function, REF-457 longname function, REF-349 putw function, REF-458 memory deallocation, REF-48 putwc function, REF-459 mvcur function, 6-16 putwchar function, REF-460 mv[w]insstr functions, REF-413 Q______________________________ [no]nl functions, REF-417 qabs function, REF-461 radix conversion specifiers, qdiv function, REF-462 2-19 qsort function, REF-463 raise function, REF-466 Quotas setgid function, REF-502 affecting RTL, 5-1, 5-3, 5-7 setuid function, REF-516 socket routines, A-1 R specific _______________________________ list of, 1-53 to 1-56 raise function, 4-7, 4-14, ssignal function, REF-563 REF-326, REF-465 ttyname function, REF-680 rand function, REF-467 UNIX file specifications, random function, REF-468 1-25 raw function, REF-470 ambiguity of, 1-27 read function, REF-472 variable-length argument read socket routine, A-79 lists, 3-17 readdir function, REF-475 va_start_1 macro, REF-713 using with closedir function, vfork versus fork function, REF-60 REF-716 readdir_r function, REF-475 [w]clrattr functions, REF-63 Reader's comments, xxiii [w]insstr functions, REF-295 realloc function, 8-1, REF-478 [w]setattr functions, Record REF-498 access by Compaq C, 1-45 _POSIX_C_SOURCE macro, 1-30 I/O pow function, REF-448 Compaq C handling of, Predefined macro 1-46 ERR, 6-15 Record files Predefined variables and accessing in record mode, constants, 6-15 1-45 accessing in stream mode, 1-44 Index-13 Record Management Services Run-Time Library (RTL) (RMS) (cont'd) accessing files, 1-43 I/O, 1-38 to 1-48 file organization, 1-42 Compaq C handling of, in Compaq C programs, 1-39 1-43 to 1-48 overview of, 1-41 to 1-48 interpreting syntax, 1-23 record access introduction to, 1-1 to 1-73 in Compaq C, 1-45 linking against RTL object record formats, 1-42 libraries, 1-6, 1-13 stream access linking against RTL shareable in Compaq C, 1-44 image, 1-4 recv socket routine, A-81 linking options explained, recvfrom socket routine, A-84 1-4 to 1-22 recvmsg socket routine, A-87 portability concerns, 1-40 Reentrancy, 1-56, REF-102 preprocessor directives, AST, 1-56, REF-102 1-23 MULTITHREAD, 1-56, REF-102 specific portability concerns NONE, REF-102 Restrictions, 1-59 , 1-53 to 1-56 TOLERANT, 1-57, REF-102 stream I/O, 1-44 Reentrancy function decc$set_reentrancy, 1-57, S______________________________ REF-102 sbrk function, 8-1, REF-488 /REENTRANCY qualifier, 1-57 scanf function, REF-489 refresh function, REF-56, scanw function, REF-491 REF-480 Screen management remove function, REF-116, Curses REF-481 See Curses rename function, REF-482 scroll function, REF-493 rewind function, REF-484 scrollok function, REF-494 rewinddir function seed48 function, REF-495 using with readdir function, using with drand48 function, REF-476 REF-129 rindex function, REF-486 using with lcong48 function, rmdir function, REF-487 REF-329 RMS using with lrand48 function, file attributes, 2-6 Routines REF-350 socket, A-1 to A-151 using with mrand48 function, Run-Time Library (RTL) REF-396 as shared images, 1-3 seekdir function, REF-497 Curses functions and macros, select socket routine, A-90 6-1 send socket routine, A-94 Date/time functions, 11-1 header files, 1-23 Index-14 sendmsg socket routine, A-96 sigemptyset function, REF-529 sendto socket routine, A-99 sigfillset function, REF-531 setattr function, REF-498 sigismember function, REF-532 setattr macro, 6-3 siglongjmp function, REF-533 setbuf function, REF-499 sigmask function, REF-535 setenv function, REF-501 signal function, 4-10, 4-16, setgid function, REF-502 REF-278, REF-465, REF-536, sethostent socket routine, REF-563 A-102 Signal handler setitimer function, REF-504 calling interface, 4-11 using with ualarm function, Signal-handling functions, 4-7 REF-688 alarm, REF-11 setjmp function, 4-17, gsignal, REF-278 REF-346, REF-506, REF-708, kill, REF-326 REF-717 longjmp, REF-346 setlocale function, 10-6, OpenVMS exceptions, 4-14 REF-509 pause, REF-437 setnetent socket routine, program examples, 4-20 A-103 raise, REF-465 setprotoent socket routine, setjmp, REF-506 A-104 sigaction, REF-521 setservent socket routine, sigaddset, REF-525 A-106 sigblock, REF-527 setsockopt socket routine, sigdelset, REF-528 A-107 sigemptyset, REF-529 setstate function, REF-514 sigfillset, REF-531 using with initstate function sigismember, REF-532 , REF-292 siglongjmp, REF-533 setuid, REF-516 sigmask, REF-535 setvbuf function, REF-518 signal, REF-536 using with popen function, sigpause, REF-538 sigpending, REF-539 REF-446 sigprocmask, REF-540 Shareable image, 1-4 sigsetjmp, REF-543 Shared access, xxxii sigsetmask, REF-545 Shared image sigstack, REF-546 Compaq C RTL, 1-3 sigsuspend, REF-548 shutdown socket routine, A-110 sigvec, REF-550 sigaction function, REF-521 sleep, REF-554 sigaction structure, REF-522 ssignal, REF-563 sigaddset function, REF-525 UNIX signals, 4-8 sigblock function, 4-10, VAXC$ESTABLISH, REF-708 REF-527, REF-538 header file, 4-8 sigdelset function, REF-528 Index-15 Signals, 4-7 Socket routines (cont'd) sigpause function, REF-538 getservbyname, A-49 sigpending function, REF-539 getservbyport, A-51 sigprocmask function, REF-540 getservent, A-52 sigsetjmp function, REF-543 getsockname, A-53 sigsetmask function, 4-10, getsockopt, A-55 REF-545 herror, A-57 sigstack function, REF-546 hostalias, A-59 sigsuspend function, REF-548 hstrerror, A-58 sigvec function, 4-10, 4-16, htonl, A-60 REF-278, REF-465, REF-550 htons, A-62 sin function, REF-552 h_errno support routines, sinh function, REF-553 A-15 sleep function, REF-554 inet_addr, A-64 _SOCKADDR_LEN macro, 1-38 inet_lnaof, A-66 Socket routines inet_makeaddr, A-67 accept, A-19 inet_netof, A-68 auxiliary communication inet_network, A-69 routines, A-15 inet_ntoa, A-70 basic communication routines, introduction, A-1 A-14 ioctl, A-71 bind, A-22 listen, A-73 close, A-24 ntohl, A-75 communication support ntohs, A-77 routines, A-16 porting considerations, A-1 Compaq C structures, A-3 programming examples, A-119 connect, A-25 read, A-79 decc$get_sdc, A-28 recv, A-81 decc$socket_fd, A-115 recvfrom, A-84 endhostent, A-29 recvmsg, A-87 endnetent, A-30 select, A-90 endprotoent, A-31 send, A-94 endservent, A-32 sendmsg, A-96 gethostaddr, A-33 sendto, A-99 gethostbyaddr, A-34 sethostent, A-102 gethostbyname, A-36 setnetent, A-103 gethostent, A-38 setprotoent, A-104 gethostname, A-39 setservent, A-106 getnetbyaddr, A-40 setsockopt, A-107 getnetbyname, A-41 shutdown, A-110 getnetent, A-43 socket, A-112 getpeername, A-44 vaxc$get_sdc, A-116 getprotobyname, A-46 write, A-117 getprotobynumber, A-47 getprotoent, A-48 Index-16 socket socket routine, A-112 Standard I/O functions Specification delimiters (cont'd) OpenVMS and UNIX, 1-26 fprintf, REF-189 sprintf function, REF-555 fputc, REF-192 sqrt function, REF-557 fputs, REF-193 srand function, REF-558 fputwc, REF-194 srand48 function, REF-559 fputws, REF-196 using with drand48 function, fread, REF-197 REF-129 freopen, REF-200 using with lcong48 function, fscanf, REF-204 REF-329 fseek, REF-207 using with lrand48 function, ftell, REF-215 REF-350 fwrite, REF-229 using with mrand48 function, getc, REF-235 REF-396 getw, REF-272 srandom function, REF-560 getwc, REF-273 using with random function, mktemp, REF-382 REF-468 putc, REF-453 sscanf function, REF-561 putw, REF-458 ssignal function, 4-10, putwc, REF-459 REF-278, REF-465, REF-563 rewind, REF-484 Standard header file, 1-1 setbuf, REF-499 Standard I/O, 1-39 setvbuf, REF-518 file pointers, 2-7 sprintf, REF-555 introduction to, 2-1 sscanf, REF-561 program example, 2-42 tmpfile, REF-668 wide character, 2-43 tmpnam, REF-669 Standard I/O functions ungetc, REF-693 clearerr, REF-55 ungetwc, REF-694 delete, REF-116, REF-481 Standards dlclose, REF-124 listed, 1-29 dlerror, REF-125 standend function, REF-565 dlopen, REF-126 standout function, REF-566 dlsym, REF-128 stat function, REF-567 fclose, REF-154 stat structure fdopen, REF-161 using with ftw function, feof, REF-162 REF-219 ferror, REF-163 __STDC_VERSION__ macro, 1-30 fflush, REF-164 stderr, 2-38, REF-164, fgetc, REF-166 REF-200, REF-439, REF-443 fgetname, REF-167 stdin, 2-38, REF-200, REF-443, fgets, REF-171 REF-489 fgetwc, REF-173 header file, 2-38 fgetws, REF-175 fopen, REF-181 Index-17 stdout, 2-38, REF-200, String-handling functions REF-443, REF-450, REF-454, (cont'd) REF-457, REF-460 index, REF-289 stdscr window, 6-8 memchr, REF-371 strcasecmp function, REF-572 memcmp, REF-372 strcat function, REF-573 memcpy, REF-373 strchr function, REF-371, memmove, REF-374 REF-575 memset, REF-376 strcmp function, REF-372, program examples, 3-18 REF-577 rindex, REF-486 strcmpn function, 1-54 strcasecmp, REF-572 strcoll function, 10-16, strcat, REF-573 REF-578 strchr, REF-575 strcpy function, REF-373, strcmp, REF-577 REF-579 strcoll, REF-578 strcpyn function, 1-54 strcpy, REF-579 strcspn function, REF-580 strcspn, REF-580 strdup function, REF-581 strdup, REF-581 Stream strlen, REF-599 access by Compaq C, 1-44 strncasecmp, REF-600 files, 2-1 strncat, REF-601 strerror function, 4-7, strncmp, REF-602 REF-582 strncpy, REF-604 strfmon function, 10-12, strnlen, REF-606 REF-584 strpbrk, REF-607 strftime function, 10-12, strrchr, REF-616 REF-590 strsep, REF-617 using with tzset function, strspn, REF-619 REF-681 strtok, REF-624 String comparison functions strtol, REF-627 multipass collation, 10-16 strtoll, REF-629 wcscoll, REF-756 strtoq, REF-629 String-handling functions, strtoul, REF-631 3-16 to 3-18 strtoull, REF-633 atof, REF-21 strtouq, REF-633 atoi, REF-22 strxfrm, REF-635 atol, REF-22 swab, REF-642 atoll, REF-23 wcscat, REF-749 atoq, REF-23 wcschr, REF-752 basename, REF-24 wcscmp, REF-754 bcmp, REF-26 wcscoll, REF-756 bcopy, REF-27 wcscpy, REF-757 bzero, REF-35 wcscspn, REF-758 dirname, REF-121 wcslen, REF-771 ffs, REF-165 wcsncat, REF-772 wcsncmp, REF-775 Index-18 String-handling functions Subprocess (cont'd) (cont'd) program examples, 5-7 to wcsncpy, REF-777 5-17 wcspbrk, REF-779 sharing data with pipe, 5-7, wcsrchr, REF-781 REF-441 wcsspn, REF-787 synchronization with wait, wcstok, REF-793 5-7 wcstol, REF-797 Subprocess functions wcstoul, REF-801 decc$set_child_standard_ wcswcs, REF-804 streams, REF-96 wcsxfrm, REF-808 decc$validate_wchar, REF-109 strlen function, REF-599 decc$write_eof_to_mbx, strncasecmp function, REF-600 REF-111 strncat function, REF-601 execl, REF-139 strncmp function, REF-602 execle, REF-141 strncpy function, REF-604 execlp, REF-143 strnlen function, REF-606 execv, REF-144 strpbrk function, REF-607 execve, REF-145 strptime function, xxix, execvp, REF-147 10-12, REF-608 pipe, REF-441 strrchr function, REF-616 vfork, REF-716 strsep function, REF-617 wait, REF-730 strspn function, REF-619 subwin function, REF-640 strstr function, REF-620 swab function, REF-642 strtod function, 10-13, swprintf function, REF-643 REF-21, REF-622 swscanf function, REF-645 strtok function, REF-624 Synchronizing processes, 5-7 strtol function, REF-22, Syntax REF-23, REF-627 of Compaq C RTL functions, strtoll function, REF-629 1-23 strtoq function, REF-629 SYS$ERROR, 2-38 strtoul function, REF-631 SYS$I18N_LOCALE logical name, strtoull function, REF-633 10-5 strtouq function, REF-633 SYS$INPUT, 2-38 Structures SYS$LANG logical name, 10-7 use with socket routines, SYS$LC_ALL logical name, 10-7 A-3 SYS$OUTPUT, 2-38 strxfrm function, 10-16, SYS$WAKE, REF-11 REF-635 sysconf function, REF-647 Subprocess, 5-1 to 5-17 system function, REF-658 executing image System functions, 9-1 to 9-8 with exec functions, 5-4 asctime, REF-12 implementation of, 5-2 asctime_r, REF-12 introduction to, 5-1 assert, REF-15 atexit, REF-19 Index-19 System functions (cont'd) System functions (cont'd) bsearch, REF-31 vfprintf, REF-718 chdir, REF-49 vprintf, REF-723 chmod, REF-51 vsprintf, REF-729 chown, REF-53 wcstod, REF-791 clock, REF-57 wcstok, REF-793 ctermid, REF-83 writev, REF-836 ctime, REF-84 ctime_r, REF-84 T______________________________ cuserid, REF-86 tan function, REF-660 difftime, REF-120 tanh function, REF-661 fchown, REF-152 TCP/IP Services for OpenVMS, fmod, REF-180 A-1 ftime, REF-216 telldir function, REF-662 getcwd, REF-240 tempnam function, REF-663 getegid, REF-243 Terminal I/O getenv, REF-244 program examples, 2-39 to geteuid, REF-246 2-46 getgid, REF-248 Terminal I/O functions getpid, REF-260 getchar, REF-237 getppid, REF-261 gets, REF-266 getuid, REF-270 getwchar, REF-274 gmtime, REF-276 printf, REF-450 gmtime_r, REF-276 putchar, REF-454 introduction to, 9-5 puts, REF-457 localtime, REF-342 putwchar, REF-460 localtime_r, REF-342 scanf, REF-489 memset, REF-376 Time mkdir, REF-377 introduction to, 11-1 nice, REF-416 time function, REF-665 program examples, 9-5 Time functions, 11-1 to 11-9 qsort, REF-463 Time-related functions remove, REF-116, REF-481 asctime, REF-12 rename, REF-482 asctime_r, REF-12 setbuf, REF-499 clock, REF-57 setgid, REF-502 ctime, REF-84 setuid function, REF-516 ctime_r, REF-84 setvbuf, REF-518 decc$fix_time, REF-88 strtod, REF-622 difftime, REF-120 strtok, REF-624 ftime, REF-216 system, REF-658 getclock, REF-238 time, REF-665 getitimer, REF-249 times, REF-666 gettimeofday, REF-269 umask, REF-690 gmtime, REF-276 utime, REF-696 gmtime_r, REF-276 utimes, REF-700 Index-20 Time-related functions (cont'd) U______________________________ localtime_r, REF-342 ualarm function, REF-688 mktime, REF-383 umask function, REF-690 setitimer, REF-504 umask value, 5-5 strftime, REF-590 uname function, REF-692 strptime, REF-608 ungetc function, REF-693 time, REF-665 ungetwc function, REF-694 times, REF-666 UNIX tzset, REF-681 file specification conversion ualarm, REF-688 functions, 1-25 usleep, REF-705 file specifications, 1-25 to utime, REF-696 1-28 utimes, REF-700 alternate translation, wcsftime, REF-761 1-28 Time-zone cache, REF-687 compared to OpenVMS, 1-26 times function, REF-666 Run-Time Library, 1-25 timespec structure, REF-238 use with Compaq C RTL, 1-25 tmpfile function, REF-668 to 1-28 tmpnam function, REF-669 UNIX file specifications toascii function, 3-14, alternate translation, xxxii REF-670 UNIX I/O, 1-39 TOLERANT reentrancy, 1-57, file descriptors, 2-7 REF-102 functions _tolower macro, 3-14 program example, 2-45 _tolower function, REF-672 UNIX I/O functions tolower function, 3-14, close, REF-58 REF-671 creat, REF-72 touchwin function, REF-673 dup, REF-131 _toupper macro, 3-14 dup2, REF-131 _toupper function, REF-675 fcntl, REF-155 toupper function, 3-14, fileno, REF-178 REF-674 fstat, REF-210 towctrans function, 3-14, getname, REF-252 10-14, REF-676 getopt, REF-254 towlower function, 10-14, isapipe, REF-298 REF-677 isatty, REF-300 towupper function, 10-14, lseek, REF-352 REF-678 open, REF-426 truncate function, REF-679 read, REF-472 ttyname function, REF-680 stat, REF-567 tzset function, REF-681 ttyname, REF-680 write, REF-834 Index-21 unsetenv function, REF-704 usleep function, REF-705 W______________________________ utime function, REF-696 waddch function, REF-8 utimes function, REF-700 waddstr function, REF-10 wait function, REF-730 V______________________________ using with waitpid function, header file, 3-17 REF-742 Variable-length argument lists wait3 function, REF-732 , 3-17 wait4 function, REF-737 Variable-length record files waitpid function, REF-742 accessing in record mode, wclear function, REF-54 1-48 wclrattr function, 6-3, REF-63 VAXC$CRTL_INIT function, 4-16, wclrtobot function, REF-64 REF-690, REF-706 wclrtoeol function, REF-65 vaxc$errno external variable, wcrtomb function, 3-14, 10-15, 4-7 REF-747 VAXC$ESTABLISH function, 4-17, wcscat function, REF-749 REF-347, REF-507, REF-708 wcschr function, REF-752 VAXC$EXECMBX logical name, 5-5 wcscmp function, REF-754 vaxc$get_sdc socket routine, wcscoll function, 10-16, A-116 REF-756 va_arg function, REF-710 wcscpy function, REF-757 va_count function, REF-711 wcscspn function, REF-758 va_end function, REF-712 wcsftime function, 10-12, va_start macro, REF-713 REF-761 va_start_1 macro, REF-713 wcslen function, REF-771 Version-dependency of Compaq C wcsncat function, REF-772 RTL routines, B-1 wcsncmp function, REF-775 vfork function, REF-443, wcsncpy function, REF-777 REF-716 wcspbrk function, REF-779 vfprintf function, REF-718 wcsrchr function, REF-781 vfwprintf function, REF-719 wcsrtombs function, 3-14, VMS/ULTRIX Connection product 10-15, REF-784 wcsspn function, REF-787 See TCP/IP Services for wcsstr function, REF-790 OpenVMS wcstod function, 10-13, _VMS_CURSES macro, 1-38 REF-791 _VMS_V6_SOURCE macro, 1-36 wcstok function, REF-793 vprintf function, REF-723 wcstol function, REF-797 vsprintf function, REF-729 wcstombs function, 10-15, vswprintf function, REF-724 REF-799 vwprintf function, REF-727 wcstoul function, REF-801 wcswcs function, REF-804 Index-22 wcswidth function, REF-807 Wide-character functions wcsxfrm function, 10-16, (cont'd) REF-808 iswpunct, REF-319 wctob function, 10-15, REF-813 iswspace, REF-320 wctomb function, 10-15, iswupper, REF-321 REF-814 iswxdigit, REF-322 wctrans function, 3-14, 10-14, mbrlen, REF-358 REF-815 mbrtowc, REF-360 wctype function, REF-817 mbsinit, REF-366 wcwidth function, REF-822 mbsrtowcs, REF-367 wdelch function, REF-115 putwc, REF-459 wdeleteln function, REF-118 putwchar, REF-460 werase function, REF-138 swprintf, REF-643 wgetch function, REF-132, swscanf, REF-645 REF-236 towctrans, REF-676 wgetstr function, REF-132, towlower, REF-677 REF-268 towupper, REF-678 Wide character ungetwc, REF-694 collating functions, 10-16 vfwprintf, REF-719 conversion to multibyte, vswprintf, REF-724 10-15 vwprintf, REF-727 data type, 10-13 wcrtomb, REF-747 functions, 10-13 wcscat, REF-749 I/O functions, 10-14 wcschr, REF-752 Wide character I/O wcscmp, REF-754 program example, 2-43 wcscoll, REF-756 Wide-character functions wcscpy, REF-757 btowc, REF-34 wcscspn, REF-758 fgetwc, REF-173 wcsftime, REF-761 fgetws, REF-175 wcslen, REF-771 fputwc, REF-194 wcsncat, REF-772 fputws, REF-196 wcsncmp, REF-775 fwide, REF-223 wcsncpy, REF-777 fwprintf, REF-225 wcspbrk, REF-779 fwscanf, REF-231 wcsrchr, REF-781 getwc, REF-273 wcsrtombs, REF-784 getwchar, REF-274 wcsspn, REF-787 iswalnum, REF-309 wcsstr, REF-790 iswalpha, REF-310 wcstod, REF-791 iswcntrl, REF-311 wcstok, REF-793 iswctype, REF-312 wcstol, REF-797 iswdigit, REF-315 wcstoul, REF-801 iswgraph, REF-316 wcswcs, REF-804 iswlower, REF-317 wcswidth, REF-807 iswprint, REF-318 wcsxfrm, REF-808 wctob, REF-813 Index-23 Wide-character functions wmemset function, REF-829 (cont'd) wmove function, REF-393 wctrans, REF-815 wprintf function, REF-830 wctype, REF-817 wprintw function, REF-451 wcwidth, REF-822 wrapok function, REF-833 wmemchr, REF-823 wrefresh function, REF-480 wmemcmp, REF-825 write function, REF-834 wmemcpy, REF-826 write socket routine, A-117 wmemmove, REF-827 writev function, REF-836 wmemset, REF-829 wscanf function, REF-838 wprintf, REF-830 wscanw function, REF-491 wscanf, REF-838 wsetattr function, 6-3, Wide-character I/O, 2-9 REF-498 winch function, REF-288 wstandend function, REF-565 winsch function, REF-293 wstandout function, REF-566 winsertln function, REF-294 winsstr function, 6-3, REF-295 X______________________________ wmemchr function, REF-823 _XOPEN_SOURCE macro, 1-30 wmemcmp function, REF-825 _XOPEN_SOURCE_EXTENDEDXOPEN_ wmemcpy function, REF-826 SOURCE_EXTENDED, 1-30 wmemmove function, REF-827 Index-24