SC 415607
SC 415607
ERserver
iSeries
ILE C/C++
Run-Time Library Functions
Version 5
SC41-5607-02
ERserver
iSeries
ILE C/C++
Run-Time Library Functions
Version 5
SC41-5607-02
Note
Before using this information and the product it supports, be sure to read the information in
Appendix B, “Notices,” on page 533. Changes or additions to the text and illustrations are
indicated by a vertical line to the left of the change or addition.
Contents v
| vswscanf() — Read Formatted Wide Character wcwidth() — Determine the Display Width of a
| Data . . . . . . . . . . . . . . . . 420 Wide Character . . . . . . . . . . . . . 475
vwprintf() — Format Argument Data as Wide wfopen() —Open Files . . . . . . . . . . 476
Characters and Print . . . . . . . . . . . 422 wmemchr() —Locate Wide Character in
| vwscanf() — Read Formatted Wide Character Data 423 Wide-Character Buffer . . . . . . . . . . 476
wcrtomb() — Convert a Wide Character to a wmemcmp() —Compare Wide-Character Buffers 477
Multibyte Character (Restartable) . . . . . . . 425 wmemcpy() —Copy Wide-Character Buffer . . . 478
wcscat() — Concatenate Wide-Character Strings 430 wmemmove() — Copy Wide-Character Buffer . . 479
wcschr() — Search for Wide Character . . . . . 431 wmemset() — Set Wide Character Buffer to a Value 480
wcscmp() — Compare Wide-Character Strings . . 433 wprintf() — Format Data as Wide Characters and
wcscoll() —Language Collation String Comparison 434 Print . . . . . . . . . . . . . . . . 481
wcscpy() — Copy Wide-Character Strings . . . . 435 wscanf() — Read Data Using Wide-Character
wcscspn() — Find Offset of First Wide-Character Format String . . . . . . . . . . . . . 482
Match . . . . . . . . . . . . . . . . 436
wcsftime() — Convert to Formatted Date and Time 437 Chapter 3. Run-Time Considerations 485
__wcsicmp() — Compare Wide Character Strings errno Macros . . . . . . . . . . . . . 485
without Case Sensitivity . . . . . . . . . . 439 errno Values for Integrated File System Enabled C
wcslen() — Calculate Length of Wide-Character Stream I/O . . . . . . . . . . . . . . 487
String . . . . . . . . . . . . . . . . 440 Record Input and Output Error Macro to Exception
| wcslocaleconv() — Retrieve Wide Locale Mapping . . . . . . . . . . . . . . . 489
| Information . . . . . . . . . . . . . . 441 Signal Handling Action Definitions . . . . . . 490
wcsncat() — Concatenate Wide-Character Strings 442 Signal to iSeries Exception Mapping . . . . . 492
wcsncmp() — Compare Wide-Character Strings 443 Cancel Handler Reason Codes . . . . . . . . 493
wcsncpy() — Copy Wide-Character Strings . . . 445 Exception Classes . . . . . . . . . . . . 495
__wcsnicmp() — Compare Wide Character Strings Data Type Compatibility . . . . . . . . . 496
without Case Sensitivity . . . . . . . . . . 446 Run-time Character Set . . . . . . . . . . 503
wcspbrk() — Locate Wide Characters in String . . 447 Asynchronous Signal Model . . . . . . . 504
| wcsptime()— Convert Wide Character String to | Unicode Support . . . . . . . . . . . . 505
| Date/Time . . . . . . . . . . . . . . 448 | Reasons to Use Unicode Support . . . . . . 506
wcsrchr() — Locate Last Occurrence of Wide | Pseudo CCSID Neutrality . . . . . . . . 506
Character in String . . . . . . . . . . . 450 | Standard Files . . . . . . . . . . . . 507
wcsrtombs() — Convert Wide Character String to | Considerations . . . . . . . . . . . . 507
Multibyte String (Restartable) . . . . . . . . 451 | Default File CCSID . . . . . . . . . . 508
wcsspn() — Find Offset of First Non-matching | Newline Character . . . . . . . . . . 509
Wide Character . . . . . . . . . . . . . 453 | Conversion Errors . . . . . . . . . . . 509
wcsstr() — Locate Wide-Character Substring . . . 455
wcstod() — Convert Wide-Character String to
Double . . . . . . . . . . . . . . . 455 Part 2. Appendixes . . . . . . . . 511
wcstok() — Tokenize Wide-Character String . . . 457
wcstol() — wcstoll() — Convert Wide Character Appendix A. Library Functions and
String to Long and Long Long Integer . . . . . 458 Extensions . . . . . . . . . . . . 513
wcstombs() — Convert Wide-Character String to Standard C Library Functions Table, By Name . . 513
Multibyte String . . . . . . . . . . . . 460 ILE C Library Extensions to C Library Functions
wcstoul() — wcstoull() — Convert WideCharacter Table . . . . . . . . . . . . . . . . 529
String to Unsigned Long and Unsigned Long Long
Integer . . . . . . . . . . . . . . . 463
Appendix B. Notices . . . . . . . . 533
wcswcs() — Locate Wide-Character Substring . . 465
Programming Interface Information . . . . . . 534
wcswidth() — Determine the Display Width of a
Trademarks . . . . . . . . . . . . . . 535
Wide Character String . . . . . . . . . . 466
wcsxfrm() — Transform a Wide-Character String 467
wctob() — Convert Wide Character to Byte . . . 468 Bibliography . . . . . . . . . . . . 537
wctomb() — Convert Wide Character to Multibyte
Character . . . . . . . . . . . . . . . 469 Index . . . . . . . . . . . . . . . 539
wctrans() —Get Handle for Character Mapping 470
wctype() — Get Handle for Character Property
Classification . . . . . . . . . . . . . 472
Use this book as a reference when you write Integrated Language Environment
(ILE) C and C++ applications.
| This book does not describe how to program in the C or C++ programming
| languages, nor does it explain the concepts of ILE. Companion publications for this
| reference are:
| v C/C++ Legacy Class Libraries Reference, SC09-7652-01
| v ILE Concepts, SC41-5606-07
| v ILE C/C++ for AS/400 MI Library Reference, SC09-2418-00
| v Standard C/C++ Library Reference, SC09-4949-01
| v WebSphere Development Studio: ILE C/C++ Compiler Reference, SC09-4816-02
| v WebSphere Development Studio: ILE C/C++ Language Reference, SC09-7852-00
| v WebSphere Development Studio: ILE C/C++ Programmer’s Guide, SC09-2712-04
For other prerequisite and related information, see “Prerequisite and related
information” on page x and the “Bibliography” on page 537.
All complete runnable examples for library functions and machine interface
instructions are in library QCPPLE, in source file QACSRC. Each example name is
the same as the function name or instruction name. For example, the source code
for the example illustrating the use of the _Rcommit() function in this book is in
library QCPPLE, file QACSRC, member RCOMMIT. The QSYSINC library must be
installed.
| The iSeries Information Center contains new and updated iSeries information such
| as software and hardware installation, Linux, WebSphere, Java, high availability,
| database, logical partitions, CL commands, and system application programming
| interfaces (APIs). In addition, it provides advisors and finders to assist in planning,
| troubleshooting, and configuring your iSeries hardware and software.
With every new hardware order, you receive the iSeries Setup and Operations
CD-ROM, SK3T-4098-02. This CD-ROM contains IBM Eserver IBM e(logo)server
iSeries Access for Windows and the EZ-Setup wizard. iSeries Access Family offers
a powerful set of client and server capabilities for connecting PCs to iSeries
servers. The EZ-Setup wizard automates many of the iSeries setup tasks.
This section describes each include file, explains its contents, and lists the functions
that are declared in the file.
The QSYSINC (system openness includes) library must be installed on your iSeries
system. QSYSINC contains include files useful for C/C++ users, such as system
API, Dynamic Screen Manager (DSM), and LE header files. The QSYSINC library
contains header files that include the prototypes and templates for the MI built-ins
and the ILE C/C++ MI functions. See the ILE C/C++ for AS/400 MI Library Reference
for more information about these header files.
<assert.h>
The <assert.h> include file defines the assert macro. You must include assert.h
when you use assert.
<ctype.h>
The <ctype.h> include file defines functions that are used in character
classification. The functions that are defined in <ctype.h> are:
<decimal.h>
The <decimal.h> include file contains definitions of constants that specify the
ranges of the packed decimal type and its attributes. The <decimal.h> file must be
included with a #include directive in your source code if you use the keywords
decimal, digitsof, or precisionof.
Note: To test the value of errno after library function calls, set it to 0 before the
call because its value may not be reset during the call.
<except.h>
The <except.h> include file declares types and macros that are used in ILE C
exception handling.
<float.h>
The <float.h> include file defines constants that specify the ranges of
floating-point data types. For example, the maximum number of digits for objects
of type double or the minimum exponent for objects of type float.
<langinfo.h>
The <langinfo.h> include file contains the declarations and definitions that are
used by nl_langinfo.
<limits.h>
The <limits.h> include file defines constants that specify the ranges of integer and
character data types. For example, the maximum value for an object of type char.
<locale.h>
| The <locale.h> include file declares the setlocale(), localeconv(), and
| wcslocaleconv() library functions. These functions are useful for changing the C
| locale when you are creating applications for international markets.
The <locale.h> include file also declares the type struct lconv and the following
macro definitions:
|| NULL LC_ALL LC_C LC_C_FRANCE
| LC_C_GERMANY LC_C_ITALY LC_C_SPAIN LC_C_UK
| LC_C_USA LC_COLLATE LC_CTYPE LC_MESSAGES
| LC_MONETARY LC_NUMERIC LC_TIME LC_TOD
| LC_UCS2_ALL LC_UCS2_COLLATE LC_UCS2_CTYPE LC_UNI_ALL
| LC_UNI_COLLATE LC_UNI_CTYPE LC_UNI_TIME LC_UNI_NUMERIC
| LC_UNI_MESSAGES LC_UNI_MONITARY LC_UNI_TOD
|
<math.h>
The <math.h> include file declares all the floating-point math functions:
For all mathematical functions, a domain error occurs when an input argument is
outside the range of values that are allowed for that function. In the event of a
domain error, errno is set to the value of EDOM.
A range error occurs if the result of the function cannot be represented in a double
value. If the magnitude of the result is too large (overflow), the function returns
the positive or negative value of the macro HUGE_VAL, and sets errno to
ERANGE. If the result is too small (underflow), the function returns zero.
<mallocinfo.h>
Include file with _C_TS_malloc_info and _C_TS_malloc_debug.
<monetary.h>
| The <monetary.h> header file contains declarations and definitions that are related
| to the output of monetary quantities. The following monetary functions are
| defined: strfmon() and wcsfmon(). The strfmon() function is not available when
| LOCALETYPE(*CLD) is specified on the compilation command. The wcsfmon()
| function is available only when LOCALETYPE(*LOCALEUTF) is specified on the
| compilation command.
<nl_types.h>
| The <nl_types.h> header file contains catalog definitions and the following catalog
| functions: catclose(), catgets(), and catopen(). These definitions are not
| available when either LOCALETYPE(*CLD) or SYSIFCOPT(*NOIFSIO) is specified
| on the compilation command.
<pointer.h>
The <pointer.h> include file contains typedefs and pragma directives for the
iSeries™ pointer types: space pointer, open pointer, invocation pointer, label
pointer, system pointer, and suspend pointer. The typedefs _ANYPTR and
_SPCPTRCN are also defined in <pointer.h>.
<recio.h>
The <recio.h> include file defines the types and macros, and prototypes functions
for all the ILE C record input and output (I/O) operations.
__READ_NEXT __READ_PREV
Any of the record I/O functions that include a buffer parameter may work in
move mode or locate mode. In move mode, data is moved between the user
user-supplied buffer and the system buffer. In locate mode, the user must access
the data in the system buffer. Pointers to the system buffers are exposed in the
_RFILE structure. To specify that locate mode is being used, the buffer parameter
of the record I/O function is coded as NULL.
A number of the functions include a size parameter. For move mode, this is the
number of data bytes that are copied between the user-supplied buffer and the
system buffer. All of the record I/O functions work with one record at a time
regardless of the size that is specified. The size of this record is defined by the file
description. It may not be equal to the size parameter that is specified by the user
on the call to the record I/O functions. The amount of data that is moved between
buffers is equal to the record length of the current record format or specified
minimum size, whichever is smaller. The size parameter is ignored for locate
mode.
System−Specific Information
typedef struct {
void *sysparm_ext;
_Maj_Min_rc_T _Maj_Min;
char reserved1[12];
} _Sys_Struct_T;
<regex.h>
The <regex.h> include file defines the following regular expression functions:
The <regex.h> include file also declares the regmatch_t type, the regex_t type, which
is capable of storing a compiled regular expression, and the following macros:
REG_BASIC
REG_EXTENDED
REG_ICASE
REG_NEWLINE
REG_NOSUB
REG_NOTBOL
REG_NOTEOL
REG_NOMATCH
REG_BADPAT
REG_ECOLLATE
<setjmp.h>
The <setjmp.h> include file declares the setjmp() macro and longjmp function. It
also defines a buffer type, jmp_buf, that the setjmp() macro and longjmp function
use to save and restore the program state.
<signal.h>
The <signal.h> include file defines the values for signals and declares the
signal() and raise() functions.
<stdarg.h>
The <stdarg.h> include file defines macros that allow you access to arguments in
functions with variable-length argument lists: va_arg(), va_start(), and va_end().
The <stdarg.h> include file also defines the type va_list.
<stddef.h>
The <stddef.h> include file declares the commonly used pointers, variables, and
types as listed below:
ptrdiff_t
typedef for the type of the difference of two pointers
size_t typedef for the type of the value that is returned by sizeof
The <stddef.h> include file also defines the macros NULL and offsetof. NULL is a
pointer that is guaranteed not to point to a data object. The offsetof macro
expands to the number of bytes between a structure member and the start of the
structure. The offsetof macro has the form:
offsetof(structure_type, member)
The <stddef.h> include file also declares the extern variable _EXCP_MSGID, an
iSeries extension to C.
<stdio.h>
The <stdio.h> include file defines constants, macros, and types, and declares
stream input and output functions. The stream I/O functions are:
The <stdio.h> include file also defines the macros that are listed below. You can
use these constants in your programs, but you should not alter their values.
BUFSIZ Specifies the buffer size that the setbuf library function will use when you
are allocating buffers for stream I/O. This value establishes the size of
system-allocated buffers and is used with setbuf.
EOF The value that is returned by an I/O function when the end of the file (or
in some cases, an error) is found.
FOPEN_MAX
The number of files that can be opened simultaneously.
FILENAME_MAX
The longest file name that is supported. If there is no reasonable limit,
FILENAME_MAX will be the recommended size.
L_tmpnam
The size of the longest temporary name that can be generated by the
tmpnam function.
The FILE structure type is defined in <stdio.h>. Stream I/O functions use a
pointer to the FILE type to get access to a given stream. The system uses the
information in the FILE structure to maintain the stream.
The C standard streams stdin, stdout, and stderr are also defined in <stdio.h>.
The macros _IOFBF, _IOLBF, and _IONBF expand to integral constant expressions
with distinct values suitable for use as the third argument to the setvbuf function.
The type fpos_t is defined in <stdio.h> for use with fgetpos() and fsetpos().
<stdlib.h>
The <stdlib.h> include file declares the following functions:
1
Note: These functions are applicable to C++ only.
The <stdlib.h> include file also contains definitions for the following macros:
NULL The NULL pointer value.
EXIT_SUCCESS
Expands to 0; used by the atexit function.
EXIT_FAILURE
Expands to 8; used by the atexit function.
RAND_MAX
Expands to an integer that represents the largest number that the rand
function can return.
MB_CUR_MAX
Expands to an integral expression to represent the maximum number of
bytes in a multibyte character for the current locale.
<string.h>
The <string.h> include file declares the string manipulation functions:
The <string.h> include file also defines the macro NULL, and the type size_t.
For more information on NULL and the type size_t, see “<stddef.h>” on page 13.
<strings.h>
Contains the functions strcasecmp and strncasecmp
<time.h>
The <time.h> include file declares the time and date functions:
For more information on NULL and the type size_t, see “<stddef.h>” on page 13.
<wcstr.h>
The<wcstr.h> include file declares the multibyte functions:
For more information on NULL and the types size_t and wchar_t, see “<stddef.h>”
on page 13.
<wctype.h>
| The <wctype.h> header file declares the following wide character functions:
|| iswalnum iswgraph iswspace towlower wctrans
| iswalpha iswlower iswupper towupper
| iswcntrl iswprint iswxdigit towctrans
| iswdigit iswpunct iswctype wctype
|
| The <wctype.h> header file also contains declarations and definitions for wide
| character classification. These declarations and definitions are not available when
| LOCALETYPE(*CLD) is specified on the compilation command.
<xxdtaa.h>
The <xxdtaa.h> include file contains the declarations for the data area interface
functions QXXCHGDA, QXXRTVDA, and the type _DTAA_NAME_T.
<xxenv.h>
The <xxenv.h> include file contains the declarations for the QPXXCALL and QPXXDLTE
EPM environment handling program. ILE procedures cannot be called from this
interface.
<xxfdbk.h>
The <xxfdbk.h> include file contains the declarations that are used by the OS/400®
system feedback areas. To retrieve information from feedback areas, see “_Riofbk()
—Obtain I/O Feedback Information” on page 266 and “_Ropnfbk() — Obtain
Open Feedback Information” on page 275.
Examples throughout the section illustrate the use of library functions and are not
necessarily complete.
This chapter lists the library functions in alphabetic order. If you are unsure of the
function you want to use, see the summary of the library functions in “The C/C++
Library.”
Error Handling
Function Header File Page Description
assert() assert.h 45 Prints diagnostic messages.
atexit() stdlib.h 48 Registers a function to be
executed at program end.
clearerr() stdio.h 64 Resets error indicators.
feof() stdio.h 86 Tests end-of-file indicator
for stream input.
ferror() stdio.h 87 Tests the error indicator for
a specified stream.
Mathematical
Function Header File Page Description
abs() stdlib.h 39 Calculates the absolute value of an
integer.
ceil() math.h 63 Calculates the double value
representing the smallest integer
that is greater than or equal to a
number.
div() stdlib.h 77 Calculates the quotient and
remainder of an integer.
erf() math.h 79 Calculates the error function.
erfc() math.h 79 Calculates the error function for
large numbers.
exp() math.h 81 Calculates an exponential function.
fabs() math.h 81 Calculates the absolute value of a
floating-point number.
floor() math.h 99 Calculates the double value
representing the largest integer that
is less than or equal to a number.
fmod() math.h 99 Calculates the floating point
remainder of one argument
divided by another.
Trigonometric Functions
Bessel Functions
Time Manipulation
Function Header File Page Description
asctime() time.h 41 Converts time stored as a structure
to a character string in storage.
asctime_r() time.h 43 Converts time stored as a structure
to a character string in storage.
(Restartable version of asctime())
clock() time.h 65 Determines processor time.
ctime() time.h 68 Converts time stored as a long
value to a character string.
ctime_r() time.h 69 Converts time stored as a long
value to a character string.
(Restartable version of ctime())
difftime() time.h 76 Calculates the difference between
two times.
gmtime() time.h 151 Converts time to Coordinated
Universal Time structure.
gmtime_r() time.h 153 Converts time to Coordinated
Universal Time structure.
(Restartable version of gmtime())
localtime() time.h 173 Converts time to local time.
localtime_r() time.h 174 Converts time to local time.
(Restartable version of localtime())
mktime() time.h 204 Converts local time into calendar
time.
time() time.h 391 Returns the time in seconds.
Type Conversion
Function Header File Page Description
atof() stdlib.h 49 Converts a character string to a
floating-point value.
atoi() stdlib.h 50 Converts a character string to an
integer.
atol() stdlib.h 51 Converts a character string to a
long integer.
Conversion
Function Header File Page Description
QXXDTOP() xxcvt.h 231 Converts a floating-point value to a
packed decimal value.
QXXDTOZ() xxcvt.h 232 Converts a floating-point value to a
zoned decimal value.
QXXITOP() xxcvt.h 233 Converts an integer value to a
packed decimal value.
QXXITOZ() xxcvt.h 233 Converts an integer value to a
zoned decimal value.
QXXPTOD() xxcvt.h 234 Converts a packed decimal value
to a floating-point value.
QXXPTOI() xxcvt.h 235 Converts a packed decimal value
to an integer value.
Record Input/Output
Function Header File Page Description
_Racquire() recio.h 240 Prepares a device for record I/O
operations.
_Rclose() recio.h 241 Closes a file that is opened for
record I/O operations.
_Rcommit() recio.h 243 Completes the current transaction,
and establishes a new commitment
boundary.
_Rdelete() recio.h 244 Deletes the currently locked record.
_Rdevatr() recio.h 246 Returns a pointer to a copy of the
xxfdbk.h device attributes feedback area for
the file reference by fp and the
device pgmdev.
_Rfeod() recio.h 260 Forces an end-of-file condition for
the file referenced by fp.
_Rfeov() recio.h 261 Forces an end-of-volume condition
for tapes.
_Rformat() recio.h 262 Sets the record format to fmt for the
file referenced by fp.
_Rindara() recio.h 264 Sets up the separate indicator area
to be used for subsequent record
I/O operations.
_Riofbk() recio.h 266 Returns a pointer to a copy of the
xxfdbk.h I/O feedback area for the file
referenced by fp.
_Rlocate() recio.h 268 Positions to the record in the files
associated with fp and specified by
the key, klen_rrn and opt
parameters.
_Ropen() recio.h 271 Opens a file for record I/O
operations.
_Ropnfbk() recio.h 275 Returns a pointer to a copy of the
xxfdbk.h open feedback area for the file
referenced by fp.
_Rpgmdev() recio.h 276 Sets the default program device.
_Rreadd() recio.h 277 Reads a record by relative record
number.
_Rreadf() recio.h 279 Reads the first record.
_Rreadindv() recio.h 281 Reads data from an invited device.
_Rreadk() recio.h 284 Reads a record by key.
_Rreadl() recio.h 288 Reads the last record.
Stream Input/Output
Formatted Input/Output
|| Function Header File Page Description
| fprintf() stdio.h 108 Formats and prints
| characters to the
| output stream.
| fscanf() stdio.h 123 Reads data from a
| stream into
| locations given by
| arguments.
| fwprintf() stdio.h 133 Formats data as
| wide characters,
| and writes to a
| stream.
| fwscanf() stdio.h 137 Reads wide data
| from stream into
| locations given by
| arguments.
| printf() stdio.h 211 Formats and prints
| characters to
| stdout.
File Positioning
File Access
Pseudorandom Numbers
Function Header File Page Description
rand(), rand_r() stdlib.h 239 Returns a pseudorandom integer.
(rand_r() is the restartable version
of rand().)
srand() stdlib.h 338 Sets the starting point for
pseudorandom numbers.
Environment Interaction
Function Header File Page Description
abort() stdlib.h 38 Ends a program
abnormally.
_C_Get_Ssn_Handle() stdio.h 57 Returns a handle to the
C session for use with
DSM APIs.
exit() stdlib.h 80 Ends the program
normally if called in the
initial thread.
getenv() stdlib.h 144 Searches environment
variables for a specified
variable.
localeconv() locale.h 168 Formats numeric
quantities in struct lconv
according to the current
locale.
longjmp() setjmp.h 178 Restores a stack
environment.
nl_langinfo() langinfo.h 206 Retrieves information
from the current locale.
putenv() stdlib.h 223 Sets the value of an
environment variable by
altering an existing
variable or creating a
new one.
setjmp() setjmp.h 321 Saves a stack
environment.
String Operations
Function Header File Page Description
strcasecmp() strings.h 340 Compares strings without case
sensitivity.
strcat() string.h 341 Concatenates two strings.
strchr() string.h 342 Locates the first occurrence of a
specified character in a string.
strcmp() string.h 343 Compares the value of two strings.
| strcmpi() string.h 345 Compares the value of two strings
| without regard to case.
strcoll() string.h 346 Compares the locale-defined value
of two strings.
strcpy() string.h 347 Copies one string into another.
strcspn() string.h 348 Finds the length of the first
substring in a string of characters
not in a second string.
| strdup() string.h 350 Duplicates a string.
strfmon() string.h 351 Converts monetary value to string.
strftime() time.h 354 Converts date and time to a
formatted string.
| stricmp() string.h 357 Compares the value of two strings
| without regard to case.
strlen() string.h 358 Calculates the length of a string.
strncasecmp() strings.h 359 Compares strings without case
sensitivity.
strncat() string.h 361 Adds a specified length of one
string to another string.
strncmp() string.h 362 Compares two strings up to a
specified length.
strncpy() string.h 364 Copies a specified length of one
string into another.
| strnicmp() string.h 365 Compares the value of two
| substrings without regard to case.
| strnset() string.h 366 Sets character in a string.
strpbrk() string.h 367 Locates specified characters in a
string.
Character Testing
Function Header File Page Description
isalnum() ctype.h 156 Tests for alphanumeric characters.
isalpha() ctype.h 156 Tests for alphabetic characters.
isascii() ctype.h 158 Tests for ASCII values.
| isblank() ctype.h 159 Tests for blank or tab characters.
iscntrl() ctype.h 156 Tests for control characters.
isdigit() ctype.h 156 Tests for decimal digits.
isgraph() ctype.h 156 Tests for printable characters
excluding the space.
islower() ctype.h 156 Tests for lowercase letters.
isprint() ctype.h 156 Tests for printable characters
including the space.
| ispunct() ctype.h 156 Tests for punctuation characters as
| defined in the locale.
isspace() ctype.h 156 Tests for white-space characters.
isupper() ctype.h 156 Tests for uppercase letters.
isxdigit() ctype.h 156 Tests for wide hexadecimal digits 0
through 9, a through f, or A
through F.
Data Areas
Function Header File Page Description
QXXCHGDA() xxdtaa.h 230 Changes the data area.
QXXRTVDA() xxdtaa.h 236 Retrieves a copy of the data area
specified by dtname.
Message Catalogs
Function Header File Page Description
catclose() nl_types.h 59 Closes a message catalog.
catgets() nl_types.h 60 Reads a message from an opened
message catalog.
catopen() nl_types.h 61 Opens a message catalog.
Regular Expression
Function Header File Page Description
regcomp() regex.h 250 Compiles a regular expression.
regerror() regex.h 252 Returns error message for regular
expression.
regexec() regex.h 253 Executes a compiled regular
expression.
regfree() regex.h 256 Frees memory for regular
expression.
Description
The abort() function causes an abnormal end of the program and returns control
to the host environment. Like the exit() function, the abort() function deletes
buffers and closes open files before ending the program.
Calls to the abort() function raise the SIGABRT signal. The abort() function will
not result in the ending of the program if SIGABRT is caught by a signal handler,
and the signal handler does not return.
Return Value
This example tests for successful opening of the file myfile. If an error occurs, an
error message is printed, and the program ends with a call to the abort() function.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *stream;
Related Information
v “exit() — End Program” on page 80
v “signal() — Handle Interrupt Signals” on page 330
v “<stdlib.h>” on page 15
v See the signal() API in the APIs topic in the iSeries Information Center.
| Threadsafe: Yes.
Description
There is no error return value. The result is undefined when the absolute value of
the argument cannot be represented as an integer. The value of the minimum
allowable integer is defined by INT_MIN in the <limits.h> include file.
int main(void)
{
int x = -4, y;
y = abs(x);
Related Information
v “fabs() — Calculate Floating-Point Absolute Value” on page 81
v “labs() — llabs() — Calculate Absolute Value of Long and Long Long Integer”
on page 164
v “<limits.h>” on page 7
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The acos() function calculates the arccosine of x, expressed in radians, in the range
0 toΠ.
Return Value
The acos() function returns the arccosine of x. The value of x must be between -1
and 1 inclusive. If x is less than -1 or greater than 1, acos() sets errno to EDOM
and returns 0.
This example prompts for a value for x. It prints an error message if x is greater
than 1 or less than -1; otherwise, it assigns the arccosine of x to y.
int main(void)
{
double x, y;
Enter x
acos( 0.400000 ) = 1.159279
*/
Related Information
v “asin() — Calculate Arcsine” on page 44
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Description
The asctime() function uses a 24-hour-clock format. The days are abbreviated to:
Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb,
Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have constant
width. Dates with only one digit are preceded either with a zero or a blank space.
The new-line character (\n) and the null character (\0) occupy the last two
positions of the string.
The time and date functions begin at 00:00:00 Universal Time, January 1, 1970.
Return Value
The asctime() function returns a pointer to the resulting character string. If the
function is unsuccessful, it returns NULL.
Note: The asctime(), ctime() functions, and other time functions may use a
common, statically allocated buffer to hold the return string. Each call to one
of these functions may destroy the result of the previous call. The
asctime_r(), ctime_r(), gmtime_r(), and localtime_r()functions do not use
a common, statically-allocated buffer to hold the return string. These
functions can be used in the place of the asctime(), ctime(), gmtime(), and
localtime() functions if reentrancy is desired.
This example polls the system clock and prints a message that gives the current
time.
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm *newtime;
time_t ltime;
Related Information
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
Threadsafe: Yes.
Description
The string result that asctime_r() produces contains exactly 26 characters and has
the format:
"%.3s %.3s%3d %.2d:%.2d:%.2d %d\n"
The asctime_r() function uses a 24-hour-clock format. The days are abbreviated to:
Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb,
Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have constant
width. Dates with only one digit are preceded either with a zero or a blank space.
The new-line character (\n) and the null character (\0) occupy the last two
positions of the string.
The time and date functions begin at 00:00:00 Universal Time, January 1, 1970.
Return Value
The asctime_r() function returns a pointer to the resulting character string. If the
function is unsuccessful, it returns NULL.
This example polls the system clock and prints a message giving the current time.
#include <time.h>
#include <stdio.h>
int main(void)
{
struct tm *newtime;
time_t ltime;
char mybuf[50];
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “mktime() — Convert Local Time” on page 204
v “strftime() — Convert Date/Time to String” on page 354
v “time() — Determine Current Time” on page 391
v “printf() — Print Formatted Characters” on page 211
v “<time.h>” on page 16
Threadsafe: Yes.
Description
The asin() function calculates the arcsine of x, in the range -π/2 to π/2 radians.
Return Value
This example prompts for a value for x. It prints an error message if x is greater
than 1 or less than -1; otherwise, it assigns the arcsine of x to y.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
double x, y;
Related Information
v “acos() — Calculate Arccosine” on page 40
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Description
The assert() function prints a diagnostic message to stderr and aborts the
program if expression is false (zero). The diagnostic message has the format:
Assertion failed: expression, file filename, line line-number.
Use the assert() function to identify program logic errors. Choose an expression
that holds true only if the program is operating as you intend. After you have
debugged the program, you can use the special no-debug identifier NDEBUG to
remove the assert() calls from the program. If you define NDEBUG to any value
with a #define directive, the C preprocessor expands all assert calls to void
expressions. If you use NDEBUG, you must define it before you include <assert.h>
in the program.
Return Value
Note: The assert() function is defined as a macro. Do not use the #undef
directive with assert().
In this example, the assert() function tests string for a null string and an empty
string, and verifies that length is positive before processing these arguments.
#include <stdio.h>
#include <assert.h>
int main(void)
{
char *string = "ABC";
int length = 3;
analyze(string, length);
printf("The string %s is not null or empty, "
"and has length %d \n", string, length);
}
Related Information
v “abort() — Stop a Program” on page 38
v “<assert.h>” on page 3
Threadsafe: Yes.
Description
The atan() and atan2() functions calculate the arctangent of x and y/x,
respectively.
Return Value
The atan() function returns a value in the range -π/2 to π/2 radians. The atan2()
function returns a value in the range -π to π radians. If both arguments of the
atan2() function are zero, the function sets errno to EDOM, and returns a value of
0.
This example calculates arctangents using the atan() and atan2() functions.
#include <math.h>
#include <stdio.h>
int main(void)
{
double a,b,c,d;
c = 0.45;
d = 0.23;
a = atan(c);
b = atan2(c,d);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “asin() — Calculate Arcsine” on page 44
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
Threadsafe: Yes.
Description
The atexit() function records the function, pointed to by func, that the system
calls at normal program end. For portability, you should use the atexit() function
to register a maximum of 32 functions. The functions are processed in a last-in,
first-out order. The atexit() function cannot be called from the OPM default
activation group. Most functions can be used with the atexit function; however, if
the exit function is used the atexit function will fail.
Return Value
This example uses the atexit() function to call goodbye() at program end.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
void goodbye(void);
int rc;
rc = atexit(goodbye);
if (rc != 0)
perror("Error in atexit");
exit(0);
}
void goodbye(void)
/* This function is called at normal program end */
{
printf("The function goodbye was called at program end\n");
}
Related Information
v “exit() — End Program” on page 80
v “signal() — Handle Interrupt Signals” on page 330
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
digits
whitespace + . digits
– . digits
e digits
E +
–
The white space consists of the same characters for which the isspace()function is
true, such as spaces and tabs. The atof() function ignores leading white-space
characters.
For the atof() function, digits is one or more decimal digits; if no digits appear
before the decimal point, at least one digit must appear after the decimal point.
The decimal digits can precede an exponent, introduced by the letter e or E. The
exponent is a decimal integer, which may be signed.
The atof() function will not fail if a character other than a digit follows an E or if
e is read in as an exponent. For example, 100elf will be converted to the
floating-point value 100.0. The accuracy is up to 17 significant character digits.
Return Value
| The atof() function returns a double value that is produced by interpreting the
| input characters as a number. The return value is 0 if the function cannot convert
| the input to a value of that type. In case of overflow, the function sets errno to
| ERANGE and returns the value -HUGE_VAL or +HUGE_VAL.
This example shows how to convert numbers that are stored as strings to numeric
values.
int main(void)
{
double x;
char *s;
s = " -2309.12E-15";
x = atof(s); /* x = -2309.12E-15 */
printf("x = %.4e\n",x);
}
x = -2.3091e-12
*/
Related Information
v “atoi() — Convert Character String to Integer”
v “atol() — atoll() — Convert Character String to Long or Long Long Integer” on
page 51
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “strtod() — Convert Character String to Double” on page 376
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The atoi() function converts a character string to an integer value. The input
string is a sequence of characters that can be interpreted as a numeric value of the
specified return type. The function stops reading the input string at the first
character that it cannot recognize as part of a number. This character can be the
null character that ends the string.
The atoi() function does not recognize decimal points or exponents. The string
argument for this function has the form:
digits
whitespace +
-
where whitespace consists of the same characters for which the isspace() function
is true, such as spaces and tabs. The atoi()function ignores leading white-space
characters. The value digits represents one or more decimal digits.
The atoi() function returns an int value that is produced by interpreting the input
characters as a number. The return value is 0 if the function cannot convert the
input to a value of that type. The return value is undefined in the case of an
overflow.
This example shows how to convert numbers that are stored as strings to numeric
values.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i;
char *s;
s = " -9885";
i = atoi(s); /* i = -9885 */
printf("i = %d\n",i);
}
i = -9885
*/
Related Information
v “atof() — Convert Character String to Float” on page 49
v “atol() — atoll() — Convert Character String to Long or Long Long Integer”
v “strtod() — Convert Character String to Double” on page 376
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “<stdlib.h>” on page 15
Format (atoll())
#include <stdlib.h>
long long int atoll(const char *string);
Threadsafe: Yes.
Description
The atol() function converts a character string to a long value. The atoll()
function converts a character string to a long long value.
The atol() and atoll() functions do not recognize decimal points or exponents.
The string argument for this function has the form:
digits
whitespace +
-
where whitespace consists of the same characters for which the isspace() function
is true, such as spaces and tabs. The atol() and atoll() functions ignore leading
white-space characters. The value digits represents one or more decimal digits.
Return Value
The atol() and atoll()functions return a long or a long long value that is
produced by interpreting the input characters as a number. The return value is 0L
if the function cannot convert the input to a value of that type. The return value is
undefined in case of overflow.
This example shows how to convert numbers that are stored as strings to numeric
values.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
long l;
char *s;
s = "98854 dollars";
l = atol(s); /* l = 98854 */
printf("l = %.ld\n",l);
}
l = 98854
*/
Related Information
v “atof() — Convert Character String to Float” on page 49
v “atoi() — Convert Character String to Integer” on page 50
v “strtod() — Convert Character String to Double” on page 376
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “<stdlib.h>” on page 15
Bessel Functions
Format
52 ILE C/C++ Run-Time Library Functions V5R3
#include <math.h>
double j0(double x);
double j1(double x);
double jn(int n, double x);
double y0(double x);
double y1(double x);
double yn(int n, double x);
Threadsafe: Yes.
Description
Bessel functions solve certain types of differential equations. The j0(), j1(), and
jn() functions are Bessel functions of the first kind for orders 0, 1, and n,
respectively. The y0(), y1(), and yn() functions are Bessel functions of the second
kind for orders 0, 1, and n, respectively.
The argument x must be positive. The argument n should be greater than or equal
to zero. If n is less than zero, it will be a negative exponent.
Return Value
For j0(), j1(), y0(), or y1(), if the absolute value of x is too large, the function
sets errno to ERANGE, and returns 0. For y0(), y1(), or yn(), if x is negative, the
function sets errno to EDOM and returns the value -HUGE_VAL. For y0, y1(), or
yn(), if x causes overflow, the function sets errno to ERANGE and returns the
value -HUGE_VAL.
This example computes y to be the order 0 Bessel function of the first kind for x. It
also computes z to be the order 3 Bessel function of the second kind for x.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y, z;
x = 4.27;
y = -0.366022
z = -0.087482
*********************************************************************/
Related Information
v “erf() – erfc() — Calculate Error Functions” on page 79
v “gamma() — Gamma Function” on page 140
Threadsafe: Yes.
Description
The bsearch() function performs a binary search of an array of num elements, each
of size bytes. The array must be sorted in ascending order by the function pointed
to by compare. The base is a pointer to the base of the array to search, and key is the
value being sought.
The compare argument is a pointer to a function you must supply that compares
two items and returns a value specifying their relationship. The first item in the
argument list of the compare() function is the pointer to the value of the item that
is being searched for. The second item in the argument list of the compare()
function is a pointer to the array element being compared with the key. The
compare() function must compare the key value with the array element and then
return one of the following values:
Value Meaning
Less than 0 key less than element
0 key identical to element
Greater than 0 key greater than element
Return Value
The bsearch() function returns a pointer to key in the array to which base points. If
two keys are equal, the element that key will point to is unspecified. If the
bsearch() function cannot find the key, it returns NULL.
This example performs a binary search on the argv array of pointers to the
program parameters and finds the position of the argument PATH. It first removes
the program name from argv, and then sorts the array alphabetically before calling
bsearch(). The compare1() and compare2() functions compare the values pointed
to by arg1 and arg2 and return the result to the bsearch() function.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
result = <PATH>
*/
Related Information
v “qsort() — Sort Array” on page 228
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
| The behavior of the btowc() function is affected by the LC_CTYPE category of the
| current locale. This function is not available when LOCALETYPE(*CLD) is
| specified on the compilation command.
Return Value
The btowc() function returns WEOF if c has the value EOF, or if (unsigned char) c
does not constitute a valid (one-byte) multibyte character in the initial shift state.
Otherwise, it returns the wide-character representation of that character.
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbtowc() — Convert Multibyte Character to a Wide Character” on page 196
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “setlocale() — Set Locale” on page 322
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
Returns a handle to the C session for use with Dynamic Screen Manager (DSM)
APIs.
Return Value
Threadsafe: Yes.
Description
Return Value
The calloc() function returns a pointer to the reserved space. The storage space to
which the return value points is suitably aligned for storage of any type of object.
To get a pointer to a type, use a type cast on the return value. The return value is
NULL if there is not enough storage, or if num or size is 0.
Note: To use Teraspace storage instead of heap storage without changing the C
source code, specify the TERASPACE(*YES *TSIFC) parameter on the
compiler command. This maps the calloc() library function to
_C_TS_calloc(), its Teraspace storage counterpart. The maximum amount of
Teraspace storage that can be allocated by each call to _C_TS_calloc() is
2GB - 224, or 2147483424 bytes.
For more information about Teraspace, see the ILE Concepts manual.
This example prompts for the number of array entries required, and then reserves
enough space in storage for the entries. If calloc() is successful, the example
prints out each entry; otherwise, it prints out an error.
int main(void)
{
long * array; /* start of the array
*/
long * index; /* index variable
*/
int i; /* index variable
*/
int num; /* number of entries of the array
*/
Related Information
v “free() — Release Storage Blocks” on page 118
v “malloc() — Reserve Storage Block” on page 180
v “realloc() — Change Reserved Storage Block Size” on page 247
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The catclose() function closes the previously opened message catalog that is
identified by catd.
Return Value
#include <stdio.h>
#include <nl_types.h>
#include <locale.h>
int main(void) {
nl_catd msg_file;
char * my_msg;
char * my_locale;
setlocale(LC_ALL, NULL);
msg_file = catopen("/qsys.lib/mylib.lib/msgs.usrspc", 0);
if (msg_file != CATD_ERR) {
printf("%s\n", my_msg);
catclose(msg_file);
}
}
Related Information
v “catopen() — Open Message Catalog” on page 61
v “catgets() — Retrieve a Message from a Message Catalog”
Threadsafe: Yes.
Description
Return Value
#include <stdio.h>
#include <nl_types.h>
#include <locale.h>
int main(void) {
nl_catd msg_file;
char * my_msg;
char * my_locale;
setlocale(LC_ALL, NULL);
msg_file = catopen("/qsys.lib/mylib.lib/msgs.usrspc", 0);
if (msg_file != CATD_ERR) {
printf("%s\n", my_msg);
catclose(msg_file);
}
}
Related Information
v “catclose() — Close Message Catalog” on page 59
v “catopen() — Open Message Catalog”
Threadsafe: Yes.
Description
The catopen() function opens a message catalog, which must be done before a
message can be retrieved. The NLSPATH environment variable and the
LC_MESSAGES category are used to find the specified message catalog if no slash
(/) characters are found in the name. If the name contains one or more slash (/)
characters, then the name is interpreted as a path name of the catalog to open.
The message catalog descriptor will remain valid until it is closed by a call to
catclose(). If the LC_MESSAGES locale category is changed, it may invalidate
existing open message catalogs.
Return Value
The catopen() function might fail under the following conditions, and the value of
errno may be set to:
EACCES
Insufficient authority to read the message catalog specified, or to search the
component of the path prefix of the message catalog specified.
| ECONVERT
| A conversion error occurred.
EMFILE
NL_MAXOPEN message catalogs are currently open.
ENAMETOOLONG
The length of the path name of the message catalog exceeds PATH_MAX,
or a path name component is longer than NAME_MAX.
ENFILE
Too many files are currently open in the system.
ENOENT
The message catalog does not exist, or the name argument points to an
empty string.
#include <stdio.h>
#include <nl_types.h>
#include <locale.h>
int main(void) {
nl_catd msg_file;
char * my_msg;
char * my_locale;
setlocale(LC_ALL, NULL);
msg_file = catopen("/qsys.lib/mylib.lib/msgs.usrspc", 0);
if (msg_file != CATD_ERR) {
printf("%s\n", my_msg);
catclose(msg_file);
}
}
Related Information
v “catclose() — Close Message Catalog” on page 59
v “catgets() — Retrieve a Message from a Message Catalog” on page 60
Threadsafe: Yes.
Description
The ceil() function computes the smallest integer that is greater than or equal to
x.
Return Value
This example sets y to the smallest integer greater than 1.05, and then to the
smallest integer greater than -1.05. The results are 2.0 and -1.0, respectively.
int main(void)
{
double y, z;
y = ceil(1.05); /* y = 2.0 */
z = ceil(-1.05); /* z = -1.0 */
y = 2.00 ; z = -1.00
**********************************************************************/
Related Information
v “floor() —Find Integer <=Argument” on page 99
v “fmod() — Calculate Floating-Point Remainder” on page 99
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The clearerr() function resets the error indicator and end-of-file indicator for the
specified stream. Once set, the indicators for a specified stream remain set until
your program calls the clearerr() function or the rewind() function. The fseek()
function also clears the end-of-file indicator. The ILE C/C++ run-time environment
does not automatically clear error or end of file indicators.
Return Value
This example reads a data stream, and then checks that a read error has not
occurred.
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
int c;
int main(void)
{
if ((stream = fopen("mylib/myfile", "r")) != NULL)
{
if ((c=getc(stream)) == EOF)
{
if (ferror(stream))
{
perror("Read error");
clearerr(stream);
}
}
}
else
exit(0);
}
Related Information
v “feof() — Test End-of-File Indicator” on page 86
v “ferror() — Test for Read/Write Errors” on page 87
v “fseek() — fseeko() — Reposition File Position” on page 124
v “perror() — Print Error Message” on page 209
v “rewind() — Adjust Current File Position” on page 259
v “strerror() — Set Pointer to Run-Time Error Message” on page 350
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The clock() function returns an approximation of the processor time used by the
program since the beginning of an implementation-defined time-period that is
related to the process invocation. To obtain the time in seconds, divide the value
that is returned by clock() by the value of the macro CLOCKS_PER_SEC.
Return Value
To measure the time spent in a program, call clock() at the start of the program,
and subtract its return value from the value returned by subsequent calls to
clock(). On other platforms, you can not always rely on the clock()function
because calls to the system() function may reset the clock.
This example prints the time that has elapsed since the program was called.
#include <time.h>
#include <stdio.h>
int main(void)
{
int i;
Related Information
v “difftime() — Compute Time Difference” on page 76
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes.
Description
The cos() function calculates the cosine of x. The value x is expressed in radians. If
x is too large, a partial loss of significance in the result may occur.
Return Value
The cos() function returns the cosine of x. The value of errno may be set to either
EDOM or ERANGE.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y;
x = 7.2;
y = cos(x);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “cosh() — Calculate Hyperbolic Cosine”
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The cosh() function calculates the hyperbolic cosine of x. The value x is expressed
in radians.
Return Value
The cosh() function returns the hyperbolic cosine of x. If the result is too large,
cosh() returns the value HUGE_VAL and sets errno to ERANGE.
int main(void)
{
double x,y;
x = 7.2;
y = cosh(x);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “cos() — Calculate Cosine” on page 66
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Description
The ctime() function converts the time value pointed to by time to local time in
the form of a character string. A time value is usually obtained by a call to the
time() function.
The string result that is produced by ctime() contains exactly 26 characters and
has the format:
"%.3s %.3s%3d %.2d:%.2d:%.2d %d\n"
For example:
Mon Jul 16 02:03:55 1987\n\0
The ctime() function uses a 24-hour clock format. The days are abbreviated to:
Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb,
Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have a constant
width. Dates with only one digit are preceded with a zero. The new-line character
(\n) and the null character (\0) occupy the last two positions of the string.
Return Value
| Note: The asctime() and ctime() functions, and other time functions may use a
| common, statically allocated buffer to hold the return string. Each call to one
| of these functions may destroy the result of the previous call. The
| asctime_r(), ctime_r(), gmtime_r(), and localtime_r() functions do not
| use a common, statically-allocated buffer to hold the return string. These
| functions can be used in the place of asctime(), ctime(), gmtime(), and
| localtime() if reentrancy is desired.
| This example polls the system clock using time(). It then prints a message giving
| the current date and time.
|
| #include <time.h>
| #include <stdio.h>
|
| int main(void)
| {
| time_t ltime;
|
| time(<ime);
|
| printf("the time is %s", ctime(<ime));
| }
|
| Related Information
| v “asctime() — Convert Time to Character String” on page 41
| v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
| v “ctime_r() — Convert Time to Character String (Restartable)”
| v “gmtime() — Convert Time” on page 151
| v “gmtime_r() — Convert Time (Restartable)” on page 153
| v “localtime() — Convert Time” on page 173
| v “localtime_r() — Convert Time (Restartable)” on page 174
| v “mktime() — Convert Local Time” on page 204
| v “setlocale() — Set Locale” on page 322
| v “strftime() — Convert Date/Time to String” on page 354
| v “time() — Determine Current Time” on page 391
| v “printf() — Print Formatted Characters” on page 211
| v “<time.h>” on page 16
|
| ctime_r() — Convert Time to Character String (Restartable)
| Format
| #include <time.h>
| char *ctime_r(const time_t *time, char *buf);
| Threadsafe: Yes.
The ctime_r() function converts the time value pointed to by time to local time in
the form of a character string. A time value is usually obtained by a call to the
time() function.
The string result that is produced by the ctime_r() function contains exactly 26
characters and has the format:
"%.3s %.3s%3d %.2d:%.2d:%.2d %d\n"
For example:
Mon Jul 16 02:03:55 1987\n\0
The ctime_r() function uses a 24-hour clock format. The days are abbreviated to:
Sun, Mon, Tue, Wed, Thu, Fri, and Sat. The months are abbreviated to: Jan, Feb,
Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, and Dec. All fields have a constant
width. Dates with only one digit are preceded with a zero. The new-line character
(\n) and the null character (\0) occupy the last two positions of the string.
Return Value
The ctime_r() function returns a pointer to the character string result. If the
function is unsuccessful, it returns NULL. A call to ctime_r() is equivalent to:
| asctime_r(localtime_r(&anytime, buf2), buf)
This example polls the system clock using ctime_r(). It then prints a message
giving the current date and time.
| #include <time.h>
| #include <stdio.h>
|
| int main(void)
| {
| time_t ltime;
| char buf[50];
|
| time(<ime);
| printf("the time is %s", ctime_r(<ime, buf));
| }
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime_r() — Convert Time (Restartable)” on page 174
v “localtime() — Convert Time” on page 173
v “mktime() — Convert Local Time” on page 204
| Threadsafe: Yes.
| Description
| The following macros are defined within the <mallocinfo.h> include file to be
| specified for the dump_level parameter:
|| _C_NO_DUMPS No information is dumped
| _C_DUMP_TOTALS Overall totals and totals for each chunk are
| printed
| _C_DUMP_CHUNKS Additional information about each chunk is
| printed
| _C_DUMP_NODES Additional information for all nodes within
| each chunk is printed
| _C_DUMP_TREE Additional information for the cartesian tree
| used to track free nodes is printed
| _C_DUMP_ALL All available information is printed
|
| The following macros are defined within the <mallocinfo.h> include file to be
| specified for the verify_level parameter:
|| _C_NO_CHECKS No verification checks are performed
| _C_CHECK_TOTALS Totals are verified for correctness
| _C_CHECK_CHUNKS Additional verifications are performed for
| each chunk
| _C_CHECK_NODES Additional verifications are performed for all
| nodes within each chunk
| _C_CHECK_TREE Additional verifications are performed for
| the cartesian tree used to track free nodes
| Note: This function is for low-level debug of teraspace memory usage within an
| application.
| Return Value
| Threadsafe: Yes.
| Description
| Note: This function is for low-level debug of teraspace memory usage within an
| application.
| Return Value
Threadsafe: Yes.
Description
The difftime() function computes the difference in seconds between time2 and
time1.
Return Value
The difftime() function returns the elapsed time in seconds from time1 to time2 as
a double precision number. Type time_t is defined in <time.h>.
This example shows a timing application that uses difftime(). The example
calculates how long, on average, it takes to find the prime numbers from 2 to
10000.
int mark[SIZE];
int main(void)
{
time_t start, finish;
int i, loop, n, num;
time(&start);
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “mktime() — Convert Local Time” on page 204
v “strftime() — Convert Date/Time to String” on page 354
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes. However, only the function version is threadsafe. The macro
version is NOT threadsafe.
Description
The div() function calculates the quotient and remainder of the division of
numerator by denominator.
Return Value
The div() function returns a structure of type div_t, containing both the quotient
int quot and the remainder int rem. If the return value cannot be represented, its
value is undefined. If denominator is 0, an exception will be raised.
This example uses div() to calculate the quotients and remainders for a set of two
dividends and two divisors.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int num[2] = {45,-45};
int den[2] = {7,-7};
div_t ans; /* div_t is a struct type containing two ints:
’quot’ stores quotient; ’rem’ stores remainder */
short i,j;
printf("Results of division:\n");
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
{
ans = div(num[i],den[j]);
printf("Dividend: %6d Divisor: %6d", num[i], den[j]);
printf(" Quotient: %6d Remainder: %6d\n", ans.quot, ans.rem);
}
}
Results of division:
Dividend: 45 Divisor: 7 Quotient: 6 Remainder: 3
Dividend: 45 Divisor: -7 Quotient: -6 Remainder: 3
Dividend: -45 Divisor: 7 Quotient: -6 Remainder: -3
Dividend: -45 Divisor: -7 Quotient: 6 Remainder: -3
**********************************************************/
Related Information
v “ldiv() — lldiv() — Perform Long and Long Long Division” on page 166
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The erfc() function computes the value of 1.0 - erf(x). The erfc() function is used
in place of erf() for large values of x.
Return Value
The erf() function returns a double value that represents the error function. The
erfc() function returns a double value representing 1.0 - erf.
This example uses erf() and erfc() to compute the error function of two
numbers.
#include <stdio.h>
#include <math.h>
int main(void)
{
smallx = 0.1;
largex = 10.0;
Related Information
v “Bessel Functions” on page 52
v “gamma() — Gamma Function” on page 140
Threadsafe: Yes.
Description
The exit() function returns control to the host environment from the program. It
first calls all functions that are registered with the atexit() function, in reverse
order; that is, the last one that is registered is the first one called. It deletes all
buffers and closes all open files before ending the program.
The argument status can have a value from 0 to 255 inclusive, or be one of the
macros EXIT_SUCCESS or EXIT_FAILURE. A status value of EXIT_SUCCESS or 0
indicates a normal exit; otherwise, another status value is returned.
Return Value
The exit() function returns both control and the value of status to the operating
system.
This example ends the program after deleting buffers and closing any open files if
it cannot open the file myfile.
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
int main(void)
{
if ((stream = fopen("mylib/myfile", "r")) == NULL)
{
perror("Could not open data file");
exit(EXIT_FAILURE);
}
}
Related Information
v “abort() — Stop a Program” on page 38
v “atexit() — Record Program Ending Function” on page 48
v “signal() — Handle Interrupt Signals” on page 330
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
Return Value
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y;
x = 5.0;
y = exp(x);
Related Information
v “log() — Calculate Natural Logarithm” on page 175
v “log10() — Calculate Base 10 Logarithm” on page 176
v “<math.h>” on page 7
Threadsafe: Yes.
The fabs() function calculates the absolute value of the floating-point argument x.
Return Value
The fabs() function returns the absolute value. There is no error return value.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y;
x = -5.6798;
y = fabs(x);
Related Information
v “abs() — Calculate Integer Absolute Value” on page 39
v “labs() — llabs() — Calculate Absolute Value of Long and Long Long Integer”
on page 164
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The fclose() function closes a stream pointed to by stream. This function deletes
all buffers that are associated with the stream before closing it. When it closes the
stream, the function releases any buffers that the system reserved. When a binary
stream is closed, the last record in the file is padded with null characters (\0) to
the end of the record.
Return Value
The fclose() function returns 0 if it successfully closes the stream, or EOF if any
errors were detected.
Note: The storage pointed to by the FILE pointer is freed by the fclose() function.
After the use of the fclose() function, any attempt to use the FILE pointer
is not valid.
This example opens a file myfile for reading as a stream; then it closes this file.
#include <stdio.h>
#define NUM_ALPHA 26
int main(void)
{
FILE *stream;
char buffer[NUM_ALPHA];
Related Information
v “fflush() — Write Buffer to File” on page 87
v “fopen() — Open Files” on page 100
v “freopen() — Redirect Open Files” on page 120
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fdopen() function associates an input or output stream with the file that is
identified by handle. The type variable is a character string specifying the type of
access that is requested for the stream.
Mode Description
r Create a stream to read a text file. The file pointer is set to the beginning of
the file.
w Create a stream to write to a text file. The file pointer is set to the
beginning of the file.
a Create a stream to write, in append mode, at the end of the text file. The
file pointer is set to the end of the file.
r+ Create a stream for reading and writing a text file. The file pointer is set to
the beginning of the file.
w+ Create a stream for reading and writing a text file. The file pointer is set to
the beginning of the file.
a+ Create a stream for reading or writing, in append mode, at the end of the
text file. The file pointer is set to the end of the file.
rb Create a stream to read a binary file. The file pointer is set to the beginning
of the file.
wb Create a stream to write to a binary file. The file pointer is set to the
beginning of the file.
ab Create a stream to write to a binary file in append mode. The file pointer
is set to the end of the file.
r+b or rb+
Create a stream for reading and writing a binary file. The file pointer is set
to the beginning of the file.
w+b or wb+
Create a stream for reading and writing a binary file. The file pointer is set
to the beginning of the file.
a+b or ab+
Create a stream for reading and writing to a binary file in append mode.
The file pointer is set to the end of the file.
Note: Use the w, w+, wb, wb+, and w+b modes with care; they can destroy
existing files.
The specified type must be compatible with the access method you used to open
the file. If the file was opened with the O_APPEND flag, the stream mode must be
a, a+, ab, a+b, or ab+. To use the fdopen() function you need a file descriptor. To
get a descriptor use the POSIX function open(). The O_APPEND flag is a mode for
open(). Modes for open() are defined in QSYSINC/H/FCNTL. For further
information see the APIs topic in the iSeries Information Center.
If fdopen() returns NULL, use close() to close the file. If fdopen() is successful,
you must use fclose() to close the stream and file.
Return Value
This example opens the file sample.dat and associates a stream with the file using
fdopen(). It then reads from the stream into the buffer.
int main(void)
{
long length;
int fh;
char buffer[20];
FILE *fp;
printf("\nCreating sample.dat.\n");
if ((fp= fopen("/sample.dat", "w")) == NULL) {
perror(" File was not created: ");
exit(1);
}
fputs("Sample Program", fp);
fclose(fp);
/****************************************************************
* The output should be:
*
* Creating sample.dat.
* Successfully read from the stream the following:
* Sample Program.
*/
}
Related Information
v “fclose() — Close Stream” on page 82
v “fopen() — Open Files” on page 100
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
Threadsafe: Yes.
Description
The feof() function indicates whether the end-of-file flag is set for the given
stream. The end-of-file flag is set by several functions to indicate the end of the file.
The end-of-file flag is cleared by calling the rewind(), fsetpos(), fseek(), or
clearerr() functions for this stream.
Return Value
The feof() function returns a nonzero value if and only if the EOF flag is set;
otherwise, it returns 0.
This example scans the input stream until it reads an end-of-file character.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char string[100];
FILE *stream;
memset(string, 0, sizeof(string));
stream = fopen("qcpple/qacsrc(feof)", "r");
Related Information
v “clearerr() — Reset Error Indicators” on page 64
v “ferror() — Test for Read/Write Errors” on page 87
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
v “perror() — Print Error Message” on page 209
v “rewind() — Adjust Current File Position” on page 259
Threadsafe: Yes.
Description
The ferror() function tests for an error in reading from or writing to the given
stream. If an error occurs, the error indicator for the stream remains set until you
close stream, call the rewind() function, or call the clearerr() function.
Return Value
The ferror() function returns a nonzero value to indicate an error on the given
stream. A return value of 0 means that no error has occurred.
This example puts data out to a stream, and then checks that a write error has not
occurred.
#include <stdio.h>
int main(void)
{
FILE *stream;
char *string = "Important information";
stream = fopen("mylib/myfile","w");
Related Information
v “clearerr() — Reset Error Indicators” on page 64
v “feof() — Test End-of-File Indicator” on page 86
v “fopen() — Open Files” on page 100
v “perror() — Print Error Message” on page 209
v “strerror() — Set Pointer to Run-Time Error Message” on page 350
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fflush() function causes the system to empty the buffer that is associated
with the specified output stream, if possible. If the stream is open for input, the
fflush() function undoes the effect of any ungetc() function. The stream remains
open after the call.
Note: The system automatically deletes buffers when you close the stream, or
when a program ends normally without closing the stream.
Return Value
The fflush() function returns the value 0 if it successfully deletes the buffer. It
returns EOF if an error occurs.
The fflush() function is not supported for files that are opened with type=record.
int main(void)
{
FILE *stream;
int ch;
unsigned int result = 0;
Related Information
v “fclose() — Close Stream” on page 82
v “fopen() — Open Files” on page 100
v “setbuf() — Control Buffering” on page 319
v “ungetc() — Push Character onto Input Stream” on page 399
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fgetc() function reads a single unsigned character from the input stream at the
current position and increases the associated file pointer, if any, so that it points to
the next character.
Return Value
The fgetc() function returns the character that is read as an integer. An EOF
return value indicates an error or an end-of-file condition. Use the feof() or the
ferror() function to determine whether the EOF value indicates an error or the
end of the file.
The fgetc() function is not supported for files that are opened with type=record.
#include <stdio.h>
#define MAX_LEN 80
int main(void)
{
FILE *stream;
char buffer[MAX_LEN + 1];
int i, ch;
stream = fopen("mylib/myfile","r");
buffer[i] = ’\0’;
if (fclose(stream))
perror("fclose error");
/***********************************************************************
If FILENAME contains: one two three
The output should be:
line: one two three
************************************************************************/
Related Information
v “feof() — Test End-of-File Indicator” on page 86
v “ferror() — Test for Read/Write Errors” on page 87
v “fgetwc() — Read Wide Character from Stream” on page 94
90 ILE C/C++ Run-Time Library Functions V5R3
v “fputc() — Write Character” on page 109
v “getc() – getchar() — Read a Character” on page 142
v “getwc() — Read Wide Character from Stream” on page 147
v “getwchar() — Get Wide Character from stdin” on page 149
v “<stdio.h>” on page 14
Threadsafe: YES
Description
The fgetpos() function stores the current position of the file pointer that is
associated with stream into the object pointed to by pos. The value pointed to by
pos can be used later in a call to fsetpos() to reposition the stream.
Return Value
The fgetpos() function returns 0 if successful; on error, it returns nonzero and sets
errno to a nonzero value.
This example opens the file myfile for reading and stores the current file pointer
position into the variable pos.
#include <stdio.h>
FILE *stream;
int main(void)
{
int retcode;
fpos_t pos;
Related Information
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
v “ftell() — ftello() — Get Current Position” on page 128
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fgets() function reads characters from the current stream position up to and
including the first new-line character (\n), up to the end of the stream, or until the
number of characters read is equal to n-1, whichever comes first. The fgets()
function stores the result in string and adds a null character (\0) to the end of the
string. The string includes the new-line character, if read. If n is equal to 1, the
string is empty.
Return Value
The fgets() function returns a pointer to the string buffer if successful. A NULL
return value indicates an error or an end-of-file condition. Use the feof() or
ferror() functions to determine whether the NULL value indicates an error or the
end of the file. In either case, the value of the string is unchanged.
This example gets a line of input from a data stream. The example reads no more
than MAX_LEN - 1 characters, or up to a new-line character from the stream.
#include <stdio.h>
int main(void)
{
FILE *stream;
char line[MAX_LEN], *result;
stream = fopen("mylib/myfile","rb");
if (fclose(stream))
perror("fclose error");
}
Related Information
v “feof() — Test End-of-File Indicator” on page 86
v “ferror() — Test for Read/Write Errors” on page 87
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “fputs() — Write String” on page 112
v “gets() — Read a Line” on page 146
v “puts() — Write a String” on page 224
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fgetwc() reads the next multibyte character from the input stream pointed to
by stream, converts it to a wide character, and advances the associated file position
indicator for the stream (if defined).
Return Value
The fgetwc() function returns the next wide character that corresponds to the
multibyte character from the input stream pointed to by stream. If the stream is at
EOF, the EOF indicator for the stream is set, and fgetwc() returns WEOF.
If a read error occurs, the error indicator for the stream is set, and the fgetwc()
function returns WEOF. If an encoding error occurs (an error converting the
multibyte character into a wide character), the fgetwc() function sets errno to
EILSEQ and returns WEOF.
Use the ferror() and feof() functions to distinguish between a read error and an
EOF. EOF is only reached when an attempt is made to read past the last byte of
data. Reading up to and including the last byte of data does not turn on the EOF
indicator.
This example opens a file, reads in each wide character, and prints out the
characters.
| #include <stdio.h>
| #include <stdlib.h>
| #include <wchar.h>
| #include <errno.h>
|
| int main(void)
| {
| FILE *stream;
| wint_t wc;
|
| if (NULL == (stream = fopen("fgetwc.dat", "r"))) {
| printf("Unable to open: \"fgetwc.dat\"\n");
| exit(1);
| }
|
| errno = 0;
| while (WEOF != (wc = fgetwc(stream)))
| printf("wc = %lc\n", wc);
|
| if (EILSEQ == errno) {
| printf("An invalid wide character was encountered.\n");
| exit(1);
| }
| fclose(stream);
| return 0;
| }
| * * * End of File * * *
|
Related Information
v “fgetc() — Read a Character” on page 89
v “fputwc() — Write Wide Character” on page 113
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “getc() – getchar() — Read a Character” on page 142
v “getwc() — Read Wide Character from Stream” on page 147
v “getwchar() — Get Wide Character from stdin” on page 149
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The fgetws() function reads at most one less than the number of wide characters
specified by n from the stream pointed to by stream. The fgetws() function stops
reading characters after WEOF, or after it reads a new-line wide character (which is
retained). It adds a null wide character immediately after the last wide character
read into the array. The fgetws() function advances the file position unless there is
an error. If an error occurs, the file position is undefined.
Using non-wide-character functions with the fgetws() function on the same stream
results in undefined behavior. After calling the fgetws() function, flush the buffer
or reposition the stream pointer before calling a write function for the stream,
unless WEOF has been reached. After a write operation on the stream, flush the
buffer or reposition the stream pointer before calling the fgetws()function.
Notes:
1. The behavior of the fgetws() function is affected by the LC_CTYPE category of
the current locale. If you change the category between subsequent read
operations on the same stream, undefined results can occur.
| 2. This function is not available when either LOCALETYPE(*CLD) or
| SYSIFCOPT(*NOIFSIO) is specified on the compilation command.
Return Value
If a read error occurs, the contents of wcs are indeterminate, and the fgetws()
function returns NULL. If an encoding error occurs (in converting a wide character
to a multibyte character), the fgetws() function sets errno to EILSEQ and returns
NULL.
If n equals 1, the wcs buffer has only room for the ending null character, and
nothing is read from the stream. (Such an operation is still considered a read
operation, so it cannot immediately follow a write operation unless the buffer is
flushed or the stream pointer repositioned first.) If n is greater than 1, the fgetws()
function fails only if an I/O error occurs, or if WEOF is reached before data is read
from the stream.
| For information about errno values for fgetws(), see “fgetwc() — Read Wide
| Character from Stream” on page 94.
This example opens a file, reads in the file contents, then prints the file contents.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
int main(void)
{
FILE *stream;
wchar_t wcs[100];
errno = 0;
if (NULL == fgetws(wcs, 100, stream)) {
if (EILSEQ == errno) {
printf("An invalid wide character was encountered.\n");
exit(1);
}
else if (feof(stream))
printf("End of file reached.\n");
else
perror("Read error.\n");
}
printf("wcs = \"%ls\"\n", wcs);
fclose(stream);
return 0;
/************************************************************
Assuming the file fgetws.dat contains:
Related Information
v “fgetc() — Read a Character” on page 89
v “fgets() — Read a String” on page 92
v “fgetwc() — Read Wide Character from Stream” on page 94
v “fputws() — Write Wide-Character String” on page 115
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The fileno() function only works in ILE C when the Integrated File System has
been enabled. The fileno() function determines the file handle that is currently
associated with stream.
Return Value
This example determines the file handle of the stderr data stream.
fp = fopen ("stderr","w");
result = fileno(fp);
printf("The file handle associated with stderr is %d.\n", result);
return 0;
/*****************************************************************
* The output should be:
*
* The file handle associated with stderr is -1.
****************************************************************/
}
Related Information
v “fopen() — Open Files” on page 100
v “freopen() — Redirect Open Files” on page 120
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The floor() function calculates the largest integer that is less than or equal to x.
Return Value
This example assigns y value of the largest integer less than or equal to 2.8 and z
the value of the largest integer less than or equal to -2.8.
#include <math.h>
#include <stdio.h>
int main(void)
{
double y, z;
y = floor(2.8);
z = floor(-2.8);
Related Information
v “ceil() — Find Integer >=Argument” on page 63
v “fmod() — Calculate Floating-Point Remainder”
v “<math.h>” on page 7
Threadsafe: Yes.
The fmod() function calculates the floating-point remainder of x/y. The absolute
value of the result is always less than the absolute value of y. The result will have
the same sign as x.
Return Value
This example computes z as the remainder of x/y; here, x/y is -3 with a remainder
of -1.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y, z;
x = -10.0;
y = 3.0;
z = fmod(x,y); /* z = -1.0 */
Related Information
v “ceil() — Find Integer >=Argument” on page 63
v “fabs() — Calculate Floating-Point Absolute Value” on page 81
v “floor() —Find Integer <=Argument” on page 99
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The fopen() function opens the file that is specified by filename. The mode
parameter is a character string specifying the type of access that is requested for
the file. The mode variable contains one positional parameter followed by optional
keyword parameters.
.
Notes:
1. The fopen() function is not supported for files that are opened with the
attributes type=record and ab+, rb+, or wb+
2. Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files
of the same name will be lost.
Text files contain printable characters and control characters that are organized into
lines. Each line ends with a new-line character, except possibly the last line,
depending on the compiler. The system may insert or convert control characters in
an output text stream. The fopen() function mode ″a″ and ″a+″ can not be used for
the QSYS.LIB file system. There are implementation restrictions when using the
QSYS.LIB file system for text files in all modes. Seeking beyond the start of files
cannot be relied on to work with streams opened in text mode.
| Note: When you use fopen() to create a file in the QSYS.LIB file system,
| specifying a library name of *LIBL or blank causes the file to be created in
| QTEMP library.
Note: Data output to a text stream may not compare as equal to the same data on
input. The QSYS.LIB file system treats database files as a directory of
members. The database file must exist before a member can be dynamically
created when using the fopen() function.
| See Large file support in the Files and file systems, Integrated File System topic in
| the iSeries Information Center. for the current file system limit for the Integrated
| File System. There are three methods you can use to allow your application
| programs access to 64-bit C runtime functions for IFS files larger than 2 gigabytes:
v Specify SYSIFCOPT(*IFS64IO) on a compilation command, which causes the
native C compiler to define _IFS64_IO_. This causes the macros _LARGE_FILES
and _LARGE_FILE_API to be defined.
v Define the macro _LARGE_FILES, either in the program source or by specifying
DEFINE(’_LARGE_FILES’) on a compilation command. The existing C runtime
functions and the relevant data types in the code will all be automatically
mapped or redefined to their 64-bit versions.
v Define the macro _LARGE_FILE_API, either in the program source or by
specifying DEFINE(’_LARGE_FILE_API’) on a compilation command. This
makes visible the set of of new 64-bit C runtime functions and data types. The
application must explicitly specify the name of the C runtime functions, both
existing version and 64-bit version, to use.
The 64-bit C runtime functions include the following: int fgetpos64(), FILE
*fopen64(), FILE *freopen64(), FILE *wfopen64(), int fsetpos64(FILE *, const
fpost64_t *), FILE *tmpfile64(), int fseeko(FILE *, off_t, int), int
fseeko64(FILE *, off64_t, int), off_t ftello(FILE *), and off64_t ftello64().
Binary files contain a series of characters. For binary files, the system does not
translate control characters on input or output.
If a binary file does not exist, you can create one using the following command:
When you open a file with a, a+, ab, a+b or ab+ mode, all write operations take
place at the end of the file. Although you can reposition the file pointer using the
fseek() function or the rewind() function, the write functions move the file pointer
back to the end of the file before they carry out any operation. This action prevents
you from overwriting existing data.
When you specify the update mode (using + in the second or third position), you
can both read from and write to the file. However, when switching between
reading and writing, you must include an intervening positioning function such as
the fseek(), fsetpos(), rewind(), or fflush(). Output may immediately follow
input if the end-of-file was detected.
Note: Mixed data (the data contains both single and double-byte
characters) is not supported for a file data processing mode of text.
Mixed data is supported for a file processing mode of binary.
If you specify the ccsid keyword, you cannot specify the o_ccsid keyword
or the codepage keyword.
The fopen() function will fail with the ECONVERT error when all of the
following three conditions occur:
v The file data processing mode is text.
v The code page is not specified.
v The CCSID of the job is ’mixed-data’ (the data contains both single– and
double–byte characters).
fclose(fp);
/* Now reopen the file with CCSID 13488, because your application
wants to deal with the data in UNICODE */
if (funcreturn < 0) {
printf("Error with ’fputws’ on line %d\n", __LINE__);
}
/* Because the file was tagged with CCSID 37, the unicode ABC was
converted to EBCDIC ABC when it was written to the file. */
codepage=value
The code page that is specified by value is used.
The keyword parameters are not case sensitive and should be separated by a
comma.
Return Value
The fopen() function returns a pointer to a FILE structure type that can be used to
access the open file.
Note: To use stream files (type = record) with record I/O functions, you must cast
the FILE pointer to an RFILE pointer.
If the mode string passed to fopen() is correct, fopen() will not set errno to
EBADMODE, regardless of the file type.
If the mode string that is passed to fopen() is not valid, fopen() will set errno to
EBADMODE, regardless of the file type.
If the mode string passed to fopen() is correct, but is invalid to that specific type
of file, fopen() will set errno to ENOTOPEN, EIOERROR, or EIORECERR,
regardless of the file type.
#include <stdio.h>
#define MAX_LEN 60
int main(void)
{
FILE *stream;
fpos_t pos;
char line1[MAX_LEN];
char line2[MAX_LEN];
char *result;
char ch;
int num;
Related Information
v “fclose() — Close Stream” on page 82
Threadsafe: Yes.
Description
The fprintf() function formats and writes a series of characters and values to the
output stream. The fprintf() function converts each entry in argument-list, if any,
and writes to the stream according to the corresponding format specification in the
format-string.
The format-string has the same form and function as the format-string argument for
the printf() function.
Return Value
The fprintf() function returns the number of bytes that are printed or a negative
value if an output error occurs.
| For information about errno values for fprintf(), see “printf() — Print Formatted
| Characters” on page 211.
This example sends a line of asterisks for each integer in the array count to the file
myfile. The number of asterisks that are printed on each line corresponds to an
integer in the array.
int main(void)
{
int i,j;
FILE *stream;
*
*****
********
***
***
*****
******
********
**********
*/
Related Information
v “fscanf() — Read Formatted Data” on page 123
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “printf() — Print Formatted Characters” on page 211
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
Return Value
The fputc() function returns the character that is written. A return value of EOF
indicates an error.
The fputc() function is not supported for files that are opened with type=record.
This example writes the contents of buffer to a file that is called myfile.
Note: Because the output occurs as a side effect within the second expression of
the for statement, the statement body is null.
#define NUM_ALPHA 26
int main(void)
{
FILE * stream;
int i;
int ch;
Related Information
v “fgetc() — Read a Character” on page 89
v “putc() – putchar() — Write a Character” on page 221
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
_fputchar writes the single character c to the stdout stream at the current position.
It is equivalent to the following fputc call:
fputc(c, stdout);
Return Value
_fputchar returns the character written. A return value of EOF indicates that a write
error has occurred. Use ferror and feof to tell whether this is an error condition
or the end of the file.
| For information about errno values for _fputchar, see “fputc() — Write Character”
| on page 109.
Related Information:
v “getc() – getchar() — Read a Character” on page 142
v “fputc() — Write Character” on page 109
v “putc() – putchar() — Write a Character” on page 221
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fputs() function copies string to the output stream at the current position. It
does not copy the null character (\0) at the end of the string.
Return Value
The fputs() function is not supported for files that are opened with type=record.
| For information about errno values for fputs(), see “fputc() — Write Character”
| on page 109.
#define NUM_ALPHA 26
int main(void)
{
FILE * stream;
int num;
Related Information
v “fgets() — Read a String” on page 92
v “fputws() — Write Wide-Character String” on page 115
v “gets() — Read a Line” on page 146
v “puts() — Write a String” on page 224
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
| The fputwc() function writes the wide character wc to the output stream pointed
| to by stream at the current position. It also advances the file position indicator
| appropriately. If the file cannot support positioning requests, or if the stream was
| opened with append mode, the character is appended to the stream.
Using non-wide-character functions with the fputwc() function on the same stream
will result in undefined behavior. After calling the fputwc() function, delete the
buffer or reposition the stream pointer before calling a read function for the stream.
After reading from the stream, delete the buffer or reposition the stream pointer
before calling the fputwc() function, unless EOF has been reached.
Return Value
The fputwc() function returns the wide character that is written. If a write error
occurs, the error indicator for the stream is set, and the fputwc() function returns
WEOF. If an encoding error occurs during conversion from wide character to a
multibyte character, fputwc() sets errno to EILSEQ and returns WEOF.
| For information about errno values for putwc(), see “fputc() — Write Character”
| on page 109.
This example opens a file and uses the fputwc() function to write wide characters
to the file.
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <errno.h>
int main(void)
{
FILE *stream;
wchar_t *wcs = L"A character string.";
int i;
/***************************************************************
The output file fputwc.out should contain:
A character string.
***************************************************************/
}
Related Information
v “fgetwc() — Read Wide Character from Stream” on page 94
Threadsafe: Yes.
Description
| The fputws() function writes the wide-character string wcs to a stream. It does not
| write the ending null wide characters.
Using non-wide-character functions with the fputws() function on the same stream
will result in undefined behavior. After calling the fputws() function, flush the
buffer or reposition the stream pointer before calling a read function for the stream.
After a read operation, flush the buffer or reposition the stream pointer before
calling the fputws() function, unless EOF has been reached.
Notes:
1. The behavior of the fputws() function is affected by the LC_CTYPE category of
the current locale. If you change the category between subsequent operations
on the same stream, undefined results can occur.
| 2. This function is not available when either LOCALETYPE(*CLD) or
| SYSIFCOPT(*NOIFSIO) is specified on the compilation command.
Return Value
| For information about errno values for fputws(), see “fputc() — Write Character”
| on page 109.
This example opens a file and writes a wide-character string to the file using the
fgetws() function.
int main(void)
{
FILE *stream;
wchar_t *wcs = L"This test string should not return -1";
errno = 0;
if (EOF == fputws(wcs, stream)) {
printf("Unable to complete fputws() function.\n");
if (EILSEQ == errno)
printf("An invalid wide character was encountered.\n");
exit(1);
}
fclose(stream);
return 0;
/************************************************************
The output file fputws.out should contain:
Related Information
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “fputs() — Write String” on page 112
v “fputwc() — Write Wide Character” on page 113
v “puts() — Write a String” on page 224
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The fread() function reads up to count items of size length from the input stream
and stores them in the given buffer. The position in the file increases by the number
of bytes read.
Return Value
The fread() function returns the number of full items successfully read, which can
be less than count if an error occurs, or if the end-of-file is met before reaching
116 ILE C/C++ Run-Time Library Functions V5R3
count. If size or count is 0, the fread() function returns zero, and the contents of the
array and the state of the stream remain unchanged.
Use the ferror() and feof() functions to distinguish between a read error and an
end-of-file.
When using fread() for record input, set size to 1 and count to the maximum
expected length of the record, to obtain the number of bytes. If you do not know
the record length, you should set size to 1 and count to a large value. You can read
only one record at a time when using record I/O.
This example attempts to read NUM_ALPHA characters from the file myfile. If
there are any errors with either fread() or fopen(), a message is printed.
#define NUM_ALPHA 26
int main(void)
{
FILE * stream;
int num; /* number of characters read from stream */
/* Do not forget that the ’\0’ char occupies one character too! */
char buffer[NUM_ALPHA + 1];
Related Information
v “feof() — Test End-of-File Indicator” on page 86
v “ferror() — Test for Read/Write Errors” on page 87
v “fopen() — Open Files” on page 100
v “fwrite() — Write Items” on page 136
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The free() function frees a block of storage. The ptr argument points to a block
that is previously reserved with a call to the calloc(), malloc(), realloc(),
_C_TS_calloc(), _C_TS_malloc(), _C_TS_realloc(), or _C_TS_malloc64() functions.
The number of bytes freed is the number of bytes specified when you reserved (or
reallocated, in the case of the realloc() function) the block of storage. If ptr is
NULL, free() simply returns.
To use Teraspace storage instead of heap storage without changing the C source
code, specify the TERASPACE(*YES *TSIFC) parameter on the CRTCMOD compiler
command. This maps the free() library function to _C_TS_free(), its Teraspace
storage counterpart.
| Following are some of the problems that can cause a C2M1212 message to
| be signalled:
| v A pointer that was never set to point to storage reserved by the malloc()
| function is passed to the free() function.
| v A pointer was set to point to storage reserved by the malloc() function,
| was subsequently modified, and then is passed to the free() function.
| v A pointer was set to point to storage reserved by the malloc() function,
| was passed to the free() function, and then is passed to the free()
| function..
Return Value
This example uses the calloc() function to allocate storage for x array elements,
and then calls the free() function to free them.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
Related Information
v “calloc() — Reserve and Initialize Storage” on page 57
v “malloc() — Reserve Storage Block” on page 180
v “realloc() — Change Reserved Storage Block Size” on page 247
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The freopen() function closes the file that is currently associated with stream and
reassigns stream to the file that is specified by filename. The freopen() function
opens the new file associated with stream with the given mode, which is a character
string specifying the type of access requested for the file. You can also use the
freopen() function to redirect the standard stream files stdin, stdout, and stderr
to files that you specify.
For database files, if filename is an empty string, the freopen() function closes and
reopens the stream to the new open mode, rather than reassigning it to a new file
or device. You can use the freopen() function with no file name specified to
change the mode of a standard stream from text to binary without redirecting the
stream, for example:
fp = freopen("", "rb", stdin);
You can use the same method to change the mode from binary back to text.
You can use the same method to change the mode from binary back to text.
Return Value
The freopen() function returns a pointer to the newly opened stream. If an error
occurs, the freopen() function closes the original file and returns a NULL pointer
value.
This example closes the stream1 data stream and reassigns its stream pointer.
stream1 and stream2 will have the same value, but they will not necessarily have
the same value as stream.
int main(void)
{
FILE *stream, *stream1, *stream2;
char line[MAX_LEN], *result;
int i;
stream = fopen("mylib/myfile","r");
if ((result = fgets(line,MAX_LEN,stream)) != NULL)
printf("The string is %s\n", result);
stream1 = stream;
stream2 = freopen("", "w+", stream1);
fputs( line, stream2 );
fclose( stream2);
}
Related Information
v “fclose() — Close Stream” on page 82
v “fopen() — Open Files” on page 100
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The frexp() function breaks down the floating-point value x into a term m for the
mantissa and another term n for the exponent. It is done such that x=m*2 n, and
the absolute value of m is greater than or equal to 0.5 and less than 1.0 or equal to
0. The frexp() function stores the integer exponent n at the location to which
expptr points.
Return Value
The frexp() function returns the mantissa term m. If x is 0, frexp() returns 0 for
both the mantissa and exponent. The mantissa has the same sign as the argument
x. The result of the frexp() function cannot have a range error.
This example separates the floating-point value of x, 16.4, into its mantissa 0.5125,
and its exponent 5. It stores the mantissa in y and the exponent in n.
int main(void)
{
double x, m;
int n;
x = 16.4;
m = frexp(x, n);
Related Information
v “ldexp() — Multiply by a Power of Two” on page 166
v “modf() — Separate Floating-Point Value” on page 205
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The fscanf() function reads data from the current position of the specified stream
into the locations that are given by the entries in argument-list, if any. Each entry in
argument-list must be a pointer to a variable with a type that corresponds to a type
specifier in format-string.
The format-string controls the interpretation of the input fields and has the same
form and function as the format-string argument for the scanf() function.
Return Value
The fscanf() function returns the number of fields that it successfully converted
and assigned. The return value does not include fields that the fscanf() function
read but did not assign.
The return value is EOF if an input failure occurs before any conversion, or the
number of input items assigned if successful.
This example opens the file myfile for reading and then scans this file for a string, a
long integer value, a character, and a floating-point value.
#define MAX_LEN 80
int main(void)
{
FILE *stream;
long l;
float fp;
char s[MAX_LEN + 1];
char c;
string = abcdefghijklmnopqrstuvwxyz
long double = 343
char = .
float = 2.000000
*/
Related Information
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
v “scanf() — Read Data” on page 313
v “sscanf() — Read Data” on page 339
v “swscanf() — Read Wide Character Data” on page 387
v “wscanf() — Read Data Using Wide-Character Format String” on page 482
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fseeko() function is identical to fseek() except that the offset argument is of
type off_t.
The origin must be one of the following constants that are defined in <stdio.h>:
Origin Definition
SEEK_SET
Beginning of file
SEEK_CUR
Current position of file pointer
SEEK_END
End of file
For a binary stream, you can also change the position beyond the end of the file.
An attempt to position before the beginning of the file causes an error. If
successful, the fseek() or fseeko() function clears the end-of-file indicator, even
when origin is SEEK_END, and undoes the effect of any preceding the ungetc()
function on the same stream.
Note: For streams opened in text mode, the fseek() and fseeko() functions have
limited use because some system translations (such as those between
carriage-return-line-feed and new line) can produce unexpected results. The
only fseek() and fseeko() operations that can be relied upon to work on
streams opened in text mode are seeking with an offset of zero relative to
any of the origin values, or seeking from the beginning of the file with an
offset value returned from a call to the ftell()or ftello() functions. Calls
to the ftell() and ftello() functions are subject to their restrictions.
Return Value
The fseek() and fseeko() functions are not supported for files that are opened
with type=record.
This example opens a file myfile for reading. After performing input
operations,fseek() moves the file pointer to the beginning of the file.
#include <stdio.h>
#define MAX_LEN 10
int main(void)
{
FILE *stream;
char buffer[MAX_LEN + 1];
int result;
int i;
char ch;
Related Information
v “ftell() — ftello() — Get Current Position” on page 128
v “fgetpos() — Get File Position” on page 91
v “fsetpos() — Set File Position”
v “rewind() — Adjust Current File Position” on page 259
v “ungetc() — Push Character onto Input Stream” on page 399
v “fseek() — fseeko() — Reposition File Position” on page 124
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fsetpos() function moves any file position that is associated with stream to a
new location within the file according to the value pointed to by pos. The value of
pos was obtained by a previous call to the fgetpos() library function.
If successful, fsetpos() clears the end-of-file indicator, and undoes the effect of any
previous ungetc() function on the same stream.
After the fsetpos() call, the next operation on a stream in update mode may be
input or output.
Return Value
The fsetpos() function cannot be used for files that are opened with type=record.
Also, the fsetpos() function can only support setting the position to the beginning
of the file if:
v your program is compiled with *IFSIO, and
v you are working on a file in the QSYS file system.
This example opens a file mylib/myfile for reading. After performing input
operations, fsetpos() moves the file pointer to the beginning of the file and
rereads the first byte.
#include <stdio.h>
FILE *stream;
int main(void)
{
int retcode;
fpos_t pos;
char ptr[20]; /* existing file ’mylib/myfile’ has 20 byte records */
int i;
/* Open file, get position of file pointer, and read first record */
fclose(stream);
}
Related Information
v “fgetpos() — Get File Position” on page 91
v “fseek() — fseeko() — Reposition File Position” on page 124
v “ftell() — ftello() — Get Current Position”
v “rewind() — Adjust Current File Position” on page 259
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The ftell() and ftello() functions find the current position of the file associated
with stream. For a fixed-length binary file, the value that is returned is an offset
relative to the beginning of the stream.
For file in the QSYS library system, the ftell() and ftello() functions return a
relative value for fixed-format binary files and an encoded value for other file
types. This encoded value must be used in calls to the fseek() and
fseeko()functions to positions other than the beginning of the file.
Return Value
The ftell() and ftello() functions return the current file position. On error,
ftell() and ftello() return –1, cast to long and off_t respectively, and set
errno to a nonzero value.
The ftell() and ftello() functions are not supported for files that are opened
with type=record.
This example opens the file mylib/myfile for reading. It reads enough characters to
fill half of the buffer and prints out the position in the stream and the buffer.
| #include <stdio.h>
|
| #define NUM_ALPHA 26
| #define NUM_CHAR 6
|
| int main(void)
| {
| FILE * stream;
| int i;
| char ch;
|
| char buffer[NUM_ALPHA];
| long position;
|
| if (( stream = fopen("mylib/myfile", "r")) != NULL )
| {
| /* read into buffer */
| for ( i = 0; ( i < NUM_ALPHA/2 ) && ((buffer[i] = fgetc(stream)) != EOF ); ++i )
| if (i==NUM_CHAR-1) /* We want to be able to position the */
| /* file pointer to the character in */
| /* position NUM_CHAR */
| position = ftell(stream);
|
| buffer[i] = ’\0’;
| } printf("Current file position is %d\n", position);
| printf("Buffer contains: %s\n", buffer);
| }
Related Information
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fgetpos() — Get File Position” on page 91
v “fopen() — Open Files” on page 100
v “fsetpos() — Set File Position” on page 126
v “ftell() — ftello() — Get Current Position” on page 128
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fwide() function determines the orientation of the stream pointed to by stream.
If mode is greater than 0, the fwide() function first attempts to make the stream
wide oriented. If mode is less than 0, the fwide() function first attempts to make
the stream byte oriented. Otherwise, mode is 0, and the fwide() function does not
alter the orientation of the stream.
Return Value
If, after the call, the stream has wide orientation, the fwide() function returns a
value greater than 0. If the stream has byte orientation, it returns a value less than
0. If the stream has no orientation, it returns 0.
int main(void)
{
FILE *stream;
/* Demonstrate that fwide can be used to set the orientation,
but cannot change it once it has been set. */
stream = fopen("test.dat","w");
printf("After opening the file: ");
check_orientation(stream);
fwide(stream, -1); /* Make the stream byte oriented */
printf("After fwide(stream, -1): ");
check_orientation(stream);
fwide(stream, 1); /* Try to make the stream wide oriented */
printf("After fwide(stream, 1): ");
check_orientation(stream);
fclose(stream);
printf("Close the stream\n");
/* Check that a wide character output operation sets the orientation
as expected. */
stream = fopen("test.dat","w");
printf("After opening the file: ");
check_orientation(stream);
fwprintf(stream, L"pi = %.5f\n", 4* atan(1.0));
printf("After fwprintf( ): ");
check_orientation(stream);
fclose(stream);
return 0;
/*******************************************************************
The output should be similar to :
After opening the file: Stream has no orientation.
After fwide(stream, -1): Stream has byte orientation.
After fwide(stream, 1): Stream has byte orientation.
Close the stream
After opening the file: Stream has no orientation.
After fwprintf( ): Stream has wide orientation.
*******************************************************************/
}
Related Information
v “fgetwc() — Read Wide Character from Stream” on page 94
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “fputwc() — Write Wide Character” on page 113
v “fputws() — Write Wide-Character String” on page 115
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The fwprintf() function writes output to the stream pointed to by stream, under
control of the wide string pointed to by format. The format string specifies how
subsequent arguments are converted for output.
If insufficient arguments exist for the format, the behavior is undefined. If the
format is exhausted while arguments remain, the fwprintf() function evaluates the
excess arguments, but otherwise ignores them. The fwprintf() function returns
when it encounters the end of the format string.
The format comprises zero or more directives: ordinary wide characters (not %)
and conversion specifications. Conversion specifications are processed as if they
were replaced in the format string by wide-character strings. The wide-character
strings are the result of fetching zero or more subsequent arguments and then
converting them, if applicable, according to the corresponding conversion specifier.
The fwprintf() function then writes the expanded wide-character format string to
the output stream.
The format for the fwprintf() function has the same form and function as the
format string for printf(), with the following exceptions:
v %c (without an l prefix) converts an integer argument to wchar_t, as if by calling
the btowc() function.
v %s (without an l prefix) converts an array of multibyte characters to an array of
wchar_t, as if by calling the mbrtowc() function. The array is written up to, but
not including, the terminating null character, unless the precision specifies a
shorter output.
v %ls and %S write an array of wchar_t. The array is written up to, but not
including, the ending null character, unless the precision specifies a shorter
output.
If any argument is, or points to, an union or an aggregate (except for an array of
char type using %s conversion, an array of wchar_t type using %ls conversion, or a
pointer using %p conversion), the behavior is undefined.
Return Value
Note: When writing wide characters, the file should be opened in binary mode, or
the file must be opened with the o_ccsid or codepage parameters. This
ensures that no conversions occur on your wide characters. Since there are
no valid double-byte job CCSIDS on the iSeries, any conversion would be
invalid.
| #include <stdio.h>
| #include <wchar.h>
| #include <locale.h>
| int count [10] = {1, 5, 8, 3, 0, 3, 5, 6, 8, 10};
| int main(void)
| {
| int i,j;
| FILE *stream; /* Open the stream for writing */
| if (NULL == (stream = fopen("/QSYS.LIB/LIB.LIB/WCHAR.FILE/WCHAR.MBR","wb")))
| perror("fopen error");
| for (i=0; i < sizeof(count) / sizeof(count[0]); i++)
| {
| for (j = 0; j < count[i]; j++)
| fwprintf(stream, L"*"); /* Print asterisk */
| fwprintf(stream, L"\n"); /* Move to the next line */
| }
| fclose (stream);
| }
| /* The member WCHAR of file WCHAR will contain:
| *
| *****
| ********
| ***
| ***
| *****
| ******
| ********
| **********
| */
fwprintf(stream, L"%6ls%.2s",ws,s1);
}
Related Information
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “printf() — Print Formatted Characters” on page 211
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “btowc() — Convert Single Byte to Wide Character” on page 55
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “vfwprintf() — Format Argument Data as Wide Characters and Write to a
Stream” on page 407
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “wprintf() — Format Data as Wide Characters and Print” on page 481
v “<stdarg.h>” on page 13
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The fwrite() function writes up to count items, each of size bytes in length, from
buffer to the output stream.
Return Value
The fwrite() function returns the number of full items successfully written, which
can be fewer than count if an error occurs.
When using fwrite() for record output, set size to 1 and count to the length of the
record to obtain the number of bytes written. You can only write one record at a
time when using record I/O.
int main(void)
{
FILE *stream;
long list[NUM];
int numwritten;
int i;
Related Information
v “fopen() — Open Files” on page 100
v “fread() — Read Items” on page 116
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The fwscanf() function reads input from the stream pointed to by stream, under
control of the wide string pointed to by format. The format string specifies the
admissible input sequences and how they are to be converted for assignment. To
receive the converted input, the fwscanf() function uses subsequent arguments as
pointers to the objects.
If insufficient arguments exist for the format, the behavior is undefined. If the
format is exhausted while arguments remain, the fwscanf() function evaluates the
excess arguments, but otherwise ignores them.
The format consists of zero or more directives: one or more white-space wide
characters; an ordinary wide character (neither % nor a white-space wide
character); or a conversion specification. Each conversion specification is
introduced by a %.
The format has the same form and function as the format string for the
scanf()function, with the following exceptions:
If the data is from stdin, and stdin has not been overridden, the data is assumed
to be in the CCSID of the job. The data is converted as required by the format
specifications. If the file that is being read is not opened with file mode rb, then
invalid conversion can occur as there are no valid wide job CCSIDs.
The fwscanf() function leaves trailing white space (including new-line wide
characters) unread, unless matched by a directive. You cannot determine the
success of literal matches and suppressed assignments other than through the %n
directive.
Return Value
The fwscanf() function returns the number of input items assigned, which can be
fewer than provided for, in the event of an early matching failure.
If an input failure occurs before any conversion, the fwscanf() function returns
EOF.
This example opens the file myfile.dat for input, and then scans this file for a
string, a long integer value, a character, and a floating point value.
#define MAX_LEN 80
int main(void)
{
FILE *stream;
long l;
float fp;
char s[MAX_LEN+1];
char c;
/***********************************************
If myfile.dat contains:
abcdefghijklmnopqrstuvwxyz 343.2.
string = abcdefghijklmnopqrstuvwxyz
long integer = 343
char = .
float = 2.000000
***********************************************/
}
This example reads a Unicode string from unicode.dat and prints it to the screen.
The example is compiled with LOCALETYPE(*LOCALEUCS2) SYSIFCOPT(*IFSIO):
Related Information
v “fscanf() — Read Formatted Data” on page 123
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “scanf() — Read Data” on page 313
v “swprintf() — Format and Write Wide Characters to Buffer” on page 385
v “swscanf() — Read Wide Character Data” on page 387
v “wscanf() — Read Data Using Wide-Character Format String” on page 482
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The gamma() function computes the natural logarithm of the absolute value of G(x)
(ln(|G(x)|)), where
Return Value
#include <math.h>
#include <stdio.h>
int main(void)
{
double x=42, g_at_x;
Related Information
v “Bessel Functions” on page 52
v “erf() – erfc() — Calculate Error Functions” on page 79
v “<math.h>” on page 7
Note: The _gcvt function is supported only for C++, not for C.
Threadsafe: Yes.
Description
digit .
+ digit digit
-
_gcvt also converts NaN and infinity values to the strings NAN and INFINITY,
respectively.
Return Value
This example converts the value -3.1415e3 to a character string and places it in the
character array buffer1.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buffer1[10];
_gcvt(-3.1415e3, 7, buffer1);
printf("The first result is %s \n", buffer1);
return 0;
}
Related Information:
v Infinity and NaN Support
v “<stdlib.h>” on page 15
Threadsafe: No. #undef getc or #undef getchar allows the getc or getchar
function to be called instead of the macro version of these functions. The functions
are threadsafe.
Description
The getc() function reads a single character from the current stream position and
advances the stream position to the next character. The getchar() function is
identical to getc(stdin).
Return Value
The getc() and getchar() functions return the character read. A return value of
EOF indicates an error or end-of-file condition. Use ferror() or feof() to
determine whether an error or an end-of-file condition occurred.
The getc() and getchar() functions are not supported in record mode.
This example gets a line of input from the stdin stream. You can also use
getc(stdin) instead of getchar() in the for statement to get a line of input from
stdin.
#define LINE 80
int main(void)
{
char buffer[LINE+1];
int i;
int ch;
Related Information
v “fgetc() — Read a Character” on page 89
v “fgetwc() — Read Wide Character from Stream” on page 94
v “gets() — Read a Line” on page 146
v “getwc() — Read Wide Character from Stream” on page 147
v “getwchar() — Get Wide Character from stdin” on page 149
v “putc() – putchar() — Write a Character” on page 221
v “ungetc() — Push Character onto Input Stream” on page 399
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The getenv() function searches the list of environment variables for an entry
corresponding to varname.
| Note: This function accepts and returns only EBCDIC character strings. When
| LOCALETYPE(*LOCALEUTF) is specified on the compilation command, the
| user may need to convert any non-EBCDIC character strings to EBCDIC
| before calling this function and convert any resulting EBCDIC character
| strings to the correct CCSID.
The getenv() function returns a pointer to the string containing the value for the
specified varname in the current environment. If getenv() cannot find the
environment string, NULL is returned, and errno is set to indicate the error.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *pathvar;
pathvar = getenv("PATH");
printf("pathvar=%s",pathvar);
}
Related Information
v “<stdlib.h>” on page 15
v “putenv() — Change/Add Environment Variables” on page 223
v Environment Variable APIs in the APIs topic in the iSeries Information Center.
Threadsafe: Yes.
Description
The _GetExcData() function returns information about the current exception from
within a C signal handler. The caller of the _GetExcData() function must allocate
enough storage for a structure of type _INTRPT_Hndlr_Parms_T. If the
_GetExcData() function is called from outside a signal handler, the storage pointed
to by parms is not updated.
The format of the exception data appended to the siginfo_t structure is defined
by the _INTRPT_Hndlr_Parms_T structure in except.h.
| Note: The character data returned within the exception data structure is in
| EBCDIC. When LOCALETYPE(*LOCALEUTF) is specified on the
| compilation command, the user may need to convert any resulting EBCDIC
| character strings to the correct CCSID.
Return Value
This example shows how exceptions from MI library functions can be monitored
and handled using a signal handling function. The signal handler
my_signal_handler is registered before the rslvsp() function signals a 0x2201
exception. When a SIGSEGV signal is raised, the signal handler is called. If an
0x2201 exception occurred, the signal handler calls the QUSRCRTS API to create a
space.
#include <signal.h>
#include <QSYSINC/MIH/RSLVSP>
#include <QSYSINC/H/QUSCRTUS>
#include <string.h>
_INTRPT_Hndlr_Parms_T excp_data;
int error_code = 0;
Related Information
v “signal() — Handle Interrupt Signals” on page 330
v “<except.h>” on page 4
Threadsafe: Yes.
Description
The gets() function reads a line from the standard input stream stdin and stores
it in buffer. The line consists of all characters up to but not including the first
new-line character (\n) or EOF. The gets() function then replaces the new-line
character, if read, with a null character (\0) before returning the line.
Return Value
If successful, the gets() function returns its argument. A NULL pointer return
value indicates an error, or an end-of-file condition with no characters read. Use
the ferror() function or the feof() function to determine which of these
conditions occurred. If there is an error, the value that is stored in buffer is
undefined. If an end-of-file condition occurs, buffer is not changed.
#include <stdio.h>
int main(void)
{
char line[MAX_LINE];
char *result;
Related Information
v “fgets() — Read a String” on page 92
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “feof() — Test End-of-File Indicator” on page 86
v “ferror() — Test for Read/Write Errors” on page 87
v “fputs() — Write String” on page 112
v “getc() – getchar() — Read a Character” on page 142
v “puts() — Write a String” on page 224
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The getwc() function reads the next multibyte character from stream, converts it to
a wide character, and advances the associated file position indicator for stream.
The behavior of the getwc() function is affected by the LC_CTYPE category of the
current locale. If you change the category between subsequent read operations on
the same stream, undefined results can occur. Using non-wide-character functions
with the getwc() function on the same stream results in undefined behavior.
After calling the getwc() function, flush the buffer or reposition the stream pointer
before calling a write function for the stream, unless EOF has been reached. After a
write operation on the stream, flush the buffer or reposition the stream pointer
before calling the getwc() function.
Return Value
The getwc() function returns the next wide character from the input stream, or
WEOF. If an error occurs, the getwc() function sets the error indicator. If the
getwc() function encounters the end-of-file, it sets the EOF indicator. If an
encoding error occurs during conversion of the multibyte character, the getwc()
function sets errno to EILSEQ.
| For information about errno values for getwc(), see “fgetwc() — Read Wide
| Character from Stream” on page 94.
int main(void)
{
FILE *stream;
wint_t wc;
errno = 0;
while (WEOF != (wc = getwc(stream)))
printf("wc = %lc\n", wc);
if (EILSEQ == errno) {
printf("An invalid wide character was encountered.\n");
exit(1);
}
fclose(stream);
return 0;
/********************************************************
Assuming the file getwc.dat contains:
Hello world!
wc = H
wc = e
wc = l
wc = l
wc = o
:
********************************************************/
}
Related Information
v “fgetwc() — Read Wide Character from Stream” on page 94
v “getwchar() — Get Wide Character from stdin”
v “getc() – getchar() — Read a Character” on page 142
v “putwc() — Write Wide Character” on page 225
v “ungetwc() — Push Wide Character onto Input Stream” on page 401
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
Threadsafe: Yes.
The getwchar() function reads the next multibyte character from stdin, converts it
to a wide character, and advances the associated file position indicator for stdin. A
call to the getwchar() function is equivalent to a call to getwc(stdin).
Return Value
The getwchar() function returns the next wide character from stdin or WEOF. If
the getwchar() function encounters EOF, it sets the EOF indicator for the stream
and returns WEOF. If a read error occurs, the error indicator for the stream is set,
and the getwchar() function returns WEOF. If an encoding error occurs during the
conversion of the multibyte character to a wide character, the getwchar() function
sets errno to EILSEQ and returns WEOF.
| For information about errno values for getwchar(), see “fgetwc() — Read Wide
| Character from Stream” on page 94.
This example uses the getwchar() to read wide characters from the keyboard, then
prints the wide characters.
int main(void)
{
wint_t wc;
errno = 0;
while (WEOF != (wc = getwchar()))
printf("wc = %lc\n", wc);
if (EILSEQ == errno) {
printf("An invalid wide character was encountered.\n");
exit(1);
}
return 0;
/***************************************************************
Assuming you enter: abcde
wc = a
wc = b
wc = c
wc = d
wc = e
***************************************************************/
}
Related Information
v “fgetc() — Read a Character” on page 89
v “fgetwc() — Read Wide Character from Stream” on page 94
v “fgetws() — Read Wide-Character String from Stream” on page 96
v “getc() – getchar() — Read a Character” on page 142
v “getwc() — Read Wide Character from Stream” on page 147
v “ungetwc() — Push Wide Character onto Input Stream” on page 401
v “<wchar.h>” on page 17
Description
The gmtime() function breaks down the time value, in seconds, and stores it in a tm
structure, defined in <time.h>. The value time is usually obtained by a call to the
time() function.
Return Value
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime_r() — Convert Time (Restartable)”
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “mktime() — Convert Local Time” on page 204
v “setlocale() — Set Locale” on page 322
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes,
Description
| The gmtime_r() function breaks down the time value, in seconds, and stores it in
| result. result is a pointer to the tmstructure, defined in <time.h>. The value time is
| usually obtained by a call to the time() function.
Return Value
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “mktime() — Convert Local Time” on page 204
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes.
Description
Return Value
The hypot() function returns the length of the hypotenuse. If an overflow results,
hypot() sets errno to ERANGE and returns the value HUGE_VAL. If an underflow
results, hypot() sets errno to ERANGE and returns zero. The value of errno may
also be set to EDOM.
#include <math.h>
int main(void)
{
double x, y, z;
x = 3.0;
y = 4.0;
z = hypot(x,y);
The hypotenuse of the triangle with sides 3.000000 and 4.000000 is 5.000000
*/
Related Information
v “sqrt() — Calculate Square Root” on page 337
v “<math.h>” on page 7
Threadsafe: Yes.
Description
Return Value
These functions return a nonzero value if the integer satisfies the test condition, or
a zero value if it does not. The integer variable c must be representable as an
unsigned char.
This example analyzes all characters between code 0x0 and code UPPER_LIMIT,
printing A for alphabetic characters, AN for alphanumerics, U for uppercase, L for
lowercase, D for digits, X for hexadecimal digits, S for spaces, PU for punctuation,
PR for printable characters, G for graphics characters, and C for control characters.
This example prints the code if printable.
The output of this example is a 256-line table showing the characters from 0 to 255
that possess the attributes tested.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int ch;
putchar(’\n’);
}
}
Related Information
v “tolower() – toupper() — Convert Character Case” on page 395
v “isblank() — Test for Blank or Tab Character” on page 159
v “<ctype.h>” on page 3
| Threadsafe: Yes.
| Description
| The isascii() function tests if a given character, in the current locale, can be
| represented as a valid 7–bit US-ASCII character.
Return Value
| This example tests the integers from 0x7c to 0x82, and prints the corresponding
| character if the integer can be represented as a character in the 7–bit US-ASCII
| character set.
|
| #include <stdio.h>
| #include <ctype.h>
|
| int main(void)
| {
| int ch;
|
| for (ch = 0x7c; ch <= 0x82; ch++) {
| printf("%#04x ", ch);
| if (isascii(ch))
| printf("The character is %c\n", ch);
| else
| printf("Cannot be represented by an ASCII character\n");
| }
| return 0;
| }
| /************************************************
| The output should be:
|
| 0x7c The character is @
| 0x7d The character is ’
| 0x7e The character is =
| 0x7f The character is "
| 0x80 Cannot be represented by an ASCII character
| 0x81 The character is a
| 0x82 The character is b
|
| ************************************************/
|
Related Information
v “isalnum() - isxdigit() — Test Integer Value” on page 156
v “iswalnum() to iswxdigit() — Test Wide Integer Value” on page 160
Note: The isblank() function is supported only for C++, not for C.
Threadsafe: Yes.
Description
The isblank() function tests if a character is either the EBCDIC space or EBCDIC
tab character.
Return Value
The isblank() function returns nonzero if c is either the EBCDIC space character
or the EBCDIC tab character, otherwise it returns 0.
int main(void)
{
char *buf = "a b\tc";
int i;
/*************************************
The output should be
*************************************/
Threadsafe: Yes.
Description
The functions listed above, which are all declared in <wctype.h>, test a given wide
integer value.
Returned Value
These functions return a nonzero value if the wide integer satisfies the test value,
or a 0 value if it does not. The value for wc must be representable as a wide
unsigned char. WEOF is a valid input value.
Example
int main(void)
{
int wc;
putchar(’\n’);
}
}
Related Information
v “<wctype.h>” on page 17
Threadsafe: Yes.
Description
| The iswctype() function determines whether the wide character wc has the
| property wc_prop. If the value of wc is neither WEOF nor any value of the wide
| characters that corresponds to a multibyte character, the behavior is undefined. If
| the value of wc_prop is incorrect (that is, it is not obtained by a previous call to the
| wctype() function, or wc_prop has been invalidated by a subsequent call to the
| setlocale() function), the behavior is undefined.
Return Value
The iswctype() function returns true if the value of the wide character wc has the
property wc_prop.
#include <stdio.h>
#include <wctype.h>
int main(void)
{
int wc;
putchar(’\n’);
}
}
Related Information
v “wctype() — Get Handle for Character Property Classification” on page 472
v “iswalnum() to iswxdigit() — Test Wide Integer Value” on page 160
v “<wctype.h>” on page 17
Note: The _itoa function is supported only for C++, not for C.
Threadsafe: Yes.
_itoa() converts the digits of the given value to a character string that ends with a
null character and stores the result in string. The radix argument specifies the base
of value; it must be in the range 2 to 36. If radix equals 10 and value is negative, the
first character of the stored string is the minus sign (-).
Note: The space reserved for string must be large enough to hold the returned
string. The function can return up to 33 bytes including the null character
(\0).
Return Value
| When the string argument is NULL or the radix is outside the range 2 to 36, errno
| will be set to EINVAL.
This example converts the integer value -255 to a decimal, a binary, and a hex
number, storing its character representation in the array buffer.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buffer[35];
char *p;
p = _itoa(-255, buffer, 10);
printf("The result of _itoa(-255) with radix of 10 is %s\n", p);
p = _itoa(-255, buffer, 2);
printf("The result of _itoa(-255) with radix of 2\n is %s\n", p);
p = _itoa(-255, buffer, 16);
printf("The result of _itoa(-255) with radix of 16 is %s\n", p);
return 0;
}
Related Information:
v “_gcvt - Convert Floating-Point to String” on page 141
v “_itoa - Convert Integer to String” on page 163
v “_ltoa - Convert Long Integer to String” on page 177
v “_ultoa - Convert Unsigned Long Integer to String” on page 398
v “<stdlib.h>” on page 15
Format (llabs())
#include <stdlib.h>
long long int llabs(long long int i);
Threadsafe: Yes.
Description
The labs() function produces the absolute value of its long integer argument n.
The result may be undefined when the argument is equal to LONG_MIN, the
smallest available long integer. The value LONG_MIN is defined in the <limits.h>
include file.
The llabs() function returns the absolute value of its long long integer
operand.The result may be undefined when the argument is equal to
LONG_LONG_MIN, the smallest available long integer. The value
LONG_LONG_MIN is defined in the <limits.h> include file.
Return Value
The labs() function returns the absolute value of n. There is no error return value.
The llabs() function returns the absolute value of i. There is no error return value.
This example computes y as the absolute value of the long integer -41567.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
long x, y;
x = -41567L;
y = labs(x);
Related Information
v “abs() — Calculate Integer Absolute Value” on page 39
v “fabs() — Calculate Floating-Point Absolute Value” on page 81
v “<limits.h>” on page 7
Threadsafe: Yes.
Description
Return Value
The ldexp() function returns the value of x*(2exp). If an overflow results, the
function returns +HUGE_VAL for a large result or -HUGE_VAL for a small result,
and sets errno to ERANGE.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y;
int p;
x = 1.5;
p = 5;
y = ldexp(x,p);
Related Information
v “exp() — Calculate Exponential Function” on page 81
v “frexp() — Separate Floating-Point Value” on page 122
v “modf() — Separate Floating-Point Value” on page 205
v “<math.h>” on page 7
Format (lldiv())
Threadsafe: Yes. However, only the function version is threadsafe. The macro
version is NOT threadsafe.
Description
The ldiv() function calculates the quotient and remainder of the division of
numerator by denominator.
Return Value
The ldiv() function returns a structure of type ldiv_t, containing both the quotient
(long int quot) and the remainder (long int rem). If the value cannot be
represented, the return value is undefined. If denominator is 0, an exception is
raised.
The lldiv() subroutine computes the quotient and remainder of the numerator
parameter by the denominator parameter.
The lldiv() subroutine returns a structure of type lldiv_t, containing both the
quotient and the remainder. The structure is defined as:
struct lldiv_t
{
long long int quot; /* quotient */
long long int rem; /* remainder */
};
If the division is inexact, the sign of the resulting quotient is that of the algebraic
quotient, and magnitude of the resulting quotient is the largest long long integer
less than the magnitude of the algebraic quotient. If the result cannot be
represented (for example, if the denominator is 0), the behavior is undefined.
This example uses ldiv() to calculate the quotients and remainders for a set of
two dividends and two divisors.
int main(void)
{
long int num[2] = {45,-45};
long int den[2] = {7,-7};
ldiv_t ans; /* ldiv_t is a struct type containing two long ints:
’quot’ stores quotient; ’rem’ stores remainder */
short i,j;
Related Information
v “div() — Calculate Quotient and Remainder” on page 77
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The localeconv() sets the components of a structure having type struct lconv to
values appropriate for the current locale. The structure may be overwritten by
another call to localeconv(), or by calling the setlocale()function and passing
| LC_ALL, LC_UNI_ALL, LC_MONETARY, or LC_NUMERIC.
The structure contains the following elements (defaults shown are for the C locale):
Pointers to strings with a value of "" indicate that the value is not available in the
C locale or is of zero length. Elements with char types with a value of
UCHAR_MAX indicate that the value is not available in the current locale.
The n_sign_posn and p_sign_posn elements can have the following values:
Value Meaning
0 The quantity and currency_symbol are enclosed in parentheses.
1 The sign precedes the quantity and currency_symbol.
2 The sign follows the quantity and currency_symbol.
3 The sign precedes the currency_symbol.
4 The sign follows the currency_symbol.
Grouping Example
Table 1. Grouping Example
Locale Source Grouping String Number Formatted Number
−1 0x00 123456789 123456789
3 0x0300 123456789 123,456,789
3;−1 0x03FF00 123456789 123456,789
3;2;1 0x03020100 123456789 1,2,3,4,56,789
The above table was generated by locales withe the following monetary fields:
Table 3. Monetary Fields
Italy Netherlands Norway Switzerland
int_curr_symbol ″ITL.″ ″NLG″ ″NOK″ ″CHF″
currency_symbol ″L.″ ″F″ ″kr″ ″SFrs.″
mon_decimal_point ″″ ″,″ ″,″ ″.″
mon_thousands_sep ″.″ ″.″ ″.″ ″,″
mon_grouping ″\3″ ″\3″ ″\3″ ″\3″
positive_sign ″″ ″″ ″″ ″″
negative_sign ″-″ ″-″ ″-″ ″C″
int_frac_digits 0 2 2 2
frac_digits 0 2 2 2
p_cs_precedes 1 1 1 1
p_sep_by_space 0 1 0 0
n_cs_preceds 1 1 1 1
n_sep_by_space 0 1 0 0
p_sep_posn 1 1 1 1
n_sign_posn 1 4 2 2
Return Value
This example prints out the default decimal point for your locale and then the
decimal point for the LC_C_FRANCE locale.
int main(void) {
char * string;
struct lconv * mylocale;
mylocale = localeconv();
} else {
/************************************************************************
This example prints out the default decimal point for
the C locale and then the decimal point for the French
locale using a *LOCALE object called
"QSYS.LIB/MYLIB.LIB/LC_FRANCE.LOCALE".
#include <stdio.h>
#include <locale.h>
int main(void) {
char * string;
struct lconv * mylocale;
mylocale = localeconv();
Description
Return Value
The localtime() function returns a pointer to the structure result. There is no error
return value.
This example queries the system clock and displays the local time.
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “mktime() — Convert Local Time” on page 204
v “localtime_r() — Convert Time (Restartable)”
v “setlocale() — Set Locale” on page 322
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes,
Description
Return Value
The localtime_r() returns a pointer to the structure result. There is no error return
value.
This example queries the system clock and displays the local time.
int main(void)
{
struct tm newtime;
time_t ltime;
char buf[50];
ltime=time(<ime);
localtime_r(<ime, &newtime);
printf("The date and time is %s", asctime_r(&newtime, buf));
}
/************** If the local time is 3:00 p.m. May 31, 1993, **********
************************* output should be: *********************
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “mktime() — Convert Local Time” on page 204
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes.
Description
Return Value
The log() function returns the computed value. If x is negative, log()sets errno to
EDOM and may return the value -HUGE_VAL. If x is zero, log() returns the value
-HUGE_VAL, and may set errno to ERANGE.
int main(void)
{
double x = 1000.0, y;
y = log(x);
Related Information
v “exp() — Calculate Exponential Function” on page 81
v “log10() — Calculate Base 10 Logarithm”
v “pow() — Compute Power” on page 210
v “<math.h>” on page 7
Threadsafe: Yes.
Description
Return Value
int main(void)
{
double x = 1000.0, y;
y = log10(x);
Related Information
v “exp() — Calculate Exponential Function” on page 81
v “log() — Calculate Natural Logarithm” on page 175
v “pow() — Compute Power” on page 210
v “<math.h>” on page 7
Note: The _ltoa function is supported only for C++, not for C.
Threadsafe: Yes.
Description
_ltoa converts the digits of the given long integer value to a character string that
ends with a null character and stores the result in string. The radix argument
specifies the base of value; it must be in the range 2 to 36. If radix equals 10 and
value is negative, the first character of the stored string is the minus sign (-).
Note: The space allocated for string must be large enough to hold the returned
string. The function can return up to 33 bytes including the null character
(\0).
Return Value
| When the string argument is NULL or the radix is outside the range 2 to 36, errno
| will be set to EINVAL.
This example converts the integer value -255L to a decimal, a binary, and a hex
value, and stores its character representation in the array buffer.
Related Information:
v “atol() — atoll() — Convert Character String to Long or Long Long Integer” on
page 51
v “_gcvt - Convert Floating-Point to String” on page 141
v “_itoa - Convert Integer to String” on page 163
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “_ultoa - Convert Unsigned Long Integer to String” on page 398
v “wcstol() — wcstoll() — Convert Wide Character String to Long and Long Long
Integer” on page 458
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
A call to the setjmp() function causes the current stack environment to be saved in
env. A subsequent call to longjmp() restores the saved environment and returns
control to a point in the program corresponding to the setjmp()call. Processing
resumes as if the setjmp() call had just returned the given value.
All variables (except register variables) that are available to the function that
receives control contain the values they had when longjmp() was called. The
Note: Ensure that the function that calls the setjmp() function does not return
before you call the corresponding longjmp() function. Calling longjmp()
after the function calling the setjmp() function returns causes unpredictable
program behavior.
The value argument must be nonzero. If you give a zero argument for value,
longjmp() substitutes 1 in its place.
Return Value
The longjmp() function does not use the normal function call and return
mechanisms; it has no return value.
if(setjmp(mark) != 0) ...
When the system first performs the if statement, it saves the environment in mark
and sets the condition to FALSE because the setjmp() function returns a 0 when it
saves the environment. The program prints the message:
The subsequent call to function p() tests for a local error condition, which can
cause it to call the longjmp() function. Then, control returns to the original
setjmp() function using the environment saved in mark. This time, the condition is
TRUE because -1 is the return value from the longjmp() function. The example
then performs the statements in the block, prints longjmp() has been called, calls
the recover() function, and leaves the program.
jmp_buf mark;
void p(void);
void recover(void);
int main(void)
{
if (setjmp(mark) != 0)
{
printf("longjmp has been called\n");
recover();
exit(1);
}
printf("setjmp has been called\n");
printf("Calling function p()\n");
p();
printf("This point should never be reached\n");
}
void p(void)
{
printf("Calling longjmp() from inside function p()\n");
longjmp(mark, -1);
printf("This point should never be reached\n");
}
void recover(void)
{
printf("Performing function recover()\n");
}
/*******************Output should be as follows: **********************
setjmp has been called
Calling function p()
Calling longjmp() from inside function p()
longjmp has been called
Performing function recover()
**********************************************************************/
Related Information
v “setjmp() — Preserve Environment” on page 321
v “<setjmp.h>” on page 13
Threadsafe: Yes.
Description
| The malloc() function reserves a block of storage of size bytes. Unlike the calloc()
| function, malloc() does not initialize all elements to 0. The maximum size for a
| non-Teraspace malloc() is 16711568 byes.
Return Value
The malloc() function returns a pointer to the reserved space. The storage space to
which the return value points is suitably aligned for storage of any type of object.
The return value is NULL if not enough storage is available, or if size was specified
as zero.
This example prompts for the number of array entries you want and then reserves
enough space in storage for the entries. If malloc() was successful, the example
assigns values to the entries and prints out each entry; otherwise, it prints out an
error.
int main(void)
{
long * array; /* start of the array */
long * index; /* index variable */
int i; /* index variable */
int num; /* number of entries of the array */
Related Information
v “calloc() — Reserve and Initialize Storage” on page 57
v “free() — Release Storage Blocks” on page 118
v “realloc() — Change Reserved Storage Block Size” on page 247
v “<stdlib.h>” on page 15
Description
The mblen() function determines the length in bytes of the multibyte character
pointed to by string. n represents the maximum number of bytes examined.
Return Value
Note: The mblen(), mbtowc(), and wctomb() functions use their own statically
allocated storage and are therefore not restartable. However, mbrlen(),
mbrtowc(), and wcrtomb() are restartable.
This example uses mblen() and mbtowc() to convert a multibyte character into a
single wide character.
| #include <stdio.h>
| #include <stdlib.h>
|
| int length, temp;
| char string [6] = "w";
| wchar_t arr[6];
|
| int main(void)
|
| {
| /* Initialize internal state variable */
| length = mblen(NULL, MB_CUR_MAX);
|
| /* Set string to point to a multibyte character */
| length = mblen(string, MB_CUR_MAX);
| temp = mbtowc(arr,string,length);
| arr[1] = L’\0’;
| printf("wide character string: %ls\n", arr);
| }
Related Information
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)”
v “mbtowc() — Convert Multibyte Character to a Wide Character” on page 196
v “mbstowcs() — Convert a Multibyte String to a Wide Character String” on page
192
v “strlen() — Determine String Length” on page 358
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wctomb() — Convert Wide Character to Multibyte Character” on page 469
v “<stdlib.h>” on page 15
Description
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
| If s is a null pointer and if the active locale allows mixed-byte strings, the mbrlen()
| function returns nonzero. If s is a null pointer and if the active locale does not
| allow mixed-byte strings, zero will be returned.
If s is not a null pointer, the mbrlen() function returns one of the following:
0 If s is a NULL string (s points to the NULL character).
positive
If the next n or fewer bytes comprise a valid multibyte character. The value
returned is the number of bytes that comprise the multibyte character.
(size_t)-1
If s does not point to a valid multibyte character.
(size_t)-2
If the next n or fewer bytes contribute to an incomplete but potentially
valid character and all n bytes have been processed
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <errno.h>
sl += length;
sl += length;
}
/* The output should look like this:
length = 1, state = 0
MB_CUR_MAX: 1
length = 1, state = 0
MB_CUR_MAX: 4
length = 3, state = 2
length = 3, state = 0
length = 1, state = 0
*/
* * * End of File * * *
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbtowc() — Convert Multibyte Character to a Wide Character” on page 196
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “setlocale() — Set Locale” on page 322
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<locale.h>” on page 7
v “<wchar.h>” on page 17
Description
If s is not a null pointer, the mbrtowc() function determines the number of bytes
that are in the multibyte character (and any leading shift sequences) pointed to by
s, produces the value of the corresponding multibyte character and if pwc is not a
null pointer, stores that value in the object pointed to by pwc. If the corresponding
multibyte character is the null wide character, the resulting state will be reset to
the initial conversion state.
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
If s is a null pointer, the mbrtowc() function returns the number of bytes necessary
to enter the initial shift state. The value returned must be less than the
MB_CUR_MAX macro.
If s is not a null pointer, the mbrtowc() function returns one of the following:
0 If the next n or fewer bytes form the multibyte character that corresponds
to the null wide character.
positive
If the next n or fewer bytes form a valid multibyte character. The value
returned is the number of bytes that constitute the multibyte character.
(size_t)-2
If the next n bytes form an incomplete (but potentially valid) multibyte
character, and all n bytes have been processed. It is unspecified whether
this can occur when the value of n is less than the value of the
MB_CUR_MAX macro.
(size_t)-1
If an encoding error occurs (when the next n or fewer bytes do not form a
complete and correct multibyte character). The value of the macro EILSEQ
is stored in errno, but the conversion state is unchanged.
| Note: When a -2 value is returned, the string could contain redundant shift-out
| and shift-in characters or a partial UTF-8 character. To continue processing
| the multibyte string, increment the pointer by the value n, and call
| mbrtowc() again.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <errno.h>
int main(void)
{
int length, sl = 0;
char string[10];
wchar_t buffer[10];
mbstate_t ps = 0;
memset(string, ’\0’, 10);
string[0] = 0xC1;
string[1] = 0x0E;
string[2] = 0x41;
string[3] = 0x71;
string[4] = 0x41;
string[5] = 0x72;
string[6] = 0x0F;
string[7] = 0xC2;
/* In this first example we will convert */
/* a multibyte character when the CCSID of locale */
/* associated with LC_CTYPE is 37. */
/* For single byte cases the state will always */
/* remain in the initial state 0 */
sl += length;
sl += length;
sl += length;
}
/* The output should look like this:
length = 1, state = 0
MB_CUR_MAX: 1
length = 1, state = 0
MB_CUR_MAX: 4
length = 3, state = 2
length = 3, state = 0
length = 1, state = 0
*/
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)” on page
183
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “setlocale() — Set Locale” on page 322
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<locale.h>” on page 7
v “<wchar.h>” on page 17
Threadsafe: Yes
Description
If ps is not a null pointer, the mbsinit() function specifies whether the pointed to
mbstate_t object describes an initial conversion state.
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
This example checks the conversion state to see if it is the initial state.
#include <stdio.h>
#include <wchar.h>
#include <stdlib.h>
main()
{
char *string = "ABC";
mbstate_t state = 0;
wchar_t wc;
int rc;
Related Information
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)” on page
183
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “setlocale() — Set Locale” on page 322
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<locale.h>” on page 7
Description
If dst is not a null pointer, the pointer object pointed to by src will be assigned
either a null pointer (if conversion stopped due to reaching an ending null
character) or the address just past the last multibyte character converted. If
conversion stopped due to reaching an ending null character, the initial conversion
state is described.
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
If the input string does not begin with a valid multibyte character, an encoding
error occurs, the mbsrtowcs() function stores the value of the macro EILSEQ in
errno, and returns (size_t) -1, but the conversion state will be unchanged.
Otherwise, it returns the number of multibyte characters successfully converted,
which is the same as the number of array elements modified when dst is not a null
pointer.
#define SIZE 10
int main(void)
{
char mbs1[] = "abc";
char mbs2[] = "\x81\x41" "m" "\x81\x42";
const char *pmbs1 = mbs1;
const char *pmbs2 = mbs2;
mbstate_t ss1 = 0;
mbstate_t ss2 = 0;
wchar_t wcs1[SIZE], wcs2[SIZE];
/*******************************************************
The output should be similar to:
Also, see the examples for “mbrtowc() — Convert a Multibyte Character to a Wide
Character (Restartable)” on page 186.
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)” on page
183
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “mbstowcs() — Convert a Multibyte String to a Wide Character String”
v “setlocale() — Set Locale” on page 322
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<locale.h>” on page 7
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The mbstowcs() function determines the length of the sequence of the multibyte
characters pointed to by string. It then converts the multibyte character string that
begins in the initial shift state into a wide character string, and stores the wide
characters into the buffer that is pointed to by pwc. A maximum of n wide
characters are written.
The behavior of this function is affected by the LC_CTYPE category of the current
locale. If the program is compiled with LOCALETYPE(*LOCALE), and the CCSID
that is associated with locale is single-byte, all the multibyte characters are
assumed to be single-byte, and are converted to wide characters like this: 0xC1 is
converted to 0x00C1. If CCSID of the locale is a multibyte CCSID, then if the
multibyte character is a single-byte character, it is converted as is above. If the
multibyte character is a double-byte character, (characters between shiftout 0x0e
and shiftin 0x0f), the double-byte characters are copied directly, stripping off the
shiftout and shiftin characters. For example, 0x0e41710f is converted to 0x4171.
Return Value
The mbstowcs() function returns the number of wide characters generated, not
including any ending null wide characters. If a multibyte character that is not valid
is encountered, the function returns (size_t)-1.
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <errno.h>
int main(void)
{
int length, sl = 0;
char string[10];
char string2[] = "ABC";
wchar_t buffer[10];
memset(string, ’\0’, 10);
string[0] = 0xC1;
string[1] = 0x0E;
string[2] = 0x41;
string[3] = 0x71;
string[4] = 0x41;
string[5] = 0x72;
string[6] = 0x0F;
string[7] = 0xC2;
/* In this first example we will convert */
/* a multibyte character when the CCSID of locale */
/* associated with LC_CTYPE is 37. */
}
/* The output should look like this:
length = 3
length = 4
*/
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <wchar.h>
#include <errno.h>
int main(void)
{
int length, sl = 0;
char string[10];
char string2[] = "ABC";
wchar_t buffer[10];
memset(string, ’\0’, 10);
string[0] = 0xC1;
string[1] = 0x0E;
string[2] = 0x41;
string[3] = 0x71;
string[4] = 0x41;
string[5] = 0x72;
string[6] = 0x0F;
string[7] = 0xC2;
/* In this first example we will convert */
/* a multibyte character when the CCSID of locale */
/* associated with LC_CTYPE is 37. */
length = 3
length = 4
*/
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
Description
The mbtowc() function first determines the length of the multibyte character
pointed to by string. It then converts the multibyte character to a wide character as
described in mbstowcs. A maximum of n bytes are examined.
The behavior of this function is affected by the LC_CTYPE category of the current
locale.
Return Value
This example uses the mblen() and mbtowc() functions to convert a multibyte
character into a single wide character.
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbstowcs() — Convert a Multibyte String to a Wide Character String” on page
192
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wctomb() — Convert Wide Character to Multibyte Character” on page 469
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The memchr() function searches the first count bytes of buf for the first occurrence
of c converted to an unsigned character. The search continues until it finds c or
examines count bytes.
Return Value
The memchr() function returns a pointer to the location of c in buf. It returns NULL
if c is not within the first count bytes of buf.
This example finds the first occurrence of “x” in the string that you provide. If it is
found, the string that starts with that character is printed.
if ( argc != 2 )
printf( "Usage: %s string\n", argv[0] );
else
{
if ((result = (char *) memchr( argv[1], ’x’, strlen(argv[1])) ) != NULL)
printf( "The string starting with x is %s\n", result );
else
printf( "The letter x cannot be found in the string\n" );
}
}
Related Information
v “memcmp() — Compare Buffers”
v “memcpy() — Copy Bytes” on page 199
v “memmove() — Copy Bytes” on page 202
v “wmemchr() —Locate Wide Character in Wide-Character Buffer” on page 476
v “memset() — Set Bytes to Value” on page 203
v “strchr() — Search for Character” on page 342
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The memcmp() function compares the first count bytes of buf1 and buf2.
Return Value
The memcmp() function returns a value indicating the relationship between the two
buffers as follows:
Value Meaning
Less than 0 buf1 less than buf2
0 buf1 identical to buf2
Greater than 0 buf1 greater than buf2
This example compares first and second arguments passed to main() to determine
which, if either, is greater.
#include <stdio.h>
#include <string.h>
if ( argc != 3 )
{
printf( "Usage: %s string1 string2\n", argv[0] );
}
else
{
/* Determine the length to be used for comparison */
if (strlen( argv[1] ) < strlen( argv[2] ))
len = strlen( argv[1] );
else
len = strlen( argv[2] );
Related Information
v “memchr() — Search Buffer” on page 197
v “memcpy() — Copy Bytes”
v “wmemcmp() —Compare Wide-Character Buffers” on page 477
v “memmove() — Copy Bytes” on page 202
v “memset() — Set Bytes to Value” on page 203
v “strcmp() — Compare Strings” on page 343
v “<string.h>” on page 16
Description
The memcpy() function copies count bytes of src to dest. The behavior is undefined if
copying takes place between objects that overlap. The memmove() function allows
copying between objects that may overlap.
Return Value
#include <string.h>
#include <stdio.h>
#define MAX_LEN 80
int main(void)
{
printf( "Before memcpy, target is \"%s\"\n", target );
memcpy( target, source, sizeof(source));
printf( "After memcpy, target becomes \"%s\"\n", target );
}
Related Information
v “memchr() — Search Buffer” on page 197
v “memcmp() — Compare Buffers” on page 198
v “wmemcpy() —Copy Wide-Character Buffer” on page 478
v “memmove() — Copy Bytes” on page 202
v “memset() — Set Bytes to Value” on page 203
v “strcpy() — Copy Strings” on page 347
v “<string.h>” on page 16
| Note: The memicmp function is available for C++ programs. It is available for C
| only when the program defines the __cplusplus__strings__ macro.
Description
The memicmp function compares the first cnt bytes of buf1 and buf2 without regard
to the case of letters in the two buffers. The function converts all uppercase
characters into lowercase and then performs the comparison.
Return Value
This example copies two strings that each contain a substring of 29 characters that
are the same except for case. The example then compares the first 29 bytes without
regard to case.
#include <stdio.h>
#include <string.h>
char first[100],second[100];
int main(void)
{
int result;
strcpy(first, "Those Who Will Not Learn From History");
strcpy(second, "THOSE WHO WILL NOT LEARN FROM their mistakes");
printf("Comparing the first 29 characters of two strings.\n");
result = memicmp(first, second, 29);
printf("The first 29 characters of String 1 are ");
if (result < 0)
printf("less than String 2.\n");
else
if (0 == result)
printf("equal to String 2.\n");
else
printf("greater than String 2.\n");
return 0;
}
Related Information:
v “memchr() — Search Buffer” on page 197
v “memcmp() — Compare Buffers” on page 198
v “memcpy() — Copy Bytes” on page 199
v “memmove() — Copy Bytes” on page 202
v “memset() — Set Bytes to Value” on page 203
v “strcmp() — Compare Strings” on page 343
v “strcmpi() - Compare Strings Without Case Sensitivity” on page 345
v “stricmp() - Compare Strings without Case Sensitivity” on page 357
Threadsafe: Yes.
Description
The memmove() function copies count bytes of src to dest. This function allows
copying between objects that may overlap as if src is first copied into a temporary
array.
Return Value
This example copies the word ″shiny″ from position target + 2 to position target +
8.
#include <string.h>
#include <stdio.h>
#define SIZE 21
Related Information
v “memchr() — Search Buffer” on page 197
v “memcmp() — Compare Buffers” on page 198
v “wmemmove() — Copy Wide-Character Buffer” on page 479
v “memcpy() — Copy Bytes” on page 199
v “memset() — Set Bytes to Value” on page 203
Threadsafe: Yes.
Description
The memset() function sets the first count bytes of dest to the value c. The value of c
is converted to an unsigned character.
Return Value
This example sets 10 bytes of the buffer to A and the next 10 bytes to B.
#include <string.h>
#include <stdio.h>
#define BUF_SIZE 20
int main(void)
{
char buffer[BUF_SIZE + 1];
char *string;
memset(buffer, 0, sizeof(buffer));
string = (char *) memset(buffer,’A’, 10);
printf("\nBuffer contents: %s\n", string);
memset(buffer+10, ’B’, 10);
printf("\nBuffer contents: %s\n", buffer);
}
Related Information
v “memchr() — Search Buffer” on page 197
v “memcmp() — Compare Buffers” on page 198
v “memcpy() — Copy Bytes” on page 199
v “memmove() — Copy Bytes” on page 202
v “wmemset() — Set Wide Character Buffer to a Value” on page 480
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The values of some structure elements pointed to by time are not restricted to the
ranges shown for gmtime().
The values of tm_wday and tm_yday passed to mktime() are ignored and are
assigned their correct values on return.
Return Value
| The mktime() function returns Universal Coordinate Time (UTC) having type
| time_t. The value (time_t)(-1) is returned if the Universal Coordinate Time cannot
| be represented.
This example prints the day of the week that is 40 days and 16 hours from the
current date.
int main(void)
{
time_t t1, t3;
struct tm *t2;
t1 = time(NULL);
t2 = localtime(&t1);
t2 -> tm_mday += 40;
t2 -> tm_hour += 16;
t3 = mktime(t2);
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
Threadsafe: Yes.
Description
The modf() function breaks down the floating-point value x into fractional and
integral parts. The signed fractional portion of x is returned. The integer portion is
stored as a double value pointed to by intptr. Both the fractional and integral parts
are given the same sign as x.
Return Value
This example breaks the floating-point number −14.876 into its fractional and
integral components.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x, y, d;
x = -14.876;
y = modf(x, &d);
x = -14.876000
Integral part = -14.000000
Fractional part = -0.876000
*/
Related Information
v “fmod() — Calculate Floating-Point Remainder” on page 99
v “frexp() — Separate Floating-Point Value” on page 122
v “ldexp() — Multiply by a Power of Two” on page 166
v “<math.h>” on page 7
Threadsafe: No.
Description
The nl_langinfo() function retrieves from the current locale the string that
describes the requested information specified by item.
The retrieval of the following information from the current locale is supported:
Item Explanation
| CODESET CCSID of locale in character form
D_T_FMT string for formatting date and time
D_FMT date format string
T_FMT time format string
T_FMT_AMPM a.m. or p.m. time format string
Returned Value
If the item is not valid, the function returns a pointer to an empty string.
This example retrieves the name of the codeset using the nl_langinfo() function.
#include <langinfo.h>
#include <locale.h>
#include <nl_types.h>
#include <stdio.h>
int main(void)
{
printf("Current codeset is %s\n", nl_langinfo(CODESET));
return 0;
}
/************************************************************************
Current codeset is 37
************************************************************************/
Related Information
v “localeconv() — Retrieve Information from the Environment” on page 168
v “setlocale() — Set Locale” on page 322
v “<langinfo.h>” on page 7
v “<nl_types.h>” on page 8
Threadsafe: Yes.
Description
The perror() function prints an error message to stderr. If string is not NULL and
does not point to a null character, the string pointed to by string is printed to the
standard error stream, followed by a colon and a space. The message associated
with the value in errno is then printed followed by a new-line character.
To produce accurate results, you should ensure that the perror() function is called
immediately after a library function returns with an error; otherwise, subsequent
calls may alter the errno value.
Return Value
This example tries to open a stream. If fopen() fails, the example prints a message
and ends the program.
int main(void)
{
FILE *fh;
Related Information
v “clearerr() — Reset Error Indicators” on page 64
v “ferror() — Test for Read/Write Errors” on page 87
v “strerror() — Set Pointer to Run-Time Error Message” on page 350
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
Return Value
int main(void)
{
double x, y, z;
x = 2.0;
y = 3.0;
z = pow(x,y);
Related Information
v “exp() — Calculate Exponential Function” on page 81
v “log() — Calculate Natural Logarithm” on page 175
v “log10() — Calculate Base 10 Logarithm” on page 176
v “sqrt() — Calculate Square Root” on page 337
v “<math.h>” on page 7
Threadsafe: Yes.
Description
The printf() function formats and prints a series of characters and values to the
standard output stream stdout. Format specifications, beginning with a percent
sign (%), determine the output format for any argument-list following the
format-string. The format-string is a multibyte character string beginning and ending
in its initial shift state.
The format-string is read left to right. When the first format specification is found,
the value of the first argument after the format-string is converted and output
according to the format specification. The second format specification causes the
second argument after the format-string to be converted and output, and so on
through the end of the format-string. If there are more arguments than there are
format specifications, the extra arguments are evaluated and ignored. The results
are undefined if there are not enough arguments for all the format specifications.
Only 15 significant digits are guaranteed for conversions of floating point numbers.
Conversions can be applied to the nth argument after the format-string in the
argument list, rather than to the next unused argument. In this case, the conversion
character % is replaced by the sequence %n$, where n is a decimal integer in the
range 1 thru NL_ARGMAX, giving the position of the argument in the argument
list. This feature provides for the definition of format strings that select arguments
in an order appropriate to specific languages.
| % arg-number$ type
flags width . precision h
L
l
ll
The arg-number is a positive integer constant where 1 refers to the first entry in
the argument-list. Arg-number may not be greater than the number of entries in
the argument-list, or else the results are undefined. Arg-number also may not be
greater than NL_ARGMAX.
Each field of the format specification is discussed in detail below. If a percent sign
(%) is followed by a character that has no meaning as a format field, the character
is simply copied to stdout. For example, to print a percent sign character, use %%.
The type characters and their meanings are given in the following table:
|| Character Argument Output Format
| d, i Integer Signed decimal integer.
| u Integer Unsigned decimal integer.
| o Integer Unsigned octal integer.
| x Integer Unsigned hexadecimal integer, using abcdef.
| X Integer Unsigned hexadecimal integer, using ABCDEF.
| D(n,p) Packed decimal It has the format [−] dddd.dddd where the number of
| digits after the decimal point is equal to the precision
| of the specification. If the precision is missing, the
| default is p; if the precision is zero, and the # flag is
| not specified, no decimal point character appears. If
| the n and the p are *, an argument from the argument
| list supplies the value. n and p must precede the value
| being formatted in the argument list. At least one
| character appears before a decimal point. The value is
| rounded to the appropriate number of digits.
| f Double Signed value having the form [-]dddd.dddd, where dddd
| is one or more decimal digits. The number of digits
| before the decimal point depends on the magnitude of
| the number. The number of digits after the decimal
| point is equal to the requested precision.
| e Double Signed value having the form [-]d.dddd e[sign]ddd,
| where d is a single-decimal digit, dddd is one or more
| decimal digits, ddd is 2 or 3 decimal digits, and sign is
| + or −.
The following list shows the format of the printed values for iSeries pointers, and
gives a brief description of the components of the printed values.
The following restrictions apply to pointer printing and scanning on the iSeries
system:
v If a pointer is printed out and scanned back from the same activation group, the
scanned back pointer will be compared equal to the pointer printed out.
v If a scanf() family function scans a pointer that was printed out by a different
activation group, the scanf() family function will set the pointer to NULL.
| v If a pointer is printed out in a Teraspace environment, just the hexadecimal
| value of the pointer is printed out. These results are the same as when using
| %#p.
See the WebSphere Development Studio: ILE C/C++ Programmer’s Guide for more
information about using iSeries pointers.
The flag characters and their meanings are as follows (notice that more than one
flag can appear in a format specification):
|| Flag Meaning Default
| - Left-justify the result within the field width. Right-justify.
For the ls type, width is specified in bytes. If the number of bytes in the output
value is less than the specified width, single-byte blanks are added on the left or
the right (depending on whether the - flag is specified) until the minimum width is
reached.
The precision specification can be an asterisk (*), in which case an argument from
the argument list supplies the value. The precision argument must precede the
value being formatted in the argument list.
The interpretation of the precision value and the default when the precision is
omitted depend on the type, as shown in the following table:
Table 4. Values of Precision
Type Meaning Default
i Precision specifies the minimum number of If precision is 0 or
d digits to be printed. If the number of digits in omitted entirely, or if
u the argument is less than precision, the output the period (.) appears
o value is padded on the left with zeros. The without a number
x value is not truncated when the number of following it, the
X digits exceeds precision. precision is set to 1.
f Precision specifies the number of digits to be Default precision for f, e
D(n,p) printed after the decimal point. The last digit and E is six. Default
e printed is rounded. precision for D(n,p) is p.
E If precision is 0 or the
period appears without
a number following it,
no decimal point is
printed.
g Precision specifies the maximum number of All significant digits
G significant digits printed. are printed. Default
precision is six.
c No effect. The character is
printed.
lc No effect. The wchar_t character
is converted and
resulting mulitbyte
character is printed.
s Precision specifies the maximum number of Characters are printed
characters to be printed. Characters in excess of until a null character is
precision are not printed. encountered.
ls Precision specifies the maximum number of wchar_t characters are
bytes to be printed. Bytes in excess of precision converted and resulting
are not printed; however, multibyte integrity is multibyte characters are
always preserved. printed.
Return Value
| The printf() function returns the number of bytes printed. The value of errno
| may be set to:
| Value Meaning
| Note: The radix character for the printf() function is locale sensitive. The radix
| character is the decimal point to be used for the #flag character of the
| format string parameter for the format types f, D(n,p), e, E, g, and G.
int main(void)
{
char ch = ’h’, *string = "computer";
int count = 234, hex = 0x10, oct = 010, dec = 10;
double fp = 251.7366;
wchar_t wc = (wchar_t)0x0058;
wchar_t ws[4];
printf("1234567890123%n4567890123456789\n\n", &count);
printf("Value of count should be 13; count = %d\n\n", count);
printf("%10c%5c\n", ch, ch);
printf("%25s\n%25.4s\n\n", string, string);
printf("%f %.2f %e %E\n\n", fp, fp, fp, fp);
printf("%i %i %i\n\n", hex, oct, dec);
}
/***************** Output should be similar to: *****************
12345678901234567890123456789
h h
computer
comp
16 8 10
*******************************************************************/
setlocale(LC_ALL,
printf("%lc %ls\n\n",wc,ws);
printf("%lc %.4ls\n\n",wc,ws);
printf("%lc %#.2ls\n\n",wc,ws);
X ABC
X AB
*******************************************************************/
Example that uses printf()
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
/* This program is compile LOCALETYPE(*LOCALE) and */
/* SYSIFCOPT(*IFSIO) */
int main(void)
{
wchar_t wc = (wchar_t)0x00C4; /* D */
wchar_t ws[4];
ws[0] = (wchar_t)0x00C1; /* A */
ws[1] = (wchar_t)0x00C2; /* B */
ws[2] = (wchar_t)0x00C3; /* C */
ws[3] = (wchar_t)0x0000;
/* The output displayed is CCSID 37 */
printf("%lc %ls\n\n",wc,ws);
setlocale(LC_ALL,
"/QSYS.lib/JA_JP.LOCALE"); /* a CCSID 5026 locale */
printf("%lc %ls\n\n",wc,ws);
printf("%lc %.4ls\n\n",wc,ws);
printf("%lc %#.2ls\n\n",wc,ws);
D ABC
*******************************************************************/
Related Information
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “fscanf() — Read Formatted Data” on page 123
v “scanf() — Read Data” on page 313
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “sscanf() — Read Data” on page 339
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “wprintf() — Format Data as Wide Characters and Print” on page 481
v “<stdio.h>” on page 14
Threadsafe: No. #undef putc or #undef putchar allows the putc or putchar
function to be called instead of the macro version of these functions. The functions
are threadsafe.
Description
The putc() function converts c to unsigned char and then writes c to the output
stream at the current position. The putchar() is equivalent to putc(c, stdout).
The putc() function can be defined as a macro so the argument can be evaluated
multiple times.
The putc() and putchar() functions are not supported for files opened with
type=record.
Return Value
The putc() and putchar() functions return the character written. A return value of
EOF indicates an error.
This example writes the contents of a buffer to a data stream. In this example, the
body of the for statement is null because the example carries out the writing
operation in the test expression.
#define LENGTH 80
int main(void)
{
FILE *stream = stdout;
int i, ch;
char buffer[LENGTH + 1] = "Hello world";
Hello world
*/
Related Information
v “fputc() — Write Character” on page 109
v “fwrite() — Write Items” on page 136
v “getc() – getchar() — Read a Character” on page 142
v “puts() — Write a String” on page 224
v “putwc() — Write Wide Character” on page 225
v “putwchar() — Write Wide Character to stdout” on page 227
v “<stdio.h>” on page 14
Threadsafe: Yes,
Description
is not valid because of the blank between PATH and NAME. Similarly,
PATH=NAME=/my_lib/joe_user
is not valid because of the equal symbol between PATH and NAME. The system
interprets all characters following the first equal symbol as being the value of the
environment variable.
Return Value
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *pathvar;
if (-1 == putenv("PATH=/:/home/userid")) {
printf("putenv failed \n");
return EXIT_FAILURE;
}
/* getting and printing the current environment path */
pathvar = getenv("PATH");
printf("The current path is: %s\n", pathvar);
return 0;
}
/**********************************************************
The output should be:
Related Information
v “getenv() — Search for Environment Variables” on page 144
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The puts() function writes the given string to the standard output stream stdout;
it also appends a new-line character to the output. The ending null character is not
written.
Return Value
The puts() function returns EOF if an error occurs. A nonnegative return value
indicates that no error has occurred.
#include <stdio.h>
int main(void)
{
if ( puts("Hello World") == EOF )
printf( "Error in puts\n" );
}
Hello World
*/
Related Information
v “fputs() — Write String” on page 112
v “fputws() — Write Wide-Character String” on page 115
v “gets() — Read a Line” on page 146
v “putc() – putchar() — Write a Character” on page 221
v “putwc() — Write Wide Character”
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
| The putwc() function writes the wide character wc to the stream at the current
| position. It also advances the file position indicator for the stream appropriately.
| The putwc() function is equivalent to the fputwc() function except that some
| platforms implement putwc() as a macro. Therefore, for portability, the stream
| argument to putwc() should not be an expression with side effects.
Return Value
The putwc() function returns the wide character written. If a write error occurs, it
sets the error indicator for the stream and returns WEOF. If an encoding error
occurs when a wide character is converted to a multibyte character, the putwc()
function sets errno to EILSEQ and returns WEOF.
| For information about errno values for putwc(), see “fputc() — Write Character”
| on page 109.
The following example uses the putwc() function to convert the wide characters in
wcs to multibyte characters and write them to the file putwc.out.
#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <errno.h>
int main(void)
{
FILE *stream;
wchar_t *wcs = L"A character string.";
int i;
/***************************************************************
The output file putwc.out should contain :
A character string.
***************************************************************/
}
Threadsafe: Yes.
Description
The behavior of this function is affected by the LC_CTYPE category of the current
locale. Using a non-wide-character function with the putwchar() function on the
same stream results in undefined behavior. After calling the putwchar()function,
flush the buffer or reposition the stream pointer before calling a write function for
the stream, unless EOF has been reached. After a write operation on the stream,
flush the buffer or reposition the stream pointer before calling the putwchar()
function.
Return Value
The putwchar() function returns the wide character written. If a write error occurs,
the putwchar() function sets the error indicator for the stream and returns WEOF.
If an encoding error occurs when a wide character is converted to a multibyte
character, the putwchar() function sets errno to EILSEQ and returns WEOF.
| For information about errno values for putwc(), see “fputc() — Write Character”
| on page 109.
This example uses the putwchar() function to write the string in wcs.
int main(void)
{
wchar_t *wcs = L"A character string.";
int i;
/**************************************************************
The output should be similar to :
A character string.
**************************************************************/
}
Related Information
v “fputc() — Write Character” on page 109
v “fputwc() — Write Wide Character” on page 113
v “fputws() — Write Wide-Character String” on page 115
v “getwchar() — Get Wide Character from stdin” on page 149
v “putc() – putchar() — Write a Character” on page 221
v “putwc() — Write Wide Character” on page 225
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The qsort() function sorts an array of num elements, each of width bytes in size.
The base pointer is a pointer to the array to be sorted. The qsort() function
overwrites this array with the sorted elements.
The compare argument is a pointer to a function you must supply that takes a
pointer to the key argument and to an array element, in that order. The qsort()
function calls this function one or more times during the search. The function must
compare the key and the element and return one of the following values:
Value Meaning
Less than 0
key less than element
0 key equal to element
Greater than 0
key greater than element
The sorted array elements are stored in ascending order, as defined by your
compare function. You can sort in reverse order by reversing the sense of “greater
than” and “less than” in compare. The order of the elements is unspecified when
two elements compare equally.
Return Value
This example sorts the arguments (argv) in ascending lexical sequence, using the
comparison function compare() supplied in the example.
arguments
correctly?
really
sort
the
this
Does
*/
Related Information
v “bsearch() — Search Arrays” on page 54
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The QXXCHGDA() function allows you to change the data area specified by dtaname,
starting at position offset, with the data in the user buffer pointed to by dtaptr of
length len. The structure dtaname contains the names of the data area and the
library that contains the data area. The values that can be specified for the data
area name are:
| Note: This function accepts and returns only EBCDIC character strings. When
| LOCALETYPE(*LOCALEUTF) is specified on the compilation command, the
| user may need to convert any non-EBCDIC character strings to EBCDIC
| before calling this function and convert any resulting EBCDIC character
| strings to the correct CCSID.
#include <stdio.h>
#include <xxdtaa.h>
#define START 1
#define LENGTH 8
int main(void)
{
char newdata[LENGTH] = "new data";
Related Information
v “QXXRTVDA() —Retrieve Data Area” on page 236
Threadsafe: Yes.
Description
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char pptr[10];
int digits = 8, fraction = 6;
double value = 3.141593;
Related Information
v “QXXDTOZ() —Convert Double to Zoned Decimal”
v “QXXITOP() —Convert Integer to Packed Decimal” on page 233
v “QXXITOZ() —Convert Integer to Zoned Decimal” on page 233
v “QXXPTOD() —Convert Packed Decimal to Double” on page 234
v “QXXPTOI() —Convert Packed Decimal to Integer” on page 235
v “QXXZTOD() —Convert Zoned Decimal to Double” on page 237
v “QXXZTOI() —Convert Zoned Decimal to Integer” on page 238
Threadsafe: Yes.
Description
The QXXDTOZ function converts the double value specified in value to a zoned
decimal number with digits total digits, and fraction fractional digits. The result is
stored in the array pointed to by zptr.
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char zptr[10];
int digits = 8, fraction = 6;
double value = 3.141593;
Threadsafe: Yes.
Description
The QXXITOP function converts the integer specified in value to a packed decimal
number with digits total digits, and fraction fractional digits. The result is stored in
the array pointed to by pptr.
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char pptr[10];
int digits = 3, fraction = 0;
int value = 116;
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
v “QXXITOZ() —Convert Integer to Zoned Decimal”
v “QXXPTOD() —Convert Packed Decimal to Double” on page 234
v “QXXPTOI() —Convert Packed Decimal to Integer” on page 235
v “QXXZTOD() —Convert Zoned Decimal to Double” on page 237
v “QXXZTOI() —Convert Zoned Decimal to Integer” on page 238
Threadsafe: Yes.
Description
The QXXITOZ function converts the integer specified in value to a zoned decimal
number with digits total digits, and fraction fractional digits. The result is stored in
the array pointed to by zptr.
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char zptr[10];
int digits = 9, fraction = 0;
int value = 111115;
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
v “QXXITOP() —Convert Integer to Packed Decimal” on page 233
v “QXXPTOD() —Convert Packed Decimal to Double”
v “QXXPTOI() —Convert Packed Decimal to Integer” on page 235
v “QXXZTOD() —Convert Zoned Decimal to Double” on page 237
v “QXXZTOI() —Convert Zoned Decimal to Integer” on page 238
Threadsafe: Yes.
Description
int main(void)
{
unsigned char pptr[10];
int digits = 8, fraction = 6;
double value = 6.123456, result;
/* First convert an integer to a packed decimal,*/
QXXDTOP(pptr, digits, fraction, value);
/* then convert it back to a double. */
result = QXXPTOD(pptr, digits, fraction);
/* result = 6.123456 */
}
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
v “QXXITOP() —Convert Integer to Packed Decimal” on page 233
v “QXXITOZ() —Convert Integer to Zoned Decimal” on page 233
v “QXXPTOI() —Convert Packed Decimal to Integer”
v “QXXZTOD() —Convert Zoned Decimal to Double” on page 237
v “QXXZTOI() —Convert Zoned Decimal to Integer” on page 238
Threadsafe: Yes.
Description
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char pptr[10];
int digits = 3, fraction = 0, value = 104, result;
/* First convert an integer to a packed decimal,*/
QXXITOP(pptr, digits, fraction, value);
/* then convert it back to an integer. */
result = QXXPTOI(pptr, digits, fraction);
/* result = 104 */
}
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
v “QXXITOP() —Convert Integer to Packed Decimal” on page 233
Threadsafe: Yes.
Description
The following typedef definition is included in the <xxdtaa.h> header file. The
character arrays are not null-ended strings so they must be blank filled.
typedef struct _DTAA_NAME_T {
char dtaa_name[10]; /* name of data area */
char dtaa_lib[10]; /* library that contains data area */
}_DTAA_NAME_T;
The QXXRTVDA() function retrieves a copy of the data area specified by dtaname
starting at position offset with a length of len. The structure dtaname contains the
names of the data area and the library that contains the data area. The values that
can be specified for the data area name are:
*LDA The contents of the local data area are to be retrieved. The library name
dtaa_lib must be blank.
*GDA The contents of the group data area are to be retrieved. The library name
dtaa_lib must be blank.
*PDA Specifies that the contents of the program initialization parameters (PIP)
data area are to be retrieved. The PIP data area is created for each
pre-started job and is a character area up to 2000 characters in length. You
cannot retrieve the PIP data area until you have acquired the requester.
The library name dtaa_lib must be blank.
data-area-name
Specifies that the contents of the data area created using the Create Data
Area (CRTDTAARA) CL command are to be retrieved. The library name
dtaa_lib must be either *LIBL, *CURLIB, or the name of the library where
the data area (data-area-name) is located. The data area is locked while the
data is being retrieved.
The parameter dtaptr is a pointer to the storage that receives the retrieved copy of
the data area. Only character data can be retrieved using QXXRTVDA.
| Note: This function accepts and returns only EBCDIC character strings. When
| LOCALETYPE(*LOCALEUTF) is specified on the compilation command, the
| user may need to convert any non-EBCDIC character strings to EBCDIC
| before calling this function and convert any resulting EBCDIC character
| strings to the correct CCSID.
#include <stdio.h>
#include <xxdtaa.h>
#define DATA_AREA_LENGTH 30
#define START 6
#define LENGTH 7
int main(void)
{
char uda_area[DATA_AREA_LENGTH];
Related Information
v “QXXCHGDA() —Change Data Area” on page 230
Threadsafe: Yes.
Description
The QXXZTOD function converts to a double, the zoned decimal number (with
digits total digits, and fraction fractional digits) pointed to by zptr. The resulting
double value is returned.
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char zptr[] = "06123456";
int digits = 8, fraction = 6;
double result;
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
Threadsafe: Yes.
Description
The QXXZTOI function converts to an integer, the zoned decimal number (with
digits total digits, and fraction fractional digits) pointed to by zptr. The resulting
integer is returned.
#include <xxcvt.h>
#include <stdio.h>
int main(void)
{
unsigned char zptr[] = "000111115";
int digits = 9, fraction = 0, result;
Related Information
v “QXXDTOP() — Convert Double to Packed Decimal” on page 231
v “QXXDTOZ() —Convert Double to Zoned Decimal” on page 232
v “QXXITOP() —Convert Integer to Packed Decimal” on page 233
v “QXXITOZ() —Convert Integer to Zoned Decimal” on page 233
v “QXXPTOD() —Convert Packed Decimal to Double” on page 234
v “QXXPTOI() —Convert Packed Decimal to Integer” on page 235
v “QXXZTOD() —Convert Zoned Decimal to Double” on page 237
Threadsafe: Yes.
The raise() functions sends the signal sig to the running program. If compiled
with SYSIFCOPT(*ASYNCSIGNAL) on the compilation command, this function
uses asynchronous signals. The asynchronous version of this function throws a
signal to the process or thread.
Return Value
This example establishes a signal handler called sig_hand for the signal SIGUSR1.
The signal handler is called whenever the SIGUSR1 signal is raised and will ignore
the first nine occurrences of the signal. On the tenth raised signal, it exits the
program with an error code of 10. Note that the signal handler must be
reestablished each time it is called.
#include <signal.h>
#include <stdio.h>
int main(void)
{
signal(SIGUSR1, sig_hand); /* set up handler for SIGUSR1 */
count++;
if (count == 10) /* ignore the first 9 occurrences of this signal */
exit(10);
else
signal(SIGUSR1, sig_hand); /* set up the handler again */
}
/* This is a program fragment and not a complete program */
Related Information
v “signal() — Handle Interrupt Signals” on page 330
v “Signal Handling Action Definitions” on page 490
v “<signal.h>” on page 13
v Signal APIs in the APIs topic in the iSeries Information Center.
v POSIX thread APIs in the APIs topic in the iSeries Information Center.
Description
Return Value
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int x;
iteration 1, rand=16838
iteration 2, rand=5758
iteration 3, rand=10113
iteration 4, rand=17515
iteration 5, rand=31051
iteration 6, rand=5627
iteration 7, rand=23010
iteration 8, rand=7419
iteration 9, rand=16212
iteration 10, rand=4086
*/
Related Information
v “srand() — Set Seed for rand() Function” on page 338
v “<stdlib.h>” on page 15
Threadsafe: No.
Description
| Note: The dev parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <recio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
_RFILE *fp;
_RIOFB_T *rfb;
/* Do some processing... */
_Rclose ( fp );
}
Related Information
v “_Rrelease() — Release a Program Device” on page 297
Threadsafe: Yes.
Description
The _Rclose() function closes the file specified by fp. Before this file is closed, all
buffers associated with it are flushed and all buffers reserved for it are released.
The file is closed even if an exception occurs. The _Rclose() function applies to all
types of files.
Note: Closing a file more than once in a multi-threaded environment will cause
undefined behavior.
Return Value
The _Rclose() function returns zero if the file is closed successfully, or EOF if the
close operation failed or the file was already closed. The file is closed even if an
exception occurs, and zero is returned.
Value Meaning
ENOTOPEN The file is not open.
EIOERROR A non-recoverable I/O error occurred.
EIORECERR A recoverable I/O error occurred.
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_Rclose ( fp );
}
Related Information
v “_Ropen() — Open a Record File for I/O Operations” on page 271
Threadsafe: No.
Description
The _Rcommit() function completes the current transaction for the job that calls it
and establishes a new commitment boundary. All changes made since the last
commitment boundary are made permanent. Any file or resource that is open
under commitment control in the job is affected.
The cmtid parameter is a null-ended C string used to identify the group of changes
associated with a commitment boundary. It cannot be longer than 4000 bytes.
| Note: The cmtid parameter string must be EBCIDIC, even if the program is
| compiled using LOCALETYPE(*LOCALEUTF).
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
char buf[40];
int rc = 1;
_RFILE *purf;
_RFILE *dailyf;
_Rclose ( purf );
_Rclose ( dailyf );
}
Related Information
v “_Rrollbck() — Roll Back Commitment Control Changes” on page 300
Description
The _Rdelete() function deletes the record that is currently locked for update in
the file specified by fp. After the delete operation, the record is not locked. The file
must be open for update.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rrlslck() — Release a Record Lock” on page 299
Threadsafe: No.
Description
The dev parameter is a null-ended C string. The device name must be specified in
uppercase.
| Note: The dev parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <recio.h>
#include <string.h>
#include <stdlib.h>
_Rclose ( fp );
}
Related Information
v “_Racquire() —Acquire a Program Device” on page 240
v “_Rrelease() — Release a Program Device” on page 297
Threadsafe: Yes.
Description
The realloc() function changes the size of a previously reserved storage block.
The ptr argument points to the beginning of the block. The size argument gives the
new size of the block, in bytes. The contents of the block are unchanged up to the
shorter of the new and old sizes.
If the ptr is NULL, realloc() reserves a block of storage of size bytes. It does not
necessarily give all bits of each element an initial value of 0.
If size is 0 and the ptr is not NULL, realloc()frees the storage allocated to ptr and
returns NULL
The realloc() function returns a pointer to the reallocated storage block. The
storage location of the block may be moved by the realloc() function. Thus, the
ptr argument to the realloc() function is not necessarily the same as the return
value.
If size is 0, the realloc() function returns NULL. If there is not enough storage to
expand the block to the given size, the original block is unchanged and the
realloc() function returns NULL.
The storage to which the return value points is aligned for storage of any type of
object.
To use Teraspace storage instead of heap storage without changing the C source
code, specify the TERASPACE(*YES *TSIFC) parameter on the CRTCMOD compiler
command. This maps the realloc() library function to _C_TS_realloc(), its
Teraspace storage counterpart. The maximum amount of Teraspace storage that can
be allocated by each call to _C_TS_realloc() is 2GB - 240, or 214743408 bytes. For
additional information about Teraspace, see the ILE Concepts manual.
This example allocates storage for the prompted size of array and then uses
realloc() to reallocate the block to hold the new size of the array. The contents of
the array are printed after each allocation.
int main(void)
{
long * array; /* start of the array */
long * ptr; /* pointer to array */
int i; /* index variable */
int num1, num2; /* number of entries of the array */
void print_array( long *ptr_array, int size);
printf( "Enter the size of the array\n" );
scanf( "%i", &num1);
/* allocate num1 entries using malloc() */
if ( (array = (long *) malloc( num1 * sizeof( long ))) != NULL )
{
for ( ptr = array, i = 0; i < num1 ; ++i ) /* assign values */
*ptr++ = i;
print_array( array, num1 );
printf("\n");
}
else { /* malloc error */
perror( "Out of storage" );
abort();
}
/* Change the size of the array ... */
printf( "Enter the size of the new array\n" );
scanf( "%i", &num2);
if ( (array = (long *) realloc( array, num2* sizeof( long ))) != NULL )
{
for ( ptr = array + num1, i = num1; i <= num2; ++i )
*ptr++ = i + 2000; /* assign values to new elements */
print_array( array, num2 );
}
else { /* realloc error */
perror( "Out of storage" );
abort();
}
}
/**** If the initial value entered is 2 and the second value entered
is 4, then the expected output is:
Enter the size of the array
The array of size 2 is:
array[ 0 ] = 0
array[ 1 ] = 1
Enter the size of the new array
The array of size 4 is:
array[ 0 ] = 0
array[ 1 ] = 1
array[ 2 ] = 2002
array[ 3 ] = 2003 */
Related Information
v “calloc() — Reserve and Initialize Storage” on page 57
v “free() — Release Storage Blocks” on page 118
v “malloc() — Reserve Storage Block” on page 180
| Threadsafe: Yes.
Description
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
regex_t preg;
char *string = "a very simple simple simple string";
char *pattern = "\\(sim[a-z]le\\) \\1";
int rc;
size_t nmatch = 2;
regmatch_t pmatch[2];
/****************************************************************************
The output should be similar to :
Threadsafe: Yes.
Description
The regerror() function finds the description for the error code errcode for the
regular expression preg. The description for errcode is assigned to errbuf. The
errbuf_size value specifies the maximum message size that can be stored (the size of
errbuf). The description strings for errcode are:
Return Value
The regerror() returns the size of the buffer needed to hold the string that
describes the error condition. The value of errno may be set to ECONVERT
(conversion error).
This example compiles an invalid regular expression, and prints an error message
using the regerror() function.
#include <regex.htm>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
regex_t preg;
char *pattern = "a[missing.bracket";
int rc;
char buffer[100];
/**********************************************************
The output should be similar to:
Related Information
v “regcomp() — Compile Regular Expression” on page 250
v “regexec() — Execute Compiled Regular Expression”
v “regfree() — Free Memory for Regular Expression” on page 256
v “<regex.h>” on page 12
| Threadsafe: Yes.
Description
The nmatch value is the number of substrings in string that the regexec() function
should try to match with subexpressions in preg. The array you supply for pmatch
must have at least nmatch elements.
The regexec() function fills in the elements of the array pmatch with offsets of the
substrings in string that correspond to the parenthesized subexpressions of the
original pattern given to the regcomp() function to create preg. The zeroth element
of the array corresponds to the entire pattern. If there are more than nmatch
subexpressions, only the first nmatch - 1 are stored. If nmatch is 0, or if the
REG_NOSUB flag was set when preg was created with the regcomp() function, the
regexec() function ignores the pmatch argument.
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
regex_t preg;
char *string = "a very simple simple simple string";
char *pattern = "\\(sim[a-z]le\\) \\1";
int rc;
size_t nmatch = 2;
regmatch_t pmatch[2];
/****************************************************************************
The output should be similar to :
Related Information
Threadsafe: Yes.
Description
The regfree() function frees any memory that was allocated by the
regcomp()function to implement the regular expression preg. After the call to the
regfree() function, the expression that is defined by preg is no longer a compiled
regular or extended expression.
| Note: This function is not available when you specify LOCALETYPE(*CLD) on the
| compilation command.
Return Value
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
regex_t preg;
char *pattern = ".*(simple).*";
int rc;
regfree(&preg);
printf("regcomp() is successful.\n");
return 0;
/************************************************************
The output should be similar to:
regcomp() is successful.
************************************************************/
}
Threadsafe: Yes.
Description
The remove() function deletes the file specified by filename. If the filename contains
the member name, the member is removed or the file is deleted.
Return Value
The remove() function returns 0 if it successfully deletes the file. A nonzero return
value indicates an error.
When you call this example with a file name, the program attempts to remove that
file. It issues a message if an error occurs.
#include <stdio.h>
Related Information
v “fopen() — Open Files” on page 100
v “rename() — Rename File”
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The rename() function renames the file specified by oldname to the name given by
newname. The oldname pointer must specify the name of an existing file. The
newname pointer must not specify the name of an existing file. You cannot rename
a file with the name of an existing file. You also cannot rename an open file.
The file formats that can be used to satisfy the new name depend on the format of
the old name. The following table shows the valid file formats that can be used to
specify the old file name and the corresponding valid file formats for the new
name.
If the format for both new name and old name is lib/file(member), then the file
cannot change. If the file name changes, rename will not work. For example, the
following is not valid: lib/file1(member1) lib/file2(member1).
Return Value
This example takes two file names as input and uses rename() to change the file
name from the first name to the second name.
#include <stdio.h>
Related Information
v “fopen() — Open Files” on page 100
v “remove() — Delete File” on page 257
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The rewind() function repositions the file pointer associated with stream to the
beginning of the file. A call to the rewind() function is the same as:
(void)fseek(stream, 0L, SEEK_SET);
except that the rewind() function also clears the error indicator for the stream.
The rewind() function is not supported for files opened with type=record.
Return Value
This example first opens a file myfile for input and output. It writes integers to the
file, uses rewind() to reposition the file pointer to the beginning of the file, and
then reads in the data.
FILE *stream;
Related Information
v “fgetpos() — Get File Position” on page 91
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
v “ftell() — ftello() — Get Current Position” on page 128
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The _Rfeod() function positions the file to *END unless the file is open for
multi-member processing and the current member is not the last member in the
file. If multi-member processing is in effect and the current member is not the last
member in the file, _Rfeod() will open the next member of the file and position it
to *START.
The _Rfeod() function returns 1 if multi-member processing is taking place and the
next member has been opened. EOF is returned if the file is positioned to *END. If
the operation is unsuccessful, zero is returned. The value of errno may be set to
EIOERROR (a non-recoverable error occurred) or EIORECERR (a recoverable I/O
error occurred). See Table 12 on page 485 and Table 14 on page 489 for errno
settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *in;
char new_purchase[21] = "PEAR 1002022244";
_Rfeod(in);
Related Information
v “_Racquire() —Acquire a Program Device” on page 240
v “_Rfeov() —Force the End-of-File”
Threadsafe: Yes.
Description
The _Rfeov() function forces an end-of-volume condition for a tape file that is
associated with the file that is specified by fp. The _Rfeov()function positions the
file to the next volume of the file. If the file is open for output, the output buffers
will be flushed.
The _Rfeov() function returns 1 if the file has moved from one volume to the next.
It will return EOF if it is called while processing the last volume of the file. It will
return zero if the operation is unsuccessful. The value of errno may be set to
EIOERROR (a non-recoverable error occurred) or EIORECERR (a recoverable I/O
error occurred). See Table 12 on page 485 and Table 14 on page 489 for errno
settings.
#include <stdio.h>
#include <recio.h>
#include <stdlib.h>
int main(void)
{
_RFILE *tape;
_RFILE *fp;
char buf[92];
int i, feov2;
_Rclose ( fp );
_Rclose ( tape );
}
Related Information
v “_Racquire() —Acquire a Program Device” on page 240
v “_Rfeod() —Force the End-of-Data” on page 260
Threadsafe: Yes.
Description
The _Rformat() function sets the record format to fmt for the file specified by fp.
| Note: The fmt parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
The _Rformat() function is valid for multi-format logical database, DDM files,
display, ICF and printer files.
Return Value
The _Rformat() function returns void. See Table 12 on page 485 and Table 14 on
page 489 for errno settings.
int main(void)
{
char buf[40];
int rc = 1;
_RFILE *purf;
_RFILE *dailyf;
_Rclose ( purf );
_Rclose ( dailyf );
}
Related Information
v “_Ropen() — Open a Record File for I/O Operations” on page 271
Description
| Note: The indic_buf parameter string must be EBCIDIC, even if the program is
| compiled using LOCALETYPE(*LOCALEUTF).
The _Rindara() function is valid for display, ICF, and printer files.
Return Value
The _Rindara() function returns void. See Table 12 on page 485 and Table 14 on
page 489 for errno settings.
int main(void)
{
char buf[40];
int rc = 1;
_SYSindara ind_area;
_RFILE *purf;
_RFILE *dailyf;
/* Open purchase display file and daily transaction file */
if ( ( purf = _Ropen ( "MYLIB/T1677RD3", "ar+,indicators=y" )) == NULL )
{
printf ( "Display file did not open.\n" );
exit ( 1 );
}
if ( ( dailyf = _Ropen ( "MYLIB/T1677RDA", "wr,commit=y") ) == NULL )
{
printf ( "Daily transaction file did not open.\n" );
exit ( 2 );
}
/* Associate separate indicator area with purchase file */
_Rindara ( purf, ind_area );
/* Select purchase record format */
_Rformat ( purf, "PURCHASE" );
/* Invite user to enter a purchase transaction. */
/* The _Rwrite function writes the purchase display. */
_Rwrite ( purf, "", 0 );
_Rreadn ( purf, buf, sizeof(buf), __DFT );
/* While user is entering transactions, update daily and */
/* monthly transaction files. */
while ( rc && ind_area[PF03] == IND_OFF )
{
rc = (( _Rwrite ( dailyf, buf, sizeof(buf) ))->num_bytes );
/* If the databases were updated, then commit transaction */
/* otherwise, rollback the transaction and indicate to the */
/* user that an error has occurred and end the application. */
if ( rc )
{
_Rcommit ( "Transaction complete" );
}
else
{
_Rrollbck ( );
_Rformat ( purf, "ERROR" );
}
_Rwrite ( purf, "", 0 );
_Rreadn ( purf, buf, sizeof(buf), __DFT );
}
_Rclose ( purf );
_Rclose ( dailyf );
}
Related Information
v “_Ropen() — Open a Record File for I/O Operations” on page 271
Threadsafe: Yes.
Description
The _Riofbk() function returns a pointer to a copy of the I/O feedback area for the
file that is specified by fp.
Return Value
The _Riofbk() function returns NULL if an error occurs. See Table 12 on page 485
and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
_XXIOFB_T *iofb; /* Pointer to the file’s feedback area */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Open the device file. */
if (( fp = _Ropen ( "MYLIB/T1677RD2", "ar+" )) == NULL )
{
printf ( "Could not open file\n" );
exit ( 1 );
}
_Racquire ( fp,"DEVICE1" ); /* Acquire another device. Replace
*/
/* with actual device name. */
_Rformat ( fp,"FORMAT1" ); /* Set the record format for the */
/* display file. */
rfb = _Rwrite ( fp, "", 0 ); /* Set up the display. */
_Rpgmdev ( fp,"DEVICE2" ); /* Change the default program device. */
/* Replace with actual device name. */
_Rformat ( fp,"FORMAT2" ); /* Set the record format for the */
/* display file. */
rfb = _Rwrite ( fp, "", 0 ); /* Set up the display. */
rfb = _Rwriterd ( fp, &buf, sizeof(buf) );
rfb = _Rwrread ( fp, &in_buf, sizeof(in_buf), &out_buf,
Related Information
v “_Ropnfbk() — Obtain Open Feedback Information” on page 275
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rlocate() function positions to the record in the file associated with fp and
specified by the key, klen_rrn and opts parameters. The _Rlocate() function locks
the record specified by the key, klen_rrn and opts parameters unless __NO_LOCK is
specified.
| Note: The key parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
The _Rlocate() function is valid for database and DDM files that are opened with
the _Ropen() function. The following are valid parameters of the
_Rlocate()function.
key Points to a string containing the key fields to be used for positioning.
klen_rrn
Specifies the length of the key that is used if positioning by key or the
relative record number if positioning by relative record number.
opts Specifies positioning options to be used for the locate operation. The
possible macros are:
__DFT
Default to __KEY_EQ and lock the record for update if the file is
open for updating.
If you specify the start and end options (__START, __START_FRC, __END or
__END_FRC) with any other options, the other options are ignored.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *in;
char new_purchase[21] = "PEAR 1002022244";
_Rfeod(in);
_Rclose(in);
}
Related Information
v “_Ropen() — Open a Record File for I/O Operations”
Threadsafe: Yes.
Description
The _Ropen() function opens the record file specified by filename according to the
mode parameter, which may be followed by optional parameters, if the varparm
keyword parameter is specified in the mode parameter. The open mode and
keyword parameters may be separated by a comma and one or more spaces. The
_Ropen() function does not dynamically create database files for you. All of the
files you refer to in the _Ropen() function must exist, or the open operation will
fail.
Files that are opened by the _Ropen() function are closed implicitly when the
activation group they are opened in, is ended. If a pointer to a file opened in one
activation group is passed to another activation group and the opening activation
group is ended, the file pointer will no longer be valid.
The mode parameter specifies the type of access that is requested for the file. It
contains an open mode that is followed by optional keyword parameters. The mode
parameter may be one of the following values:
Mode Description
rr Open an existing file for reading records.
wr Open an existing file for writing records. If the file contains data, the
content is cleared unless the file is a logical file.
ar Open an existing file for writing records to the end of the file (append).
rr+ Open an existing file for reading, writing or updating records.
wr+ Open an existing file for reading, writing or updating records. If the file
contains data, the content is cleared unless the file is a logical file.
ar+ Open an existing file for reading and writing records. All data is written to
the end of the file.
Return Value
The _Ropen() function returns a pointer to a structure of type _RFILE if the file is
opened successfully. It returns NULL if opening the file is unsuccessful.
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_Rclose ( fp );
}
Related Information
v “_Rclose() —Close a File” on page 241
v “<recio.h>” on page 8
Threadsafe: Yes.
Description
The _Ropnfbk() function returns a pointer to a copy of the open feedback area for
the file that is specified by fp.
Return Value
The _Ropnfbk() function returns NULL if an error occurs. See Table 12 on page 485
and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rupfb() — Provide Information on Last I/O Operation” on page 304
Threadsafe: No.
Description
The _Rpgmdev() function sets the current program device for the file that is
associated with fp to dev. You must specify the device in uppercase.
| Note: The dev parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
The _Rpgmdev() function is valid for display, ICF, and printer files.
Return Value
typedef struct {
char name[20];
char address[25];
} format1 ;
typedef struct {
char name[8];
char password[10];
} format2 ;
typedef union {
format1 fmt1;
format2 fmt2;
} formats ;
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Continue processing. */
_Rclose ( fp );
}
Related Information
v “_Racquire() —Acquire a Program Device” on page 240
v “_Rrelease() — Release a Program Device” on page 297
Description
The _Rreadd() function reads the record that is specified by rrn in the arrival
sequence access path for the file that is associated with fp. The _Rreadd() function
locks the record specified by the rrn unless __NO_LOCK is specified. If the file is a
keyed file, the keyed access path is ignored. Up to size number of bytes are copied
from the record into buf (move mode only).
The _Rreadd() function is valid for database, DDM and display (subfiles) files.
Return Value
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadf() — Read the First Record”
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
_RIOFB_T *_Rreadf (_RFILE *fp, void *buf, size_t size, int opts);
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rreadf() function reads the first record in the access path that is currently
being used for the file specified by fp. The access path may be keyed sequence or
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadindv() — Read from an Invited Device”
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: No.
Description
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rreadk() function reads the record in the keyed access path that is currently
being used for the file that is associated with fp. Up to size number of bytes are
copied from the record into buf (move mode only). The _Rreadk() function locks
the record positioned to unless __NO_LOCK is specified. You must be processing
the file using a keyed sequence path.
The following options may be combined with the positioning options using the
bit-wise OR (|) operator.
__KEY_NULL_MAP
The NULL key map is to be considered when reading a record by key.
__NO_LOCK
The record that is positioned will not be locked.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp;
_RIOFB_T *fb;
char buf[4];
/* Create a physical file */
system("CRTPF FILE(QTEMP/MY_FILE)");
/* Open the file for write */
if ( (fp = _Ropen("QTEMP/MY_FILE", "wr")) == NULL )
{
printf("open for write fails\n");
exit(1);
}
/* write some records into the file */
_Rwrite(fp, "KEY9", 4);
_Rwrite(fp, "KEY8", 4);
_Rwrite(fp, "KEY7", 4);
_Rwrite(fp, "KEY6", 4);
_Rwrite(fp, "KEY5", 4);
_Rwrite(fp, "KEY4", 4);
_Rwrite(fp, "KEY3", 4);
_Rwrite(fp, "KEY2", 4);
_Rwrite(fp, "KEY1", 4);
/* Close the file */
_Rclose(fp);
/* Open the file for read */
if ( (fp = _Ropen("QTEMP/MY_FILE", "rr")) == NULL )
{
printf("open for read fails\n");
exit(2);
}
/* Read the record with key KEY3 */
fb = _Rreadk(fp, buf, 4, __KEY_EQ, "KEY3", 4);
printf("record %d with value %4.4s\n", fb->rrn, buf);
/* Read the next record with key less than KEY3 */
fb = _Rreadk(fp, buf, 4, __KEY_LT, "KEY3", 4);
printf("record %d with value %4.4s\n", fb->rrn, buf);
/* Read the next record with key greater than KEY3 */
fb = _Rreadk(fp, buf, 4, __KEY_GT, "KEY3", 4);
printf("record %d with value %4.4s\n", fb->rrn, buf);
/* Read the next record with different key */
fb = _Rreadk(fp, buf, 4, __KEY_NEXTUNQ, "", 4);
printf("record %d with value %4.4s\n", fb->rrn, buf);
/* Close the file */
_Rclose(fp);
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rreadl() function reads the last record in the access path currently being
used for the file specified by fp. The access path may be keyed sequence or arrival
sequence. Up to size number of bytes are copied from the record into buf (move
mode only). The _Rreadl() function locks the last record unless __NO_LOCK is
specified.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadn() — Read the Next Record”
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
_RIOFB_T *_Rreadn (_RFILE *fp, void *buf, size_t size, int opts);
Description
The _Rreadn() function reads the next record in the access path that is currently
being used for the file that is associated with fp. The access path may be keyed
sequence or arrival sequence. Up to size number of bytes are copied from the
record into buf (move mode only). The _Rreadn() function locks the record
positioned to unless __NO_LOCK is specified.
If the file associated with fp is opened for sequential member processing and the
current record position is the last record of any member in the file except the last,
_Rreadn() will read the first record in the next member of the file.
If the file is open for record blocking and a call to _Rreadp() has filled the block,
the _Rreadn() function is not valid if there are records remaining in the block. You
can check the blk_count in _RIOFB_T to see if there are any remaining records.
The _Rreadn() function is valid for all types of files except printer files.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: No.
Description
The _Rreadnc() function reads the next changed record from the current position
in the subfile that is associated with fp. The minimum size of data that is read from
the screen are copied from the system buffer to buf.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *pf;
_RFILE *subf;
/*************************************************
* Open the subfile and the physical file. *
*************************************************/
if ((pf = _Ropen(PFILENAME, "rr")) == NULL) {
printf("can’t open file %s\n", PFILENAME);
exit(1);
}
if ((subf = _Ropen(SUBFILENAME, "ar+")) == NULL) {
printf("can’t open file %s\n", SUBFILENAME);
exit(2);
}
/*************************************************
* Initialize the subfile with records *
* from the physical file. *
*************************************************/
init_subfile(pf, subf);
/*************************************************
* Write the subfile to the display by writing *
* a record to the subfile control format. *
*************************************************/
_Rformat(subf, "SFLCTL");
_Rwrite(subf, "", 0);
_Rreadnc(subf, "", 0);
/*************************************************
* Close the physical file and the subfile. *
*************************************************/
_Rclose(pf);
_Rclose(subf);
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadp() — Read the Previous Record”
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rreadp() function reads the previous record in the access path that is
currently being used for the file that is associated with fp. The access path may be
keyed sequence or arrival sequence. Up to size number of bytes are copied from
the record into buf (move mode only). The _Rreadp() function locks the record
positioned to unless __NO_LOCK is specified.
If the file associated with fp is opened for sequential member processing and the
current record position is the first record of any member in the file except the first,
_Rreadp() will read the last record in the previous member of the file.
If the file is open for record blocking and a call to _Rreadn() has filled the block,
the _Rreadp() function is not valid if there are records remaining in the block. You
can check the blk_count in _RIOFB_T to see if there are any remaining records.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rreads() function reads the current record in the access path that is currently
being used for the file that is associated with fp. The access path may be keyed
sequence or arrival sequence. Up to size number of bytes are copied from the
record into buf (move mode only). The _Rreads() function locks the record
positioned to unless __NO_LOCK is specified.
If the current position in the file that is associated with fp has no record associated
with it, the _Rreads() function will fail.
The _Rreads() function is not valid when the file is open for record blocking.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *fp;
_XXOPFB_T *opfb;
_Rclose ( fp );
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
Threadsafe: No.
Description
The _Rrelease() function releases the program device that is specified by dev from
the file that is associated with fp. The device name must be specified in uppercase.
| Note: The dev parameter string must be EBCIDIC, even if the program is compiled
| using LOCALETYPE(*LOCALEUTF).
Return Value
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
_XXIOFB_T *iofb; /* Pointer to the file’s feedback area */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Open the device file. */
if (( fp = _Ropen ( "MYLIB/T1677RD2", "ar+" )) == NULL )
{
printf ( "Could not open file\n" );
exit ( 1 );
}
_Racquire ( fp,"DEVICE1" ); /* Acquire another device. Replace */
/* with actual device name. */
_Rformat ( fp,"FORMAT1" ); /* Set the record format for the */
/* display file. */
rfb = _Rwrite ( fp, "", 0 ); /* Set up the display. */
Threadsafe: Yes.
Description
The _Rrlslck() function releases the lock on the currently locked record for the file
specified by fp. The file must be open for update, and a record must be locked. If
the _NO_POSITION option was specified on the _Rlocate() operation that locked
the record, the record released may not be the record currently positioned to.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
char buf[21];
_RFILE *fp;
_XXOPFB_T *opfb;
int result;
/* _Rrlslck example. */
result = _Rrlslck ( fp );
if ( result == 0 )
printf("_Rrlslck failed.\n");
_Rclose ( fp );
}
Related Information
v “_Rdelete() —Delete a Record” on page 244
int _Rrollbck(void);
Threadsafe: No.
Description
Return Value
int main(void)
{
char buf[40];
int rc = 1;
_RFILE *purf;
_RFILE *dailyf;
_Rclose ( purf );
_Rclose ( dailyf );
}
Related Information
v “_Rcommit() —Commit Current Record” on page 243
v Backup and Recovery manual
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rupdate() function updates the record that is currently locked for update in
the file that is specified by fp. The file must be open for update. A record is locked
for update by reading or locating to it unless __NO_LOCK is specified on the read
or locate operation. If the __NO_POSITION option is specified on a locate
operation the record updated may not be the record currently positioned to. After
the update operation, the updated record is no longer locked.
The number of bytes that are copied from buf to the record is the minimum of size
and the record length of the file (move mode only). If size is greater than the
record length, the data is truncated, and errno is set to ETRUNC. One complete
record is always written to the file. If the size is less than the record length of the
file, the remaining data in the record will be the original data that was read into
the system buffer by the read that locked the record. If a locate operation locked
the record, the remaining data will be what was in the system input buffer prior to
the locate.
The _Rupdate() function can be used to update deleted records and key fields. A
deleted record that is updated will no longer be marked as a deleted record. In
both of these cases any keyed access paths defined for fp will be changed.
Note: If locate mode is being used, _Rupdate() works on the data in the file’s
input buffer.
The _Rupdate() function is valid for database, display (subfiles) and DDM files.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
#include <stdio.h>
#include <stdlib.h>
#include <recio.h>
int main(void)
{
_RFILE *in;
char new_purchase[21] = "PEAR 1002022244";
_Rfeod(in);
_Rclose(in);
}
Related Information
v “_Rreadd() — Read a Record by Relative Record Number” on page 277
v “_Rreadf() — Read the First Record” on page 279
v “_Rreadindv() — Read from an Invited Device” on page 281
v “_Rreadk() — Read a Record by Key” on page 284
v “_Rreadl() — Read the Last Record” on page 288
v “_Rreadn() — Read the Next Record” on page 289
v “_Rreadnc() — Read the Next Changed Record in a Subfile” on page 292
v “_Rreadp() — Read the Previous Record” on page 293
v “_Rreads() — Read the Same Record” on page 296
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rupfb() function updates the feedback structure associated with the file
specified by fp with information about the last I/O operation. The _RIOFB_T
structure will be updated even if riofb=N was specified when the file was opened.
The num_bytes field of the _RIOFB_T structure will not be updated. See
“<recio.h>” on page 8 for a description of the _RIOFB_T structure.
Return Value
The _Rupfb() function returns a pointer to the _RIOFB_T structure specified by fp.
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp;
_RIOFB_T *fb;
/* Create a physical file */
system("CRTPF FILE(QTEMP/MY_FILE) RCDLEN(80)");
/* Open the file for write */
if ( (fp = _Ropen("QTEMP/MY_FILE", "wr")) == NULL )
{
printf("open for write fails\n");
exit(1);
}
/* Write some records into the file */
_Rwrite(fp, "This is record 1", 16);
_Rwrite(fp, "This is record 2", 16);
_Rwrite(fp, "This is record 3", 16);
_Rwrite(fp, "This is record 4", 16);
_Rwrite(fp, "This is record 5", 16);
_Rwrite(fp, "This is record 6", 16);
_Rwrite(fp, "This is record 7", 16);
_Rwrite(fp, "This is record 8", 16);
_Rwrite(fp, "This is record 9", 16);
/* Close the file */
_Rclose(fp);
/* Open the file for read */
if ( (fp = _Ropen("QTEMP/MY_FILE", "rr, blkrcd = y")) == NULL )
{
printf("open for read fails\n");
exit(2);
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rwrite() function has two modes: move and locate. When buf points to a
user buffer, _Rwrite() is in move mode. When buf is NULL, the function is in
locate mode.
The _Rwrite() function appends a record to the file specified by fp. The number of
bytes copied from buf to the record is the minimum of size and the record length of
the file (move mode only). If size is greater than the record length, the data is
truncated and errno is set to ETRUNC. One complete record is always written if
the operation is successful.
If you are using _Ropen() and then _Rwrite() to output records to a source
physical file, the sequence numbers must be manually appended.
The _Rwrite() function has no effect on the position of the file for a subsequent
read operation.
If record blocking is taking place and the file associated with fp is nearing the limit
of the number of records it can contain, records may be lost although the
_Rwrite() function indicates success. This can happen if another file pointer is
being used to write records to the file and it fills the file before the records in the
Chapter 2. Library Functions 305
block are written to the file. In this case, the _Rwrite() function will indicate an
error has occurred only on the call to the _Rwrite() function that sends the data to
the database.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
_XXIOFB_T *iofb; /* Pointer to the file’s feedback area */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Open the device file. */
if (( fp = _Ropen ( "MYLIB/T1677RD2", "ar+" )) == NULL )
_RIOFB_T *_Rwrited(_RFILE *fp, void *buf, size_t size, unsigned long rrn);
Threadsafe: Yes. However, if the file pointer is passed among threads, the I/O
feedback area is shared among those threads.
Description
The _Rwrited() function writes a record to the file associated with fp at the
position specified by rrn. The _Rwrited() function will only write over deleted
records. The number of bytes copied from buf to the record is the minimum of size
and the record length of the file (move mode only). If size is greater than the
record length, the data is truncated, and errno is set to ETRUNC. One complete
record is always written if the operation is successful.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
Related Information
v “_Rwrite() — Write the Next Record” on page 305
v “_Rwriterd() — Write and Read a Record” on page 310
v “_Rwrread() — Write and Read a Record (separate buffers)” on page 311
Threadsafe: No.
Description
The _Rwriterd() function performs a write and then a read operation on the file
that is specified by fp. The minimum of size and the length of the current record
format determines the amount of data to be copied between the system buffer and
buf for both the write and read parts of the operation. If size is greater than the
record length of the current format, errno is set to ETRUNC on the write part of
the operation. If size is less than the length of the current record format, errno is set
to ETRUNC on the read part of the operation.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
typedef struct {
char name[20];
char address[25];
} format1 ;
typedef struct {
char name[8];
char password[10];
} format2 ;
typedef union {
format1 fmt1;
format2 fmt2;
} formats ;
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Continue processing. */
_Rclose ( fp );
}
Related Information
v “_Rwrite() — Write the Next Record” on page 305
v “_Rwrited() — Write a Record Directly” on page 307
v “_Rwrread() — Write and Read a Record (separate buffers)”
Threadsafe: No.
Description
The _Rwrread() function performs a write and then a read operation on the file
that is specified by fp. Separate buffers may be specified for the input and output
data. The minimum of size and the length of the current record format determines
the amount of data to be copied between the system buffer and the buffers for
both the write and read parts of the operation. If out_buf_size is greater than the
record length of the current format, errno is set to ETRUNC on the write part of
the operation. If in_buf_size is less than the length of the current record format,
errno is set to ETRUNC on the read part of the operation.
Return Value
See Table 12 on page 485 and Table 14 on page 489 for errno settings.
typedef struct {
char name[20];
char address[25];
} format1 ;
typedef struct {
char name[8];
char password[10];
} format2 ;
typedef union {
format1 fmt1;
format2 fmt2;
} formats ;
int main(void)
{
_RFILE *fp; /* File pointer */
_RIOFB_T *rfb; /*Pointer to the file’s feedback structure */
formats buf, in_buf, out_buf; /* Buffers to hold data */
/* Continue processing. */
_Rclose ( fp );
}
Related Information
v “_Rwrite() — Write the Next Record” on page 305
v “_Rwrited() — Write a Record Directly” on page 307
v “_Rwriterd() — Write and Read a Record” on page 310
Description
The scanf() function reads data from the standard input stream stdin into the
locations that is given by each entry in argument-list. Each argument must be a
pointer to a variable with a type that corresponds to a type specifier in
format-string. The format-string controls the interpretation of the input fields, and is
a multibyte character string that begins and ends in its initial shift state.
The scanf() function reads format-string from left to right. Characters outside of
format specifications are expected to match the sequence of characters in stdin; the
matched characters in stdin are scanned but not stored. If a character in stdin
conflicts with format-string, scanf() ends. The conflicting character is left in stdin
as if it had not been read.
When the first format specification is found, the value of the first input field is
converted according to the format specification and stored in the location specified
by the first entry in argument-list. The second format specification converts the
second input field and stores it in the second entry in argument-list, and so on
through the end of format-string.
| % type
* width h
L
l
ll
|
|
Each field of the format specification is a single character or a number signifying a
particular format option. The type character, which appears after the last optional
format field, determines whether the input field is interpreted as a character, a
Each field of the format specification is discussed in detail below. If a percent sign
(%) is followed by a character that has no meaning as a format control character,
that character and following characters up to the next percent sign are treated as
an ordinary sequence of characters; that is, a sequence of characters that must
match the input. For example, to specify a percent-sign character, use %%.
See the WebSphere Development Studio: ILE C/C++ Programmer’s Guide for more
information about using iSeries pointers.
An asterisk (*) following the percent sign suppresses assignment of the next input
field, which is interpreted as a field of the specified type. The field is scanned but
not stored.
The optional size modifiers h, l, ll, and L indicate the size of the receiving object.
The conversion characters d, i, and n must be preceded by h if the corresponding
argument is a pointer to short int rather than a pointer to int, by l if it is a pointer
to long int, or by ll if it is a pointer to long long int. Similarly, the conversion
characters o, u, x, and X must be preceded by h if the corresponding argument is a
pointer to unsigned short int rather than a pointer to unsigned int, by l if it is a
pointer to unsigned long int, or by ll if it is a pointer to unsigned long long int.
The conversion characters e, E, f, g, and G must be preceded by l if the
corresponding argument is a pointer to double rather than a pointer to float, or by
L if it is a pointer to a long double. Finally, the conversion characters c, s, and [
must be preceded by l if the corresponding argument is a pointer to wchar_t rather
than a pointer to a single byte character type. If an h, l, L or ll appears with any
other conversion character, the behavior is undefined.
The type characters and their meanings are in the following table:
To store a string without storing an ending null character (\0), use the specification
%ac, where a is a decimal integer. In this instance, the c type character means that
the argument is a pointer to a character array. The next a characters are read from
the input stream into the specified location, and no null character is added.
The scanf() function scans each input field character by character. It might stop
reading a particular input field either before it reaches a space character, when the
specified width is reached, or when the next character cannot be converted as
316 ILE C/C++ Run-Time Library Functions V5R3
specified. When a conflict occurs between the specification and the input character,
the next input field begins at the first unread character. The conflicting character, if
there was one, is considered unread and is the first character of the next input field
or the first character in subsequent read operations on stdin.
| For %lc and %ls, specifies the data that is read is a multibyte string and is
| converted to wide characters as if by calls to mbtowc.
| % arg-number$ type
* width h
L
l
ll
|
|
As an alternative, specific entries in the argument-list may be assigned by using
the format specification outlined in the diagram above. This format specification
and the previous format specification may not be mixed in the same call to
scanf(). Otherwise, unpredictable results may occur.
The arg-number is a positive integer constant where 1 refers to the first entry in
the argument-list. Arg-number may not be greater than the number of entries in
the argument-list, or else the results are undefined. Arg-number also may not be
greater than NL_ARGMAX.
Return Value
The scanf() function returns the number of fields that were successfully converted
and assigned. The return value does not include fields that were read but not
assigned.
The return value is EOF for an attempt to read at end-of-file if no conversion was
performed. A return value of 0 means that no fields were assigned.
Error Conditions
If the type of the argument that is to be assigned into is different than the format
specification, unpredictable results can occur. For example, reading a floating point
value, but assigning it into a variable of type int, is incorrect and would have
unpredictable results.
If there are more arguments than format specifications, the extra arguments are
ignored. The results are undefined if there are not enough arguments for the
format specifications.
If the format string contains an invalid format specification, and positional format
specifications are being used, errno will be set to EILSEQ.
If positional format specifications are used and there are not enough arguments,
errno will be set to EINVAL.
#include <stdio.h>
int main(void)
{
int i;
float fp;
char c, s[81];
This example converts a hexadecimal integer to a decimal integer. The while loop
ends if the input value is not a hexadecimal integer.
#include <stdio.h>
int main(void)
{
int number;
This example reads from stdin and assigns data by using the alternative positional
format string.
return 0;
}
--------------------------------------------------------------------
| This example reads in a multibyte character string into a wide Unicode string. The
| example can be compiled with either LOCALETYPE(*LOCALEUCS2) or
| LOCALETYPE(*LOCALEUTF).
|
| #include <locale.h>
| #include <stdio.h>
| #include <wchar.h>
|
| void main(void)
| {
| wchar_t uString[20];
|
| setlocale(LC_UNI_ALL, "");
| scanf("Enter a string %ls",uString);
|
| printf("String read was %ls\n",uString);
| }
|
| /* if the input is : ABC
| then the output will be similiar to:
|
| String read was ABC
|
| */
|
Related Information
v “fscanf() — Read Formatted Data” on page 123
v “printf() — Print Formatted Characters” on page 211
v “sscanf() — Read Data” on page 339
v “wscanf() — Read Data Using Wide-Character Format String” on page 482
v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
v “swscanf() — Read Wide Character Data” on page 387
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
If the buffer argument is NULL, the stream is unbuffered. If not, the buffer must
point to a character array of length BUFSIZ, which is the buffer size that is defined
in the <stdio.h> include file. The system uses the buffer, which you specify, for
input/output buffering instead of the default system-allocated buffer for the given
stream. stdout, stderr, and stdin do not support user-defined buffers.
Return Value
This example opens the file setbuf.dat for writing. It then calls the setbuf()
function to establish a buffer of length BUFSIZ. When string is written to the
stream, the buffer buf is used and contains the string before it is flushed to the file.
#include <stdio.h>
int main(void)
{
char buf[BUFSIZ];
char string[] = "hello world";
FILE *stream;
Related Information
v “fclose() — Close Stream” on page 82
v “fflush() — Write Buffer to File” on page 87
v “fopen() — Open Files” on page 100
v “setvbuf() — Control Buffering” on page 328
Threadsafe: Yes.
Description
The setjmp() function saves a stack environment that can subsequently be restored
by the longjmp() function. The setjmp() and longjmp() functions provide a way to
perform a non-local goto. They are often used in signal handlers.
A call to the setjmp() function causes it to save the current stack environment in
env. A subsequent call to the longjmp() function restores the saved environment
and returns control to a point corresponding to the setjmp() call. The values of all
variables (except register variables) available to the function receiving control
contain the values they had when the longjmp() function was called. The values of
register variables are unpredictable. Nonvolatile auto variables that are changed
between calls to the setjmp() function and the longjmp() function are also
unpredictable.
Return Value
The setjmp() function returns the value 0 after saving the stack environment. If the
setjmp() function returns as a result of a longjmp() call, it returns the value
argument of the longjmp() function, or 1 if the value argument of the longjmp()
function is 0. There is no error return value.
This example stores the stack environment at the statement if(setjmp(mark) != 0) ...
When the system first performs the if statement, it saves the environment in mark
and sets the condition to FALSE because setjmp()returns a 0 when it saves the
environment. The program prints the message:
The subsequent call to function p tests for a local error condition, which can cause
it to perform the longjmp() function. Then, control returns to the original function
using the environment that is saved in mark. This time, the condition is TRUE
because -1 is the return value from the longjmp() function. The program then
performs the statements in the block and prints:
jmp_buf mark;
int main(void)
{
if (setjmp(mark) != 0)
{
printf("longjmp has been called\n");
recover();
}
printf("setjmp has been called\n");
p();
exit(1);
}
void p(void)
{
longjmp(mark, -1);
}
void recover(void)
{
exit(1);
}
Related Information
v “longjmp() — Restore Stack Environment” on page 178
v “<setjmp.h>” on page 13
Threadsafe: No.
Description
The setlocale() function changes or queries variables that are defined in the
<locale.h> include file, that indicate location. The values for category are listed
below.
Category Purpose
LC_ALL Names entire locale of program.
LC_COLLATE Affects behavior of the strcoll() and strxfrm() functions.
LC_CTYPE Affects behavior of character handling functions.
LC_MONETARY Affects monetary information returned by localeconv() and
nl_langinfo() functions.
LC_NUMERIC Affects the decimal-point character for the formatted
input/output and string conversion functions, and the
non-monetary formatting information returned by the
localeconv() and nl_langinfo() functions.
LC_TIME Affects behavior of the strftime() function and the time
formatting information returned by the nl_langinfo() function.
| Note: There are two ways of defining setlocale() and other locale-sensitive C
| functions on the iSeries server. The original way to define setlocale() uses
| *CLD locale objects to set the locale and retrieve locale-sensitive data. The
| second way to define setlocale() uses *LOCALE objects to set the locale
| and retrieve locale-sensitive data. The original way is accessed by specifying
| LOCALETYPE(*CLD) on the compilation command. The second way is
| accessed by specifying LOCALETYPE(*LOCALE),
| LOCALETYPE(*LOCALEUCS2), or LOCALETYPE(*LOCALEUTF) on the
| compilation command. For more information on the two methods of locale
| definition in ILE C, see ″International Locale Support″ in the WebSphere
| Development Studio: ILE C/C++ Programmer’s Guide.
You can set the value of locale to "C", "", LC_C, LC_C_GERMANY, LC_C_FRANCE,
LC_C_SPAIN, LC_C_ITALY, LC_C_USA or LC_C_UK. A locale value of ″C″
indicates the default C environment. A locale value of "" tells the setlocale()
function to use the default locale for the implementation.
You can set the value of locale to "", "C", "POSIX", or the fully qualified Integrated
File System path name of a *LOCALE object enclosed in double quotes. A locale
value of "C" or "POSIX" indicates the default C *LOCALE object. A locale value of
"" tells the setlocale() function to use the default locale for the process.
| The default locale for the process is determined using the following table:
|| LC_ALL
| 1. Check the LC_ALL environment variable1. If it is
| defined and not null, use the specified locale2 for all
| POSIX locale categories. Otherwise, go to the next
| step.
| 2. For each POSIX locale category (LC_CTYPE,
| LC_COLLATE, LC_TIME, LC_NUMERIC,
| LC_MESSAGES, LC_MONETARY, and LC_TOD),
| check the environment variable with the same name1.
| If it is defined and not null, use the locale specified2.
| 3. Check the LANG environment variable1. For every
| locale category that was not set in the previous step, if
| the LANG environment variable is defined and not
| null, set the locale category to the specified locale2.
| Otherwise, set it to the default C *LOCALE object.
Return Value
The setlocale() function returns a pointer to a string that, if passed back to the
setlocale() function, would restore the locale to the previous setting. This string
should be copied by the user as it will be overwritten on subsequent calls to
setlocale().
| Note: Because the string to which a successful call to setlocale() points may be
| overwritten by subsequent calls to the setlocale() function, you should
| copy the string if you plan to use it later. The exact format of the locale
| string is different between locale types of *CLD, *LOCALE, *LOCALEUCS2,
| and *LOCALEUTF.
To query the locale, give a NULL as the second parameter. For example, to query
all the categories of your locale, enter the following statement:
On error, the setlocale() function returns NULL, and the program’s locale is not
changed.
************************************************************************/
#include <stdio.h>
#include <locale.h>
char *string;
int main(void)
{
string = setlocale(LC_ALL, LC_C_FRANCE);
if (string != NULL)
printf(" %s \n",string);
}
Example that uses *LOCALE objects
/************************************************************************
This example sets the locale of the program to be "POSIX" and prints
the string that is associated with the locale. This example must be
compiled with the LOCALETYPE(*LOCALE) parameter on the CRTCMOD or
CRTBNDC command.
************************************************************************/
#include <stdio.h>
#include <locale.h>
char *string;
int main(void)
{
Related Information
v “getenv() — Search for Environment Variables” on page 144
v “localeconv() — Retrieve Information from the Environment” on page 168
v “nl_langinfo() —Retrieve Locale Information” on page 206
v “<locale.h>” on page 7
Threadsafe: Yes.
The setvbuf() function allows control over the buffering strategy and buffer size
for a specified stream. The setvbuf() function only works in ILE C when using the
integrated file system. The stream must refer to a file that has been opened, but
not read or written to.
The array pointed to by buf designates an area that you provide that the C library
may choose to use as a buffer for the stream. A buf value of NULL indicates that
no such area is supplied and that the C library is to assume responsibility for
managing its own buffers for the stream. If you supply a buffer, it must exist until
the stream is closed.
If type is _IOFBF or _IOLBF, size is the size of the supplied buffer. If buf is NULL,
the C library takes size as the suggested size for its own buffer. If type is _IONBF,
both buf and size are ignored.
Return Value
Warning: The array that is used as the buffer must still exist when the specified
stream is closed. For example, if the buffer is declared within the scope of a
function block, the stream must be closed before the function is ended and frees the
storage allocated to the buffer.
This example sets up a buffer of buf for stream1 and specifies that input to stream2
is to be unbuffered.
char buf[BUF_SIZE];
FILE *stream1, *stream2;
int main(void)
{
stream1 = fopen("myfile1.dat", "r");
stream2 = fopen("myfile2.dat", "r");
/* stream2 is unbuffered */
if (setvbuf(stream2, NULL, _IONBF, 0) != 0)
printf("Incorrect type or size of buffer\n");
Related Information
v “fclose() — Close Stream” on page 82
v “fflush() — Write Buffer to File” on page 87
v “fopen() — Open Files” on page 100
v “setbuf() — Control Buffering” on page 319
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The signal() function allows a program to choose one of several ways to handle
an interrupt signal from the operating system or from the raise() function. If
compiled with the SYSIFCOPT(*ASYNCSIGNAL) option, this function uses
asynchronous signals. The asynchronous version of this function behaves like
sigaction() with SA_NODEFER and SA_RESETHAND options. Asynchronous
signal handlers may not call abort() or exit(). The remainder of this function
description will describe synchronous signals.
The sig argument must be one of the macros SIGABRT, SIGALL, SIGILL, SIGINT,
SIGFPE, SIGIO, SIGOTHER, SIGSEGV, SIGTERM, SIGUSR1, or SIGUSR2, defined
in the signal.h include file. SIGALL, SIGIO, and SIGOTHER are only supported by
the ILE C/C++ Run-time library. The func argument must be one of the macros
SIG_DFL or SIG_IGN, defined in the <signal.h> include file, or a function address.
The action that is taken when the interrupt signal is received depends on the value
of func.
Value Meaning
SIG_DFL
Default handling for the signal will occur.
SIG_IGN
The signal is to be ignored.
Return Value
void StrCln(int);
void DoWork(char **, int);
Related Information
v “abort() — Stop a Program” on page 38
v “atexit() — Record Program Ending Function” on page 48
v “exit() — End Program” on page 80
v “raise() — Send Signal” on page 238
v “<signal.h>” on page 13
v signal() API in the APIs topic in the iSeries Information Center.
Threadsafe: Yes.
Description
The sin() function calculates the sine of x, with x expressed in radians. If x is too
large, a partial loss of significance in the result may occur.
Return Value
The sin() function returns the value of the sine of x. The value of errno may be
set to either EDOM or ERANGE.
#include <math.h>
#include <stdio.h>
int main(void)
{
double pi, x, y;
pi = 3.1415926535;
x = pi/2;
y = sin(x);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “asin() — Calculate Arcsine” on page 44
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sinh() — Calculate Hyperbolic Sine”
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Description
Return Value
The sinh() function returns the value of the hyperbolic sine of x. If the result is
too large, the sinh() function sets errno to ERANGE and returns the value
HUGE_VAL (positive or negative, depending on the value of x).
#include <math.h>
#include <stdio.h>
int main(void)
{
double pi, x, y;
pi = 3.1415926535;
x = pi/2;
y = sinh(x);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “asin() — Calculate Arcsine” on page 44
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “tan() — Calculate Tangent” on page 389
v “tanh() — Calculate Hyperbolic Tangent” on page 390
v “<math.h>” on page 7
Threadsafe: Yes.
The snprintf() function formats and stores a series of characters and values in the
array buffer. Any argument-list is converted and put out according to the
corresponding format specification in the format-string. The snprintf() function is
identical to the sprintf() function with the addition of the n argument, which
indicates the maximum number of characters (including the ending null character)
to be written to buffer.
The format-string consists of ordinary characters and has the same form and
function as the format string for the printf() function.
Return Value
The snprintf() function returns the number of bytes that are written in the array,
not counting the ending null character.
Threadsafe: Yes.
Description
The sprintf() function formats and stores a series of characters and values in the
array buffer. Any argument-list is converted and put out according to the
corresponding format specification in the format-string.
The format-string consists of ordinary characters and has the same form and
function as the format-string argument for the printf() function.
Return Value
The sprintf() function returns the number of bytes that are written in the array,
not counting the ending null character.
#include <stdio.h>
char buffer[200];
int i, j;
double fp;
char *s = "baltimore";
char c;
int main(void)
{
c = ’l’;
i = 35;
fp = 1.7320508;
string:
baltimore
l
35
1.732051
character count = 24 */
Related Information
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “printf() — Print Formatted Characters” on page 211
v “sscanf() — Read Data” on page 339
Threadsafe: Yes.
Description
The sqrt() function calculates the nonnegative value of the square root of x.
Return Value
The sqrt() function returns the square root result. If x is negative, the function sets
errno to EDOM, and returns 0.
This example computes the square root of the quantity that is passed as the first
argument to main. It prints an error message if you pass a negative value.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
if ( argc != 2 )
printf( "Usage: %s value\n", argv[0] );
else
{
value = strtod( argv[1], &rest);
if ( value < 0.0 )
printf( "sqrt of a negative number\n" );
else
printf("sqrt( %lf ) = %lf\n", value, sqrt( value ));
}
}
Related Information
v “exp() — Calculate Exponential Function” on page 81
Threadsafe: No.
Description
The srand() function sets the starting point for producing a series of
pseudo-random integers. If srand() is not called, the rand() seed is set as if
srand(1) were called at program start. Any other value for seed sets the generator to
a different starting point.
Return Value
This example first calls srand() with a value other than 1 to initiate the random
value sequence. Then the program computes five random values for the array of
integers that are called ranvals.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int i, ranvals[5];
srand(17);
for (i = 0; i < 5; i++)
{
ranvals[i] = rand();
printf("Iteration %d ranvals [%d] = %d\n", i+1, i, ranvals[i]);
}
}
Threadsafe: Yes.
Description
The sscanf() function reads data from buffer into the locations that are given by
argument-list. Each argument must be a pointer to a variable with a type that
corresponds to a type specifier in the format-string.
Return Value
The sscanf() function returns the number of fields that were successfully
converted and assigned. The return value does not include fields that were read
but not assigned.
The return value is EOF when the end of the string is encountered before anything
is converted.
This example uses sscanf() to read various data from the string tokenstring, and
then displays that data.
| #include <stdio.h>
| #include <stddef.h>
|
| int main(void)
| {
| char *tokenstring = "15 12 14";
| char *string = "ABC Z";
| wchar_t ws[81];
| wchar_t wc;
| int i;
| float fp;
| char s[81];
| char c;
|
| /* Input various data */
| /* In the first invocation of sscanf, the format string is */
| /* "%s %c%d%f". If there were no space between %s and %c, */
| /* sscanf would read the first character following the */
| /* string, which is a blank space. */
|
| sscanf(tokenstring, "%s %c%d%f", s, &c, &i, &fp);
| sscanf(string, "%ls %lc", ws,&wc);
|
| /* Display the data */
| printf("\nstring = %s\n",s);
| printf("character = %c\n",c);
| printf("integer = %d\n",i);
Threadsafe: Yes.
Description
The strcasecmp() function compares string1 and string2 without sensitivity to case.
All alphabetic characters in string1 and string2 are converted to lowercase before
comparison.
Return Value
The strcasecmp() function returns a value indicating the relationship between the
two strings, as follows:
Table 6. Return values of strcasecmp()
Value Meaning
Less than 0 string1 less than string2
0 string1 equivalent to string2
Greater than 0 string1 greater than string2
int main(void)
{
char_t *str1 = "STRING";
char_t *str2 = "string";
int result;
if (result == 0)
printf("Strings compared equal.\n");
else if (result < 0)
printf("\"%s\" is less than \"%s\".\n", str1, str2);
else
printf("\"%s\" is greater than \"%s\".\n", str1, str2);
return 0;
}
***********************************/
Related Information
v “strncasecmp() — Compare Strings without Case Sensitivity” on page 359
v “strncmp() — Compare Strings” on page 362
v “stricmp() - Compare Strings without Case Sensitivity” on page 357
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “__wcsicmp() — Compare Wide Character Strings without Case Sensitivity” on
page 439
v “__wcsnicmp() — Compare Wide Character Strings without Case Sensitivity” on
page 446
v “<strings.h>” on page 16
Threadsafe: Yes.
Description
The strcat() function concatenates string2 to string1 and ends the resulting string
with the null character.
If the storage of string1 overlaps the storage of string2, the behavior is undefined.
Return Value
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char buffer1[SIZE] = "computer";
char * ptr;
Related Information
v “strchr() — Search for Character”
v “strcmp() — Compare Strings” on page 343
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncat() — Concatenate Strings” on page 361
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strchr() function operates on null-ended strings. The string arguments to the
function should contain a null character (\0) that marks the end of the string.
Return Value
This example finds the first occurrence of the character ″p″ in ″computer program″.
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char buffer1[SIZE] = "computer program";
char * ptr;
int ch = ’p’;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strcmp() — Compare Strings”
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncmp() — Compare Strings” on page 362
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcschr() — Search for Wide Character” on page 431
v “wcsspn() — Find Offset of First Non-matching Wide Character” on page 453
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strcmp() function compares string1 and string2. The function operates on
null-ended strings. The string arguments to the function should contain a null
character (\0) that marks the end of the string.
Return Value
The strcmp() function returns a value indicating the relationship between the two
strings, as follows:
Value Meaning
Less than 0 string1 less than string2
0 string1 identical to string2
Greater than 0 string1 greater than string2
This example compares the two strings that are passed to main() using strcmp().
#include <stdio.h>
#include <string.h>
if ( argc != 3 )
{
printf( "Usage: %s string1 string2\n", argv[0] );
}
else
{
if ( result == 0 )
printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] );
else if ( result < 0 )
printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] );
else
printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] );
}
}
"is this first?" is greater than "is this before that one?"
**********************************************************************/
Related Information
| Note: The strcmpi function is available for C++ programs. It is available for C
| only when the program defines the __cplusplus__strings__ macro.
Threadsafe: Yes.
Description
strcmpi compares string1 and string2 without sensitivity to case. All alphabetic
characters in the two arguments string1 and string2 are converted to lowercase
before the comparison.
The function operates on null-ended strings. The string arguments to the function
are expected to contain a null character (\0) marking the end of the string.
Return Value
strcmpi returns a value indicating the relationship between the two strings, as
follows:
Value Meaning
Less than 0 string1 less than string2
0 string1 equivalent to string2
Greater than 0 string1 greater than string2
Related Information:
v “strcoll() — Compare Strings”
v “strcspn() — Find Offset of First Character Match” on page 348
v “strdup - Duplicate String” on page 350
v “stricmp() - Compare Strings without Case Sensitivity” on page 357
v “strncmp() — Compare Strings” on page 362
v “strnicmp - Compare Substrings Without Case Sensitivity” on page 365
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “strcasecmp() — Compare Strings without Case Sensitivity” on page 340
v “strncasecmp() — Compare Strings without Case Sensitivity” on page 359
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strcoll() function compares two strings using the collating sequence that is
specified by the program’s locale.
Return Value
The strcoll() function returns a value indicating the relationship between the
strings, as listed below:
Value Meaning
Less than 0 string1 less than string2
0 string1 equivalent to string2
Greater than 0 string1 greater than string2
This example compares the two strings that are passed to main() using strcoll():
#include <stdio.h>
#include <string.h>
if ( argc != 3 )
{
printf( "Usage: %s string1 string2\n", argv[0] );
}
else
{
if ( result == 0 )
printf( "\"%s\" is identical to \"%s\"\n", argv[1], argv[2] );
else if ( result < 0 )
printf( "\"%s\" is less than \"%s\"\n", argv[1], argv[2] );
else
printf( "\"%s\" is greater than \"%s\"\n", argv[1], argv[2] );
}
}
Related Information
v “setlocale() — Set Locale” on page 322
v “strcmp() — Compare Strings” on page 343
v “strncmp() — Compare Strings” on page 362
v “wcscoll() —Language Collation String Comparison” on page 434
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strcpy() function operates on null-ended strings. The string arguments to the
function should contain a null character (\0) that marks the end of the string. No
length checking is performed. You should not use a literal string for a string1
value, although string2 may be a literal string.
Return Value
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char source[SIZE] = "This is the source string";
char destination[SIZE] = "And this is the destination string";
char * return_string;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcspn() — Find Offset of First Character Match”
v “strncpy() — Copy Strings” on page 364
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strcspn() function finds the first occurrence of a character in string1 that
belongs to the set of characters that is specified by string2. Null characters are not
considered in the search.
The strcspn() function operates on null-ended strings. The string arguments to the
function should contain a null character (\0) marking the end of the string.
Return Value
The strcspn() function returns the index of the first character found. This value is
equivalent to the length of the initial substring of string1 that consists entirely of
characters not in string2.
This example uses strcspn() to find the first occurrence of any of the characters
″a″, ″x″, ″l″, or ″e″ in string.
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char string[SIZE] = "This is the source string";
char * substring = "axle";
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcpy() — Copy Strings” on page 347
v “strncmp() — Compare Strings” on page 362
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
| Note: The strdup function is available for C++ programs. It is available for C only
| when the program defines the __cplusplus__strings__ macro.
Threadsafe: Yes.
Description
strdup reserves storage space for a copy of string by calling malloc. The string
argument to this function is expected to contain a null character (\0) marking the
end of the string. Remember to free the storage reserved with the call to strdup.
Return Value
strdup returns a pointer to the storage space containing the copied string. If it
cannot reserve storage strdup returns NULL.
This example uses strdup to duplicate a string and print the copy.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string = "this is a copy";
char *newstr;
/* Make newstr point to a duplicate of string */
if ((newstr = strdup(string)) != NULL)
printf("The new string is: %s\n", newstr);
return 0;
}
Related Information:
v “strcpy() — Copy Strings” on page 347
v “strncpy() — Copy Strings” on page 364
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strerror() function maps the error number in errnum to an error message
string.
Return Value
| The strerror() function returns a pointer to the string. It does not return a NULL
| value. The value of errno may be set to ECONVERT (conversion error).
This example opens a file and prints a run-time error message if an error occurs.
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(void)
{
FILE *stream;
Related Information
v “clearerr() — Reset Error Indicators” on page 64
v “ferror() — Test for Read/Write Errors” on page 87
v “perror() — Print Error Message” on page 209
v “<string.h>” on page 16
Threadsafe: Yes.
Description
Field Width
w A decimal digit string w specifying a minimum field width in bytes in
which the result of the conversion is right-justified (or left-justified if the
flag - is specified). The default is 0.
Left Precision
#n A # followed by a decimal digit string n specifying a maximum number of
digits expected to be formatted to the left of the radix character. This
option can be used to keep the formatted output from multiple calls to
strfmon() aligned in the same columns. It can also be used to fill unused
positions with a special character as in $***123.45. This option causes an
Right Precision
.p A period followed by a decimal digit string p specifies the number of digits
after the radix character. If the value of the right precision p is 0, no radix
character appears. If a right precision is not specified, a default specified
by the current locale is used. The amount being formatted is rounded to
the specified number of digits prior to formatting.
Table 8. Conversion Characters
Specifier Meaning
%i The double argument is formatted according to
the locale’s international currency format.
%n The double argument is formatted according to
the locale’s national currency format.
%% Is replaced by %. No argument is converted.
Return Value
If the total number of resulting bytes including the ending null character is not
more than maxsize, the strfmon() function returns the number of bytes placed into
the array pointed to by s, but excludes the ending null character. Otherwise, zero is
returned, and the contents of the array are undefined.
int main(void)
{
char string[100];
double money = 1234.56;
if (setlocale(LC_ALL, "/qsys.lib/en_us.locale") == NULL) {
printf("Unable to setlocale().\n");
exit(1);
}
Related Information
v “localeconv() — Retrieve Information from the Environment” on page 168
v “<monetary.h>” on page 8
Threadsafe: Yes.
Description
The strftime() function places bytes into the array pointed to by s as controlled
by the string pointed to by format. The format string consists of zero or more
conversion specifications and ordinary characters. A conversion specification
consists of a % character and a terminating conversion character that determines
the behavior of the conversion. All ordinary characters (including the terminating
null byte, and multi-byte chars) are copied unchanged into the array. If copying
takes place between objects that overlap, then the behavior is undefined. No more
than maxsize bytes are placed in the array. The appropriate characters are
determined by the values contained in the structure pointed to by timeptr, and by
the values stored in the current locale.
Specifier Meaning
%a Abbreviated weekday name.
%A Full weekday name.
%b Abbreviated month name.
%B Full month name.
%c Date/Time in the format of the locale.
%C Century number [00-99], the year divided by 100 and truncated to an
integer.
%d Day of the month [01-31].
%D Date Format, same as %m/%d/%y.
%e Same as %d, except single digit is preceded by a space [1-31].
| %g 2 digit year portion of ISO week date [00,99].
| Note: %C, %D, %e, %h, %n, %r, %R, %t, %T, %u, %V, and the modified conversion
| specifiers are not available when LOCALETYPE(*CLD) is specified on the
| compilation command.
Return Value
If the total number of resulting bytes including the terminating null byte is not
more than maxsize, strftime() returns the number of bytes placed into the array
pointed to by s, not including the terminating null byte. Otherwise, 0 is returned
and the contents of the array are indeterminate.
int main(void)
{
char s[100];
int rc;
time_t temp;
struct tm *timeptr;
temp = time(NULL);
timeptr = localtime(&temp);
return 0;
}
/*************************************************
The output should be similar to:
46 characters written
Today is Wednesday, Oct 24.
Time: 01:01:15 PM
************************************************************/
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “setlocale() — Set Locale” on page 322
v “strptime()— Convert String to Date/Time” on page 369
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
| Note: The stricmp function is available for C++ programs. It is available for C
| only when the program defines the __cplusplus__strings__ macro.
Threadsafe: Yes.
Description
The function operates on null-ended strings. The string arguments to the function
are expected to contain a null character (\0) marking the end of the string.
Return Value
stricmp returns a value indicating the relationship between the two strings, as
follows:
Value Meaning
Less than 0 string1 less than string2
0 string1 equivalent to string2
Greater than 0 string1 greater than string2
Related Information:
v “strcmpi() - Compare Strings Without Case Sensitivity” on page 345
v “strcoll() — Compare Strings” on page 346
v “strcspn() — Find Offset of First Character Match” on page 348
v “strdup - Duplicate String” on page 350
v “strncmp() — Compare Strings” on page 362
v “strcasecmp() — Compare Strings without Case Sensitivity” on page 340
v “strncasecmp() — Compare Strings without Case Sensitivity” on page 359
v “strnicmp - Compare Substrings Without Case Sensitivity” on page 365
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strlen() function determines the length of string excluding the ending null
character.
Return Value
This example determines the length of the string that is passed to main().
#include <stdio.h>
#include <string.h>
if ( argc != 2 )
printf( "Usage: %s string\n", argv[0] );
else
printf( "Input string has a length of %i\n", strlen( argv[1] ));
}
/****************** If the input is the string ***********************
*****************"How long is this string?", ******************
****************** then the expected output is: *****************
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “strncat() — Concatenate Strings” on page 361
v “strncmp() — Compare Strings” on page 362
v “strncpy() — Copy Strings” on page 364
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “<string.h>” on page 16
Threadsafe: Yes.
Description
Return Value
int main(void)
{
char_t *str1 = "STRING ONE";
char_t *str2 = "string TWO";
int result;
if (result == 0)
printf("Strings compared equal.\n");
else if (result < 0)
printf("\"%s\" is less than \"%s\".\n", str1, str2);
else
printf("\"%s\" is greater than \"%s\".\n", str1, str2);
return 0;
}
***********************************/
Related Information
v “strcasecmp() — Compare Strings without Case Sensitivity” on page 340
v “strncmp() — Compare Strings” on page 362
v “stricmp() - Compare Strings without Case Sensitivity” on page 357
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “__wcsicmp() — Compare Wide Character Strings without Case Sensitivity” on
page 439
Threadsafe: Yes.
Description
The strncat() function appends the first count characters of string2 to string1 and
ends the resulting string with a null character (\0). If count is greater than the
length of string2, the length of string2 is used in place of count.
The strncat() function operates on null-ended strings. The string argument to the
function should contain a null character (\0) marking the end of the string.
Return Value
This example demonstrates the difference between strcat() and strncat(). The
strcat() function appends the entire second string to the first, whereas strncat()
appends only the specified number of characters in the second string to the first.
#define SIZE 40
int main(void)
{
char buffer1[SIZE] = "computer";
char * ptr;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strncmp() — Compare Strings”
v “strncpy() — Copy Strings” on page 364
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strncmp() function compares string1 and string2 to the maximum of count.
Return Value
Value Meaning
Less than 0 string1 less than string2
0 string1 equivalent to string2
Greater than 0 string1 greater than string2
This example demonstrates the difference between the strcmp() function and the
strncmp() function.
#include <stdio.h>
#include <string.h>
#define SIZE 10
int main(void)
{
int result;
int index = 3;
char buffer1[SIZE] = "abcdefg";
char buffer2[SIZE] = "abcfg";
void print_result( int, char *, char * );
Related Information
v “strcmp() — Compare Strings” on page 343
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncat() — Concatenate Strings” on page 361
Threadsafe: Yes.
Description
The strncpy() function copies count characters of string2 to string1. If count is less
than or equal to the length of string2, a null character (\0) is not appended to the
copied string. If count is greater than the length of string2, the string1 result is
padded with null characters (\0) up to length count.
Return Value
#define SIZE 40
int main(void)
{
char source[ SIZE ] = "123456789";
char source1[ SIZE ] = "123456789";
char destination[ SIZE ] = "abcdefg";
char destination1[ SIZE ] = "abcdefg";
char * return_string;
int index = 5;
Related Information
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncat() — Concatenate Strings” on page 361
v “strncmp() — Compare Strings” on page 362
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “<string.h>” on page 16
| Note: The strnset and strset functions are available for C++ programs. They are
| available for C only when the program defines the __cplusplus__strings__
| macro.
Threadsafe: Yes.
Description
Chapter 2. Library Functions 365
strnicmp compares, at most, the first n characters of string1 and string2 without
sensitivity to case.
The function operates on null terminated strings. The string arguments to the
function are expected to contain a null character (\0) marking the end of the
string.
Return Value
Related Information:
v “strcmp() — Compare Strings” on page 343
v “strcmpi() - Compare Strings Without Case Sensitivity” on page 345
v “stricmp() - Compare Strings without Case Sensitivity” on page 357
v “strncmp() — Compare Strings” on page 362
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “<string.h>” on page 16
| Note: The strnset and strset functions are available for C++ programs. They are
| available for C only when the program defines the __cplusplus__strings__
| macro.
Threadsafe: Yes.
Description
Return Value
Both strset and strnset return a pointer to the altered string. There is no error
return value.
In this example, strnset sets not more than four characters of a string to the
character ’x’. Then the strset function changes any non-null characters of the
string to the character ’k’.
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] = "abcdefghi";
printf("This is the string: %s\n", str);
printf("This is the string after strnset: %s\n", strnset((char*)str, ’x’, 4));
printf("This is the string after strset: %s\n", strset((char*)str, ’k’));
return 0;
}
Related Information:
v “strchr() — Search for Character” on page 342
v “strpbrk() — Find Characters in String”
v “wcschr() — Search for Wide Character” on page 431
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strpbrk() function locates the first occurrence in the string pointed to by
string1 of any character from the string pointed to by string2.
Return Value
The strpbrk() function returns a pointer to the character. If string1 and string2
have no characters in common, a NULL pointer is returned.
This example returns a pointer to the first occurrence in the array string of either a
or b.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *result, *string = "A Blue Danube";
char *chars = "ab";
The first occurrence of any of the characters "ab" in "The Blue Danube"
is "anube"
*/
Related Information
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncmp() — Compare Strings” on page 362
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcschr() — Search for Wide Character” on page 431
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strptime() function converts the character string pointed to by buf to values
that are stored in the tm structure pointed to by tm, using the format specified by
format.
The format contains zero or more directives. A directive contains either an ordinary
character (not % or a white space), or a conversion specification. Each conversion
specification is composed of a % character followed by one or more conversion
characters, which specify the replacement required. There must be a white space or
other delimiter in both buf and format to be guaranteed that the function will
behave as expected. There must be a delimiter between two string-to-number
conversions, or the first number conversion may convert characters that belong to
the second conversion specifier.
Specifier Meaning
%a Name of day of the week, can be either the full name or an
abbreviation.
%A Same as %a.
%b Month name, can be either the full name or an abbreviation.
Specifier Meaning
%Ec Date/time for current era.
%EC Era name.
%Ex Date for current era.
%EX Time for current era.
%Ey Era year. This is the offset from the base year.
%EY Year for the current era.
%Od Day of the month using alternate digits.
%Oe Same as %Od.
%OH Hour in 24-hour format using alternate digits.
%OI Hour in 12-hour format using alternate digits.
%Om Month using alternate digits.
%OM Minutes using alternate digits.
%OS Seconds using alternate digits.
%Ou Day of the week using alternate digits. Monday is 1 and Sunday is 7.
%OU Week number of the year using alternate digits. Sunday is the first day
of the week.
| %OV ISO week number of the year using alternate digits. See %V for
| explanation of ISO week number.
%Ow Weekday using alternate digit. Sunday is 0 and Saturday is 6.
%OW Week number of the year using alternate digits. Monday is the first day
of the week.
%Oy 2-digit year using alternate digits.
Return Value
int main(void)
{
char buf[100];
time_t t;
struct tm *timeptr,result;
setlocale(LC_ALL,"/QSYS.LIB/EN_US.LOCALE");
t = time(NULL);
timeptr = localtime(&t);
strftime(buf,sizeof(buf), "%a %m/%d/%Y %r", timeptr);
return 0;
}
/************************************************************
The output should be similar to:
Tue 10/30/2001 10:59:10 AM
tm_hour: 10
tm_min: 59
tm_sec: 10
tm_mon: 9
tm_mday: 30
tm_year: 101
tm_yday: 302
tm_wday: 2
************************************************************/
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “setlocale() — Set Locale” on page 322
v “strftime() — Convert Date/Time to String” on page 354
v “time() — Determine Current Time” on page 391
v “<time.h>” on page 16
v “wcsptime()— Convert Wide Character String to Date/Time” on page 448
Threadsafe: Yes.
Description
Return Value
The strrchr() function returns a pointer to the last occurrence of c in string. If the
given character is not found, a NULL pointer is returned.
This example compares the use of strchr() and strrchr(). It searches the string
for the first and last occurrence of p in the string.
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main(void)
{
char buf[SIZE] = "computer program";
char * ptr;
int ch = ’p’;
Related Information
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcspn() — Find Offset of First Character Match” on page 348
v “strncmp() — Compare Strings” on page 362
v “strpbrk() — Find Characters in String” on page 367
v “strspn() —Find Offset of First Non-matching Character” on page 374
Threadsafe: Yes.
Description
The strspn() function finds the first occurrence of a character in string1 that is not
contained in the set of characters that is specified by string2. The null character
(\0) that ends string2 is not considered in the matching process.
Return Value
The strspn() function returns the index of the first character found. This value is
equal to the length of the initial substring of string1 that consists entirely of
characters from string2. If string1 begins with a character not in string2, the
strspn() function returns 0. If all the characters in string1 are found in string2, the
length of string1 is returned.
This example finds the first occurrence in the array string of a character that is not
an a, b, or c. Because the string in this example is cabbage, the strspn() function
returns 5, the length of the segment of cabbage before a character that is not an a,
b, or c.
#include <stdio.h>
#include <string.h>
int main(void)
{
char * string = "cabbage";
char * source = "abc";
int index;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
Threadsafe: Yes.
Description
The strstr() function finds the first occurrence of string2 in string1. The function
ignores the null character (\0) that ends string2 in the matching process.
Return Value
The strstr() function returns a pointer to the beginning of the first occurrence of
string2 in string1. If string2 does not appear in string1, the strstr() function
returns NULL. If string2 points to a string with zero length, the strstr() function
returns string1.
This example locates the string ″haystack″ in the string "needle in a haystack".
#include <string.h>
#include <stdio.h>
int main(void)
{
char *string1 = "needle in a haystack";
char *string2 = "haystack";
char *result;
result = strstr(string1,string2);
/* Result = a pointer to "haystack" */
printf("%s\n", result);
}
haystack
*/
Related Information
v “strchr() — Search for Character” on page 342
Threadsafe: Yes.
Description
The strtod() function expects nptr to point to a string with the following form:
digits
whitespace + . digits
– . digits
e digits
E +
–
The first character that does not fit this form stops the scan.
Return Value
The strtod() function returns the value of the floating-point number, except when
the representation causes an underflow or overflow. For an overflow, it returns
-HUGE_VAL or +HUGE_VAL; for an underflow, it returns 0.
376 ILE C/C++ Run-Time Library Functions V5R3
In both cases, errno is set to ERANGE, depending on the base of the value. If the
string pointed to by nptr does not have the expected form, no conversion is
performed and the value of nptr is stored in the object pointed to by endptr,
provided that endptr is not a NULL pointer.
The strtod() function does not fail if a character other than a digit follows an E or
e read in as an exponent. For example, 100elf will be converted to the
floating-point value 100.0.
This example converts the strings to a double value. It prints out the converted
value and the substring that stopped the conversion.
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *string, *stopstring;
double x;
string = "100ergs";
x = strtod(string, &stopstring);
printf("string = \"%s\"\n", string);
printf(" strtod = %lf\n", x);
printf(" Stopped scan at \"%s\"\n\n", stopstring);
}
string = 100ergs
strtod = 100.000000
Stopped scan at ergs
*/
Related Information
v “atof() — Convert Character String to Float” on page 49
v “atoi() — Convert Character String to Integer” on page 50
v “atol() — atoll() — Convert Character String to Long or Long Long Integer” on
page 51
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “strtoul() — strtoull() — Convert Character String to Unsigned Long and
Unsigned Long Long Integer” on page 382
v “wcstod() — Convert Wide-Character String to Double” on page 455
v “<stdlib.h>” on page 15
Description
The strtok() function reads string1 as a series of zero or more tokens, and string2
as the set of characters serving as delimiters of the tokens in string1. The tokens in
string1 can be separated by one or more of the delimiters from string2. The tokens
in string1 can be located by a series of calls to the strtok() function.
In the first call to the strtok() function for a given string1, the strtok() function
searches for the first token in string1, skipping over leading delimiters. A pointer to
the first token is returned.
When the strtok() function is called with a NULL string1 argument, the next
token is read from a stored copy of the last non-null string1 parameter. Each
delimiter is replaced by a null character. The set of delimiters can vary from call to
call, so string2 can take any value. Note that the initial value of string1 is not
preserved after the call to the strtok() function.
Note that the strtok() function writes data into the buffer. The function should be
passed to a non-critical buffer containing the string to be tokenized because the
buffer will be damaged by the strtok() function.
Return Value
The first time the strtok() function is called, it returns a pointer to the first token
in string1. In later calls with the same token string, the strtok() function returns a
pointer to the next token in the string. A NULL pointer is returned when there are
no more tokens. All tokens are null-ended.
Note: The strtok() function uses an internal static pointer to point to the next
token in the string being tokenized. A reentrant version of the strtok()
function, strtok_r(), which does not use any internal static storage, can be
used in place of the strtok() function.
Using a loop, this example gathers tokens, separated by commas, from a string
until no tokens are left. The example prints the tokens, a string, of, and tokens.
int main(void)
{
char *token, *string = "a string, of, ,tokens\0,after null terminator";
token: a string
token: of
token:
token: tokens
*/
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “strtok_r() — Tokenize String (Restartable)”
v “<string.h>” on page 16
Threadsafe: Yes.
Description
The strtok_r() function reads string as a series of zero or more tokens, and seps as
the set of characters serving as delimiters of the tokens in string. The tokens in
string can be separated by one or more of the delimiters from seps. The arguments
lasts points to a user-provided pointer, which points to stored information
necessary for the strtok_r() function to continue scanning the same string.
To read the next token from string, call the strtok_r() function with a NULL string
argument. This causes the strtok_r() function to search for the next token in the
previous token string. Each delimiter is replaced in the original string is replaced
by a null character, and the pointer to which lasts points is updated. The set of
delimiters in seps can vary from call to call, but lasts must remain unchanged from
the previous call. When no tokens remain in string, a NULL pointer is returned.
Return Value
The first time the strtok_r() function is called, it returns a pointer to the first
token in string. In later calls with the same token string, the strtok_r() function
returns a pointer to the next token in the string. A NULL pointer is returned when
there are no more tokens. All tokens are null-ended.
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strchr() — Search for Character” on page 342
v “strcmp() — Compare Strings” on page 343
v “strcpy() — Copy Strings” on page 347
v “strcspn() — Find Offset of First Character Match” on page 348
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “strtok() — Tokenize String” on page 378
v “<string.h>” on page 16
Format (strtoll())
#include <stdlib.h>
long long int strtoll(char *string, char **endptr, int base);
Threadsafe: Yes.
Description
The strtol() function converts a character string to a long integer value. The
parameter nptr points to a sequence of characters that can be interpreted as a
numeric value of type long int.
The strtoll() function converts a character string to a long long integer value.
The parameter nptr points to a sequence of characters that can be interpreted as a
numeric value of type long long int.
digits
whitespace + 0
– 0x
0X
If the base parameter is a value between 2 and 36, the subject sequence’s expected
form is a sequence of letters and digits representing an integer whose radix is
specified by the base parameter. This sequence is optionally preceded by a positive
(+) or negative (-) sign. Letters from a to z inclusive (either upper or lower case)
are ascribed the values 10 to 35; only letters whose ascribed values are less than
that of the base parameter are permitted. If the base parameter has a value of 16,
the characters 0x or 0X optionally precede the sequence of letters and digits,
following the positive (+) or negative (-) sign, if present.
If the value of the base parameter is 0, the string determines the base. After an
optional leading sign a leading 0 indicates octal conversion, a leading 0x or 0X
indicates hexadecimal conversion, and all other leading characters result in decimal
conversion.
These functions scan the string up to the first character that is inconsistent with the
base parameter. This character may be the null character (’\0’) at the end of the
string. Leading white-space characters are ignored, and an optional sign may
precede the digits.
If the value of the endptr parameter is not null a pointer, a pointer to the character
that ended the scan is stored in the value pointed to by endptr. If a value cannot be
formed, the value pointed to by endptr is set to the nptr parameter
Return Value
| If base has an invalid value (less than 0, 1, or greater than 36), errno is set to
| EINVAL and 0 is returned. The value pointed to by the endptr parameter is set to
| the value of the nptr parameter.
If the value is outside the range of representable values, errno is set to ERANGE.
If the value is positive, the strtol() function will return LONG_MAX, and the
strtoll() function will return LONGLONG_MAX. If the value is negative, the
strtol() function will return LONG_MIN, and the strtoll() function will return
LONGLONG_MIN.
| If no characters are converted, the strtoll() and strtol() functions will set errno
| to EINVAL and 0 is returned. For both functions, the value pointed to by endptr is
| set to the value of the nptr parameter. Upon successful completion, both functions
| return the converted value.
This example converts the strings to a long value. It prints out the converted value
and the substring that stopped the conversion.
int main(void)
{
char *string, *stopstring;
long l;
int bs;
string = "10110134932";
printf("string = %s\n", string);
for (bs = 2; bs <= 8; bs *= 2)
{
l = strtol(string, &stopstring, bs);
printf(" strtol = %ld (base %d)\n", l, bs);
printf(" Stopped scan at %s\n\n", stopstring);
}
}
string = 10110134932
strtol = 45 (base 2)
Stopped scan at 34932
Related Information
v “atof() — Convert Character String to Float” on page 49
v “atoi() — Convert Character String to Integer” on page 50
v “atol() — atoll() — Convert Character String to Long or Long Long Integer” on
page 51
v “strtod() — Convert Character String to Double” on page 376
v “strtoul() — strtoull() — Convert Character String to Unsigned Long and
Unsigned Long Long Integer”
v “wcstol() — wcstoll() — Convert Wide Character String to Long and Long Long
Integer” on page 458
v “<stdlib.h>” on page 15
Format (strtoull())
#include <stdlib.h>
unsigned long long int strtoull(char *string, char **endptr, int base);
Threadsafe: Yes.
Description
When you use these functions, the nptr parameter should point to a string with the
following form:
digits
whitespace + 0
– 0x
0X
If the base parameter is a value between 2 and 36, the subject sequence’s expected
form is a sequence of letters and digits representing an integer whose radix is
specified by the base parameter. This sequence is optionally preceded by a positive
(+) or negative (-) sign. Letters from a to z inclusive (either upper or lower case)
are ascribed the values 10 to 35. Only letters whose ascribed values are less than
that of the base parameter are permitted. If the base parameter has a value of 16
the characters 0x or 0X optionally precede the sequence of letters and digits,
following the positive (+) or negative (-) sign, if present.
If the value of the base parameter is 0, the string determines the base. After an
optional leading sign a leading 0 indicates octal conversion, a leading 0x or 0X
indicates hexadecimal conversion, and all other leading characters result in decimal
conversion.
These functions scan the string up to the first character that is inconsistent with the
base parameter. This character may be the null character (’\0’) at the end of the
string. Leading white-space characters are ignored, and an optional sign may
precede the digits.
If the value of the endptr parameter is not null a pointer, a pointer to the character
that ended the scan is stored in the value pointed to by endptr. If a value cannot
be formed, the value pointed to by endptr is set to the nptr parameter.
Return Value
| If base has an invalid value (less than 0, 1, or greater than 36), errno is set to
| EINVAL and 0 is returned. The value pointed to by the endptr parameter is set to
| the value of the nptr parameter.
If the value is outside the range of representable values, errno is set to ERANGE.
The strtoul() function will return ULONG_MAX and the strtoull() function
will return ULONGLONG_MAX.
If no characters are converted, the strtoull() function will set errno to EINVAL
and 0 is returned. The strtoul() function will return 0 but will not set errno to
EINVAL. In both cases the value pointed to by endptr is set to the value of the nptr
parameter. Upon successful completion, both functions return the converted value.
This example converts the string to an unsigned long value. It prints out the
converted value and the substring that stopped the conversion.
#include <stdio.h>
#include <stdlib.h>
#define BASE 2
int main(void)
{
char *string, *stopstring;
unsigned long ul;
string = 1000e13 e
strtoul = 8 (base 2)
Stopped scan at e13 e
*/
Related Information
v “atof() — Convert Character String to Float” on page 49
v “atoi() — Convert Character String to Integer” on page 50
v “atol() — atoll() — Convert Character String to Long or Long Long Integer” on
page 51
v “strtod() — Convert Character String to Double” on page 376
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “wcstoul() — wcstoull() — Convert WideCharacter String to Unsigned Long and
Unsigned Long Long Integer” on page 463
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The strxfrm() function transforms the string pointed to by string2 and places the
result into the string pointed to by string1. The transformation is determined by the
program’s current locale. The transformed string is not necessarily readable, but
can be used with the strcmp() or the strncmp() functions.
Return Value
The strxfrm() function returns the length of the transformed string, excluding the
ending null character. If the returned value is greater than or equal to count, the
contents of the transformed string are indeterminate.
This example prompts the user to enter a string of characters, then uses
strxfrm()to transform the string and return its length.
#include <stdio.h>
#include <string.h>
int main(void)
{
char *string1, buffer[80];
int length;
Related Information
v “localeconv() — Retrieve Information from the Environment” on page 168
v “setlocale() — Set Locale” on page 322
v “strcmp() — Compare Strings” on page 343
v “strcoll() — Compare Strings” on page 346
v “strncmp() — Compare Strings” on page 362
v “<string.h>” on page 16
Threadsafe: Yes.
Description
A null wide character is added to the end of the wide characters written; the null
wide character is not counted as part of the returned value. If copying takes place
between objects that overlap, the behavior is undefined.
Return Value
The swprintf() function returns the number of wide characters that are written in
the array, not counting the ending null wide character.
This example uses the swprintf() function to format and print several values to
buffer.
int main(void)
{
wchar_t wcsbuf[BUF_SIZE];
wchar_t wstring[] = L"ABCDE";
int num;
/***************************************************************
The output should be similar to :
Related Information
v “printf() — Print Formatted Characters” on page 211
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The swscanf() function is equivalent of the fwscanf() function, except that the
argument buffer specifies a wide string from which the input is to be obtained,
rather than from a stream. Reaching the end of the wide string is equivalent to
encountering end-of-file for the fwscanf() function.
Return Value
The swscanf() function returns the number of fields that were successfully
converted and assigned. The return value does not include fields that were read
but not assigned. The return value is EOF when the end of the string is
encountered before anything is converted.
#include <wchar.h>
#include <stdio.h>
int main(void)
{
/* Input various data */
printf("string = %s\n",s);
printf("character = %c\n",c);
printf("integer = %d\n",i);
printf("floating-point number = %f\n",fp);
Related Information
v “fscanf() — Read Formatted Data” on page 123
v “scanf() — Read Data” on page 313
v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
v “wscanf() — Read Data Using Wide-Character Format String” on page 482
v “sscanf() — Read Data” on page 339
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “<wchar.h>” on page 17
Threadsafe: Yes. However, the CL command processor and all CL commands are
NOT threadsafe. Use this function with caution.
Description
The system() function passes the given string to the CL command processor for
processing.
Return Value
| #include <stdlib.h>
|
| int main(void)
| {
| int result;
|
| /* A data area is created, displayed and deleted: */
|
| result = system("CRTDTAARA QTEMP/TEST TYPE(*CHAR) VALUE(’Test’)");
| result = system("DSPDTAARA TEST");
| result = system("DLTDTAARA TEST");
|
| }
|
Related Information
v “exit() — End Program” on page 80
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
Return Value
int main(void)
{
double pi, x;
pi = 3.1415926;
x = tan(pi/4.0);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “asin() — Calculate Arcsine” on page 44
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tanh() — Calculate Hyperbolic Tangent”
v “<math.h>” on page 7
Threadsafe: Yes.
Description
Return Value
The tanh() function returns the value of the hyperbolic tangent of x. The result of
tanh() cannot have a range error.
int main(void)
{
double pi, x;
pi = 3.1415926;
x = tanh(pi/4);
Related Information
v “acos() — Calculate Arccosine” on page 40
v “asin() — Calculate Arcsine” on page 44
v “atan() – atan2() — Calculate Arctangent” on page 47
v “cos() — Calculate Cosine” on page 66
v “cosh() — Calculate Hyperbolic Cosine” on page 67
v “sin() — Calculate Sine” on page 332
v “sinh() — Calculate Hyperbolic Sine” on page 333
v “tan() — Calculate Tangent” on page 389
v “<math.h>” on page 7
Threadsafe: Yes.
Description
Note: Calendar time is the number of seconds that have elapsed since EPOCH,
which is 00:00:00, January 1, 1970 Universal Coordinate Time (UTC).
Return Value
The time() function returns the current calendar time. The return value is also
stored in the location that is given by timeptr. If timeptr is NULL, the return value
is not stored. If the calendar time is not available, the value (time_t)(-1) is returned.
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t ltime;
if(time(<ime) == -1)
{
printf("Calendar time not available.\n");
exit(1);
}
printf("The time is %s\n", ctime(<ime));
}
Related Information
v “asctime() — Convert Time to Character String” on page 41
v “asctime_r() — Convert Time to Character String (Restartable)” on page 43
v “ctime() — Convert Time to Character String” on page 68
v “ctime_r() — Convert Time to Character String (Restartable)” on page 69
v “gmtime() — Convert Time” on page 151
v “gmtime_r() — Convert Time (Restartable)” on page 153
v “localtime() — Convert Time” on page 173
v “localtime_r() — Convert Time (Restartable)” on page 174
v “mktime() — Convert Local Time” on page 204
v “<time.h>” on page 16
Threadsafe: Yes.
Description
The tmpfile() function creates a temporary binary file. The file is automatically
removed when it is closed or when the program is ended.
Return Value
On the iSeries Data Management system, the tmpfile() function creates a new file
that is named QTEMP/QACXxxxx. If you specify the SYSIFCOPT(*IFSIO) option
on the compilation command, the tmpfile() function creates a new file that is
named /tmp/QACXaaaaaaa. At the end of the job, the file that is created with the
filename from the tmpfile() function is discarded. You can use the remove()
function to remove files.
This example creates a temporary file, and if successful, writes tmpstring to it. At
program end, the file is removed.
#include <stdio.h>
FILE *stream;
char tmpstring[ ] = "This is the string to be temporarily written";
int main(void)
{
if((stream = tmpfile( )) == NULL)
perror("Cannot make a temporary file");
else
fprintf(stream, "%s", tmpstring);
}
Related Information
v “fopen() — Open Files” on page 100
v “<stdio.h>” on page 14
Description
The tmpnam() function produces a valid file name that is not the same as the name
of any existing file. It stores this name in string. If string is NULL, the tmpnam()
function leaves the result in an internal static buffer. Any subsequent calls destroy
this value. If string is not NULL, it must point to an array of at least L_tmpnam
bytes. The value of L_tmpnam is defined in <stdio.h>.
The tmpnam() function produces a different name each time it is called within an
activation group up to at least TMP_MAX names. For ILE C, TMP_MAX is 32 767.
This is a theoretical limit; the actual number of files that can be opened at the same
time depends on the available space in the system.
Return Value
Chapter 2. Library Functions 393
The tmpnam() function returns a pointer to the name. If it cannot create a unique
name then it returns NULL.
#include <stdio.h>
int main(void)
{
char *name1;
if ((name1 = tmpnam(NULL)) !=NULL)
printf("%s can be used as a file name.\n", name1);
else printf("Cannot create a unique file name\n");
Related Information
v “fopen() — Open Files” on page 100
v “remove() — Delete File” on page 257
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
Return Value
The toascii() function maps the character c according to a 7–bit US-ASCII locale
and returns the corresponding character encoding in the current locale.
This example prints encodings of the 7–bit US-ASCII characters 0x7c to 0x82 are
mapped to by toascii().
void main(void)
{
int ch;
Related Information
v “isascii() — Test for Character Representable as ASCII Value” on page 158
v “<ctype.h>” on page 3
Threadsafe: Yes.
Description
Return Value
Both functions return the converted character. If the character c does not have a
corresponding lowercase or uppercase character, the functions return c unchanged.
This example uses the toupper() and tolower() functions to change characters
between code 0 and code 7f.
int main(void)
{
int ch;
Related Information
v “isalnum() - isxdigit() — Test Integer Value” on page 156
v “towlower() –towupper() — Convert Wide Character Case” on page 397
v “<ctype.h>” on page 3
Threadsafe: Yes.
Description
The towctrans() function maps the wide character wc using the mapping that is
described by desc. The current setting of the LC_CTYPE category (or the
LC_UNI_CTYPE category if a UNICODE LOCALETYPE was specified) will be the
same as the one used during the call to the wctrans() function that returned the
value desc.
Return Value
The towctrans() function returns the mapped value of wc using the mapping that
is described by desc.
int main()
{
char *alpha = "abcdefghijklmnopqrstuvwxyz";
char *tocase[2] = {"toupper", "tolower"};
wchar_t *wcalpha;
int i, j;
size_t alphalen;
alphalen = strlen(alpha)+1;
wcalpha = (wchar_t *)malloc(sizeof(wchar_t)*alphalen);
Related Information
v “wctrans() —Get Handle for Character Mapping” on page 470
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
Return Value
If wc is a wide character for which iswupper() (or iswlower()) is true and there is
a corresponding wide character for which iswlower() (or iswupper()) is true,
towlower() (or towupper()) returns the corresponding wide character. Otherwise,
the argument is returned unchanged.
#include <wctype.h>
#include <stdio.h>
int main(void)
{
wint_t w_ch;
:
towupper : 0xc1 0xc1, towlower : 0xc1 0x81
towupper : 0xc2 0xc2, towlower : 0xc2 0x82
towupper : 0xc3 0xc3, towlower : 0xc3 0x83
towupper : 0xc4 0xc4, towlower : 0xc4 0x84
towupper : 0xc5 0xc5, towlower : 0xc5 0x85
:
towupper : 0x81 0xc1, towlower : 0x81 0x81
towupper : 0x82 0xc2, towlower : 0x82 0x82
towupper : 0x83 0xc3, towlower : 0x83 0x83
towupper : 0x84 0xc4, towlower : 0x84 0x84
towupper : 0x85 0xc5, towlower : 0x85 0x85
:
**********************************************************************/
}
Related Information
v “iswalnum() to iswxdigit() — Test Wide Integer Value” on page 160
v “tolower() – toupper() — Convert Character Case” on page 395
v “<wctype.h>” on page 17
Note: The _ultoa function is supported only for C++, not for C.
Threadsafe: Yes.
Description
_ultoa converts the digits of the given unsigned long value to a character string
that ends with a null character and stores the result in string. The radix argument
specifies the base of value; it must be in the range 2 to 36.
Note: The space allocated for string must be large enough to hold the returned
string. The function can return up to 33 bytes including the null character
(\0).
| When the string argument is NULL or the radix is outside the range 2 to 36, errno
| will be set to EINVAL.
This example converts the integer value 255 to a decimal, binary, and hexidecimal
representation.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buffer[35];
char *p;
p = _ultoa(255UL, buffer, 10);
printf("The result of _ultoa(255) with radix of 10 is %s\n", p);
p = _ultoa(255UL, buffer, 2);
printf("The result of _ultoa(255) with radix of 2\n is %s\n", p);
p = _ultoa(255UL, buffer, 16);
printf("The result of _ultoa(255) with radix of 16 is %s\n", p);
return 0;
}
Related Information
v “_gcvt - Convert Floating-Point to String” on page 141
v “_itoa - Convert Integer to String” on page 163
v “_ltoa - Convert Long Integer to String” on page 177
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The ungetc() function pushes the unsigned character c back onto the given input
stream. However, only one consecutive character is guaranteed to be pushed back
onto the input stream if you call ungetc()consecutively. The stream must be open
for reading. A subsequent read operation on the stream starts with c. The character
c cannot be the EOF character.
Return Value
The ungetc() function is not supported for files opened with type=record.
In this example, the while statement reads decimal digits from an input data
stream by using arithmetic statements to compose the numeric values of the
numbers as it reads them. When a non-digit character appears before the end of
the file, ungetc() replaces it in the input stream so that later input functions can
process it.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *stream;
int ch;
unsigned int result = 0;
while ((ch = getc(stream)) != EOF && isdigit(ch))
result = result * 10 + ch - ’0’;
if (ch != EOF)
ungetc(ch,stream);
/* Put the nondigit character back */
printf("The result is: %d\n", result);
if ((ch = getc(stream)) != EOF)
printf("The character is: %c\n", ch);
}
Related Information
v “getc() – getchar() — Read a Character” on page 142
v “fflush() — Write Buffer to File” on page 87
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
v “putc() – putchar() — Write a Character” on page 221
v “rewind() — Adjust Current File Position” on page 259
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The ungetwc() function pushes the wide character wc back onto the input stream.
The pushed-back wide characters will be returned by subsequent reads on that
stream in the reverse order of their pushing. A successful intervening call (on the
stream) to a file positioning function (fseek(), fsetpos(), or rewind()) discards
any pushed-back wide characters for the stream. The external storage
corresponding to the stream is unchanged. There is always at least one wide
character of push-back. If the value of wc is WEOF, the operation fails and the
input stream is unchanged.
A successful call to the ungetwc() function clears the EOF indicator for the stream.
The value of the file position indicator for the stream after reading or discarding
all pushed-back wide characters is the same as it was before the wide characters
were pushed back. However, only one consecutive wide character is guaranteed to
be pushed back onto the input stream if you call ungetwc() consecutively.
For a text stream, the file position indicator is backed up by one wide character.
This affects the ftell(), fflush(), fseek() (with SEEK_CUR), and
fgetpos()function. For a binary stream, the position indicator is unspecified until
all characters are read or discarded, unless the last character is pushed back, in
which case the file position indicator is backed up by one wide character. This
affects the ftell(), fseek() (with SEEK_CUR), fgetpos(), and fflush()function.
Return Value
The ungetwc() function returns the wide character pushed back after conversion,
or WEOF if the operation fails.
int main(void)
{
FILE *stream;
wint_t wc;
wint_t wc2;
unsigned int result = 0;
if (WEOF != wc)
ungetwc(wc, stream); /* Push the nondigit wide character back */
/****************************************************************************
Assuming the file ungetwc.dat contains:
12345ABCDE67890XYZ
Related Information
v “fflush() — Write Buffer to File” on page 87
v “fseek() — fseeko() — Reposition File Position” on page 124
v “fsetpos() — Set File Position” on page 126
v “getwc() — Read Wide Character from Stream” on page 147
v “putwc() — Write Wide Character” on page 225
v “ungetc() — Push Character onto Input Stream” on page 399
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The va_arg() function retrieves a value of the given var_type from the location
given by arg_ptr, and increases arg_ptr to point to the next argument in the list. The
va_arg() function can retrieve arguments from the list any number of times within
the function. The var_type argument must be one of int, long, decimal, double,
struct, union, or pointer, or a typedef of one of these types.
Return Value
The va_arg() function returns the current argument. The va_end and va_start()
functions do not return a value.
int main(void)
{
vout(3, "Sat", "Sun", "Mon");
printf("\n");
vout(5, "Mon", "Tues", "Wed", "Thurs", "Fri");
}
va_start(arg_ptr, max);
while(args < max)
{
days[args] = va_arg(arg_ptr, char *);
printf("Day: %s \n", days[args++]);
}
va_end(arg_ptr);
}
Day: Sat
Day: Sun
Day: Mon
Day: Mon
Day: Tues
Day: Wed
Day: Thurs
Day: Fri
*/
Related Information
v “vfprintf() — Print Argument Data to Stream”
v “vprintf() — Print Argument Data” on page 411
v “vfwprintf() — Format Argument Data as Wide Characters and Write to a
Stream” on page 407
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “<stdarg.h>” on page 13
Threadsafe: Yes.
Description
The vfprintf() function converts each entry in the argument list according to the
corresponding format specifier in format. The format has the same form and
function as the format string for the printf() function.
Return Value
This example prints out a variable number of strings to the file myfile.
#include <stdarg.h>
#include <stdio.h>
int main(void)
{
FILE *stream;
stream = fopen("mylib/myfile", "w");
{
va_list arg_ptr;
va_start(arg_ptr, fmt);
vfprintf(stream, fmt, arg_ptr);
va_end(arg_ptr);
}
Related Information
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “printf() — Print Formatted Characters” on page 211
v “va_arg() – va_end() – va_start() — Access Function Arguments” on page 402
v “vprintf() — Print Argument Data” on page 411
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “vwprintf() — Format Argument Data as Wide Characters and Print” on page
422
v “<stdarg.h>” on page 13
v “<stdio.h>” on page 14
| Threadsafe: Yes.
| Description
| The vfscanf() function reads data from a stream into locations specified by a
| variable number of arguments. The vfscanf() function works just like the
| fscanf()function, except that arg_ptr points to a list of arguments whose number
| can vary from call to call in the program. These arguments should be initialized by
| va_start for each call. In contrast, the fscanf() function can have a list of
| arguments, but the number of arguments in that list is fixed when you compile the
| program.
| Return Value
| The vfscanf() function returns the number of fields that were successfully
| converted and assigned. The return value does not include fields that were read
| but not assigned. The return value is EOF for an attempt to read at end-of-file if no
| conversion was performed. A return value of 0 means that no fields were assigned.
| This example opens the file myfile for input, and then scans this file for a string, a
| long integer value, and a floating point value.
|
Threadsafe: Yes.
Description
The vfwprintf() function is equivalent to the fwprintf() function, except that the
variable argument list is replaced by arg, which the va_start macro (and possibly
subsequent va_arg calls) will have initialized. The vfwprintf() function does not
invoke the va_end macro.
Return Value
This example prints the wide character a to a file. The printing is done from the
vout() function, which takes a variable number of arguments and uses
vfwprintf() to print them to a file.
#include <wchar.h>
#include <stdarg.h>
#include <locale.h>
int main(void) {
FILE *stream;
wchar_t format [] = L"%lc";
setlocale(LC_ALL, "POSIX");
if ((stream = fopen (ifs_path, "w")) == NULL) {
printf("Could not open file.\n");
return (-1);
}
vout (stream, format, L’a’);
fclose (stream);
/***********************************************
The contents of output file tmp/myfile.dat should
be a wide char ’a’ which in the "POSIX" locale
is ’0081’x.
*/
return (0);
Related Information
v “printf() — Print Formatted Characters” on page 211
v “fprintf() — Write Formatted Data to a Stream” on page 108
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “btowc() — Convert Single Byte to Wide Character” on page 55
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “vwprintf() — Format Argument Data as Wide Characters and Print” on page
422
v “<stdarg.h>” on page 13
v “<stdio.h>” on page 14
v “<wchar.h>” on page 17
| Threadsafe: Yes.
| Description
| The vfwscanf() function reads wide data from a stream into locations specified by
| a variable number of arguments. The vfwscanf() function works just like the
| fwscanf() function, except that arg_ptr points to a list of arguments whose number
| can vary from call to call in the program. These arguments should be initialized by
| va_start for each call. In contrast, the fwscanf() function can have a list of
| arguments, but the number of arguments in that list is fixed when you compile the
| program.
| Return Value
| This example opens the file myfile for input, and then scans this file for a string, a
| long integer value, and a floating point value.
|
| #include <stdio.h>
| #include <stdarg.h>
| #include <wchar.h>
|
| int vread(FILE *stream, wchar_t *fmt, ...)
| {
| int rc;
| va_list arg_ptr;
| va_start(arg_ptr, fmt);
| rc = vfwscanf(stream, fmt, arg_ptr);
| va_end(arg_ptr);
| return(rc);
| }
|
| #define MAX_LEN 80
| int main(void)
| {
| FILE *stream;
| long l;
| float fp;
| char s[MAX_LEN + 1];
| char c;
| stream = fopen("mylib/myfile", "r");
| /* Put in various data. */
| vread(stream, L"%s", &s [0]);
| vread(stream, L"%ld", &l);
| vread(stream, L"%c", &c);
| vread(stream, L"%f", &fp);
| printf("string = %s\n", s);
| printf("long double = %ld\n", l);
| printf("char = %c\n", c);
| printf("float = %f\n", fp);
| }
| /*************** If myfile contains ************************
| **************** abcdefghijklmnopqrstuvwxyz 343.2 ***********
| ********************** expected output is: *********************
| string = abcdefghijklmnopqrstuvwxyz
| long double = 343
| char = .
| float = 2.000000
| */
|
| Related Information
| v “fscanf() — Read Formatted Data” on page 123
| v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
| 133
| v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
| v “scanf() — Read Data” on page 313
| v “sscanf() — Read Data” on page 339
| v “swprintf() — Format and Write Wide Characters to Buffer” on page 385
| v “swscanf() — Read Wide Character Data” on page 387
Threadsafe: Yes.
Description
The vprintf() function formats and prints a series of characters and values to
stdout. The vprintf() function works just like the printf()function, except that
arg_ptr points to a list of arguments whose number can vary from call to call in the
program. These arguments should be initialized by va_start for each call. In
contrast, the printf() function can have a list of arguments, but the number of
arguments in that list is fixed when you compile the program.
The vprintf() function converts each entry in the argument list according to the
corresponding format specifier in format. The format has the same form and
function as the format string for the printf() function.
Return Value
If successful, the vprintf() function returns the number of bytes written to stdout.
If an error occurs, the vprintf() function returns a negative value. The value of
errno may be set to ETRUNC.
int main(void)
{
FILE *stream;
stream = fopen("mylib/myfile", "w");
va_start(arg_ptr, fmt);
vprintf(fmt, arg_ptr);
va_end(arg_ptr);
}
Related Information
v “printf() — Print Formatted Characters” on page 211
v “va_arg() – va_end() – va_start() — Access Function Arguments” on page 402
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “<stdarg.h>” on page 13
v “<stdio.h>” on page 14
| Threadsafe: Yes.
| Description
| The vscanf() function reads data from stdin into locations specified by a variable
| number of arguments. The vscanf() function works just like the scanf()function,
| except that arg_ptr points to a list of arguments whose number can vary from call
| to call in the program. These arguments should be initialized by va_start for each
| call. In contrast, the scanf() function can have a list of arguments, but the number
| of arguments in that list is fixed when you compile the program.
| The vscanf() function returns the number of fields that were successfully
| converted and assigned. The return value does not include fields that were read
| but not assigned. The return value is EOF for an attempt to read at end-of-file if no
| conversion was performed. A return value of 0 means that no fields were assigned.
| This example uses the vscanf() function to read an integer, a floating point value,
| a character, and a string from stdin and then displays these values.
|
| #include <stdio.h>
| #include <stdarg.h>
| int vread(char *fmt, ...)
| {
| int rc;
| va_list arg_ptr;
| va_start(arg_ptr, fmt);
| rc = vscanf(fmt, arg_ptr);
| va_end(arg_ptr);
| return(rc);
| }
|
| int main(void)
| {
| int i, rc;
| float fp;
| char c, s[81];
| printf("Enter an integer, a real number, a character "
| "and a string : \n");
| rc = vread("%d %f %c %s", &i, &fp, &c, s);
| if (rc != 4)
| printf("Not all fields are assigned\n");
| else
| {
| printf("integer = %d\n", i);
| printf("real number = %f\n", fp);
| printf("character = %c\n", c);
| printf("string = %s\n",s);
| }
| }
| /***************** If input is: 12 2.5 a yes, *******************
| ************** then output should be similar to: ****************
| Enter an integer, a real number, a character and a string :
| integer = 12
| real number = 2.500000
| character = a
| string = yes
| */
|
| Related Information
| v “fscanf() — Read Formatted Data” on page 123
| v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
| 133
| v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
| v “scanf() — Read Data” on page 313
| v “sscanf() — Read Data” on page 339
| v “swprintf() — Format and Write Wide Characters to Buffer” on page 385
| v “swscanf() — Read Wide Character Data” on page 387
Threadsafe: Yes.
Description
The vsnprintf() function formats and stores a series of characters and values in
the buffer target-string. The vsnprintf() function works just like the snprintf()
function, except that arg_ptr points to a list of arguments whose number can vary
from call to call in the program. These arguments should be initialized by the
va_start function for each call. In contrast, the snprintf() function can have a list
of arguments, but the number of arguments in that list is fixed when you compile
the program.
The vsnprintf() function converts each entry in the argument list according to the
corresponding format specifier in format. The format has the same form and
function as the format string for the printf() function.
Return Value
The vsnprintf() function returns the number of bytes that are written in the array,
not counting the ending null character.
This example assigns a variable number of strings to string and prints the resultant
string.
#include <stdarg.h>
#include <stdio.h>
int main(void)
{
char string[100];
va_start(arg_ptr, fmt);
vsnprintf(string, 8, fmt, arg_ptr);
va_end(arg_ptr);
}
Related Information
v “printf() — Print Formatted Characters” on page 211
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “snprintf() — Print Formatted Data to Buffer” on page 334
v “va_arg() – va_end() – va_start() — Access Function Arguments” on page 402
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vsprintf() — Print Argument Data to Buffer”
v “<stdarg.h>” on page 13
v “<stdio.h>” on page 14
Threadsafe: Yes.
Description
The vsprintf() function formats and stores a series of characters and values in the
buffer target-string. The vsprintf() function works just like the sprintf() function,
except that arg_ptr points to a list of arguments whose number can vary from call
to call in the program. These arguments should be initialized by the va_start
function for each call. In contrast, the sprintf() function can have a list of
arguments, but the number of arguments in that list is fixed when you compile the
program.
The vsprintf() function converts each entry in the argument list according to the
corresponding format specifier in format. The format has the same form and
function as the format string for the printf() function.
Return Value
This example assigns a variable number of strings to string and prints the resultant
string.
#include <stdarg.h>
#include <stdio.h>
int main(void)
{
char string[100];
va_start(arg_ptr, fmt);
vsprintf(string, fmt, arg_ptr);
va_end(arg_ptr);
}
Related Information
v “printf() — Print Formatted Characters” on page 211
v “sprintf() — Print Formatted Data to Buffer” on page 335
v “va_arg() – va_end() – va_start() — Access Function Arguments” on page 402
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “<stdarg.h>” on page 13
v “<stdio.h>” on page 14
| Threadsafe: Yes.
| Description
| The vsscanf() function reads data from a buffer into locations specified by a
| variable number of arguments. The vsscanf() function works just like the
| sscanf()function, except that arg_ptr points to a list of arguments whose number
416 ILE C/C++ Run-Time Library Functions V5R3
| can vary from call to call in the program. These arguments should be initialized by
| va_start for each call. In contrast, the sscanf() function can have a list of
| arguments, but the number of arguments in that list is fixed when you compile the
| program.
| Return Value
| The vsscanf() function returns the number of fields that were successfully
| converted and assigned. The return value does not include fields that were read
| but not assigned. The return value is EOF for an attempt to read at end-of-file if no
| conversion was performed. A return value of 0 means that no fields were assigned.
| This example uses vsscanf() to read various data from the string tokenstring and
| then displays that data.
|
Threadsafe: Yes.
Description
The vswprintf() function formats and stores a series of wide characters and values
in the buffer wcsbuffer. The vswprintf() function works just like the swprintf()
function, except that argptr points to a list of wide-character arguments whose
number can vary from call to call. These arguments should be initialized by
va_start for each call. In contrast, the swprintf() function can have a list of
arguments, but the number of arguments in that list are fixed when you compile in
the program.
A null wide character is added to the end of the wide characters written; the null
wide character is not counted as part of the returned value. If copying takes place
between objects that overlap, the behavior is undefined.
Return Value
The vswprintf() function returns the number of bytes written in the array, not
counting the ending null wide character.
va_start(arg_ptr, fmt);
vswprintf(wcs, n, fmt, arg_ptr);
va_end(arg_ptr);
return;
}
int main(void)
{
wchar_t wcstr[100];
/************************************************************
The output should be similar to:
ONE 2 THREE
ONE 2 THREE 4 FIVE
************************************************************/
}
Related Information
v “swprintf() — Format and Write Wide Characters to Buffer” on page 385
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “vsprintf() — Print Argument Data to Buffer” on page 415
v “<stdarg.h>” on page 13
v “<wchar.h>” on page 17
| Threadsafe: Yes.
| Description
| The vswscanf() function reads wide data from a buffer into locations specified by
| a variable number of arguments. The vswscanf() function works just like the
| swscanf() function, except that arg_ptr points to a list of arguments whose number
| Return Value
| The vswscanf() function returns the number of fields that were successfully
| converted and assigned. The return value does not include fields that were read
| but not assigned. The return value is EOF for an attempt to read at end-of-file if no
| conversion was performed. A return value of 0 means that no fields were assigned.
| This example uses the vswscanf() function to read various data from the string
| tokenstring and then displays that data.
|
| #include <stdio.h>
| #include <stdarg.h>
| #include <wchar.h>
| int vread(const wchar_t *buffer, wchar_t *fmt, ...)
| {
| int rc;
| va_list arg_ptr;
| va_start(arg_ptr, fmt);
| rc = vswscanf(buffer, fmt, arg_ptr);
| va_end(arg_ptr);
| return(rc);
| }
| int main(void)
| {
| wchar_t *tokenstring = L"15 12 14";
| char s[81];
| char c;
| int i;
| float fp;
|
| /* Input various data */
|
| vread(tokenstring, L"%s %c%d%f", s, &c, &i, &fp);
|
| /* Display the data */
| printf("\nstring = %s\n",s);
| printf("character = %c\n",c);
| printf("integer = %d\n",i);
| printf("floating-point number = %f\n",fp);
|
| }
| /***************** Output should be similar to: *****************
| string = 15
| character = 1
| integer = 2
| floating-point number = 14.000000
|
| *******************************************************************/
|
| Related Information
| v “fscanf() — Read Formatted Data” on page 123
Threadsafe: Yes.
Description
The vwprintf() function is equivalent to the wprintf() function, except that the
variable argument list is replaced by arg, which the va_start macro (and possibly
subsequent va_arg calls) will have initialized. The vwprintf() function does not
invoke the va_end macro.
Return Value
This example prints the wide character a. The printing is done from the vout()
function, which takes a variable number of arguments and uses the
vwprintf()function to print them to stdout.
int main(void) {
FILE *stream;
wchar_t format[] = L"%lc";
setlocale(LC_ALL, "POSIX");
vout (format, L’a’);
return(0);
va_list arg_ptr;
va_start (arg_ptr, fmt);
vwprintf (fmt, arg_ptr);
va_end (arg_ptr);
}
Related Information
v “printf() — Print Formatted Characters” on page 211
v “vfprintf() — Print Argument Data to Stream” on page 404
v “vprintf() — Print Argument Data” on page 411
v “btowc() — Convert Single Byte to Wide Character” on page 55
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “vfwprintf() — Format Argument Data as Wide Characters and Write to a
Stream” on page 407
v “<stdarg.h>” on page 13
v “<wchar.h>” on page 17
| Threadsafe: Yes.
| Description
| The vwscanf() function reads data from stdin into locations specified by a variable
| number of arguments. The vwscanf() function works just like the wscanf()
| Return Value
| The vwscanf() function returns the number of fields that were successfully
| converted and assigned. The return value does not include fields that were read
| but not assigned. The return value is EOF for an attempt to read at end-of-file if no
| conversion was performed. A return value of 0 means that no fields were assigned.
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
given 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 will be
stored. If wc is a null wide character, the resulting state described will be the initial
conversions state.
Return Value
If s is a null pointer, the wcrtomb() function returns the number of bytes needed to
enter the initial shift state. The value returned will not be greater than that of the
MB_CUR_MAX macro.
If s is not a null pointer, the wcrtomb() function returns the number of bytes stored
in the array object (including any shift sequences) when wc is a valid wide
character; otherwise (when wc is not a valid wide character), an encoding error
occurs, the value of the macro EILSEQ shall be stored in errno and -1 will be
returned, but the conversion state will be unchanged.
#define STRLENGTH 10
#define LOCNAME "qsys.lib/JA_JP.locale"
#define LOCNAME_EN "qsys.lib/EN_US.locale"
int main(void)
{
char string[STRLENGTH];
int length, sl = 0;
wchar_t wc = 0x4171;
wchar_t wc2 = 0x00C1;
wchar_t wc_string[10];
mbstate_t ps = 0;
memset(string, ’\0’, STRLENGTH);
wc_string[0] = 0x00C1;
wc_string[1] = 0x4171;
wc_string[2] = 0x4172;
wc_string[3] = 0x00C2;
wc_string[4] = 0x0000;
/* In this first example we will convert a wide character */
/* to a single byte character. We first set the locale */
/* to a single byte locale. We choose a locale with */
/* CCSID 37. For single byte cases the state will always */
/* remain in the initial state 0 */
sl += length;
sl += length;
}
/* The output should look like this:
string = A
length = 1, state = 0
length = 3, state = 2
length = 2, state = 2
length = 2, state = 0
length = 4, state = 0
*/
#define STRLENGTH 10
int main(void)
{
char string[STRLENGTH];
int length, sl = 0;
wchar_t wc = 0x4171;
wchar_t wc2 = 0x0041;
wchar_t wc_string[10];
mbstate_t ps = 0;
memset(string, ’\0’, STRLENGTH);
wc_string[0] = 0x0041;
wc_string[1] = 0xFF31;
wc_string[2] = 0xFF32;
wc_string[3] = 0x0042;
wc_string[4] = 0x0000;
/* In this first example we will convert a UNICODE character */
/* to a single byte character. We first set the locale */
/* to a single byte locale. We choose a locale with */
/* CCSID 37. For single byte cases the state will always */
/* remain in the initial state 0 */
sl += length;
sl += length;
}
/* The output should look like this:
string = A
length = 1, state = 0
length = 3, state = 2
length = 2, state = 2
length = 2, state = 0
*/
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)” on page
183
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “wctomb() — Convert Wide Character to Multibyte Character” on page 469
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wcscat() function appends a copy of the string pointed to by string2 to the
end of the string pointed to by string1.
Return Value
This example creates the wide character string ″computer program″ using the
wcscat() function.
#include <stdio.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
wchar_t buffer1[SIZE] = L"computer";
wchar_t * string = L" program";
wchar_t * ptr;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strncat() — Concatenate Strings” on page 361
v “wcschr() — Search for Wide Character”
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
Return Value
The wcschr() function returns a pointer to the first occurrence of character in string.
If the character is not found, a NULL pointer is returned.
This example finds the first occurrence of the character ″p″ in the wide-character
string ″computer program″.
#include <stdio.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
wchar_t buffer1[SIZE] = L"computer program";
wchar_t * ptr;
wchar_t ch = L’p’;
Related Information
v “strchr() — Search for Character” on page 342
v “strcspn() — Find Offset of First Character Match” on page 348
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcsspn() — Find Offset of First Non-matching Wide Character” on page 453
v “wcswcs() — Locate Wide-Character Substring” on page 465
Threadsafe: Yes.
Description
Return Value
The wcscmp() function returns a value indicating the relationship between the two
strings, as follows:
Value Meaning
Less than 0
string1 less than string2
0 string1 identical to string2
Greater than 0
string1 greater than string2.
This example compares the wide-character string string1 to string2 using wcscmp().
#include <stdio.h>
#include <wcstr.h>
int main(void)
{
int result;
wchar_t string1[] = L"abcdef";
wchar_t string2[] = L"abcdefg";
if ( result == 0 )
printf( "\"%ls\" is identical to \"%ls\"\n", string1, string2);
else if ( result < 0 )
printf( "\"%ls\" is less than \"%ls\"\n", string1, string2 );
else
printf( "\"%ls\" is greater than \"%ls\"\n", string1, string2);
}
Threadsafe: Yes.
Description
Return Value
#include <stdio.h>
#include <wchar.h>
int main(void)
{
int result;
wchar_t *wcs1 = L"first_wide_string";
wchar_t *wcs2 = L"second_wide_string";
if ( result == 0)
printf("\"%S\" is identical to \"%S\"\n", wcs1, wcs2);
else if ( result < 0)
printf("\"%S\" is less than \"%S\"\n", wcs1, wcs2);
else
printf("\"%S\" is greater than \"%S\"\n", wcs1, wcs2);
}
Related Information
v “strcoll() — Compare Strings” on page 346
v “setlocale() — Set Locale” on page 322
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wcscpy() function copies the contents of string2 (including the ending wchar_t
null character) into string1.
Return Value
#include <stdio.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
wchar_t source[ SIZE ] = L"This is the source string";
wchar_t destination[ SIZE ] = L"And this is the destination string";
wchar_t * return_string;
Related Information
v “strcpy() — Copy Strings” on page 347
v “strncpy() — Copy Strings” on page 364
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscspn() — Find Offset of First Wide-Character Match”
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
The wcscspn() function determines the number of wchar_t characters in the initial
segment of the string pointed to by string1 that do not appear in the string pointed
to by string2.
Return Value
This example uses wcscspn() to find the first occurrence of any of the characters a,
x, l, or e in string.
#include <stdio.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
wchar_t string[SIZE] = L"This is the source string";
wchar_t * substring = L"axle";
printf( "The first %i characters in the string \"%ls\" are not in the "
"string \"%ls\" \n", wcscspn( string, substring),
string, substring );
}
The first 10 characters in the string "This is the source string" are not
in the string "axle"
*/
Related Information
v “strcspn() — Find Offset of First Character Match” on page 348
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcsspn() — Find Offset of First Non-matching Wide Character” on page 453
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
The wcsftime() function converts the time and date specification in the timeptr
structure into a wide-character string. It then stores the null-ended string in the
array pointed to by wdest according to the format string pointed to by format. The
The wcsftime() function works just like the strftime() function, except that it uses
wide characters. The format string is a wide-character character string that
contains:
v Conversion-specification characters.
v Ordinary wide characters, which are copied into the array unchanged.
This function uses the time structure pointed to by timeptr, and if the specifier is
locale sensitive, then it will also use the LC_TIME category of the current locale to
determine the appropriate replacement value of each valid specifier. The time
structure pointed to by timeptr is usually obtained by calling the gmtime() or
localtime()function.
Return Value
If the total number of wide characters in the resulting string, including the ending
null wide character, does not exceed maxsize, wcsftime() returns the number of
wide characters placed into wdest, not including the ending null wide character.
Otherwise, the wcsftime() function returns 0 and the contents of the array are
indeterminate.
This example obtains the date and time using localtime(), formats the information
with the wcsftime(), and prints the date and time.
#include <stdio.h>
#include <time.h>
#include <wchar.h>
int main(void)
{
struct tm *timeptr;
wchar_t dest[100];
time_t temp;
size_t rc;
temp = time(NULL);
timeptr = localtime(&temp);
rc = wcsftime(dest, sizeof(dest), L" Today is %A,"
L" %b %d.\n Time: %I:%M %p", timeptr);
printf("%d characters placed in string to make:\n\n%ls\n", rc, dest);
return 0;
/********************************************************************
The output should be similar to:
Related Information
v “gmtime() — Convert Time” on page 151
v “localtime() — Convert Time” on page 173
v “strftime() — Convert Date/Time to String” on page 354
v “strptime()— Convert String to Date/Time” on page 369
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The __wcsicmp() function compares string1 and string2 without sensitivity to case.
All alphabetic wide characters in string1 and string2 are converted to lowercase
before comparison. The function operates on null terminated wide character
strings. The string arguments to the function are expected to contain a wchar_t null
character (L’\0’) marking the end of the string.
Return Value
int main(void)
{
wchar_t *str1 = L"STRING";
if (result == 0)
printf("Strings compared equal.\n");
else if (result < 0)
printf("\"%ls\" is less than \"%ls\".\n", str1, str2);
else
printf("\"%ls\" is greater than \"%ls\".\n", str1, str2);
return 0;
}
***********************************/
Related Information
v “strcmp() — Compare Strings” on page 343
v “strncmp() — Compare Strings” on page 362
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcschr() — Search for Wide Character” on page 431
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcslen() — Calculate Length of Wide-Character String”
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “__wcsnicmp() — Compare Wide Character Strings without Case Sensitivity” on
page 446
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wcslen() function computes the number of wide characters in the string
pointed to by string.
Return Value
The wcslen() function returns the number of wide characters in string, excluding
the ending wchar_t null character.
#include <stdio.h>
#include <wcstr.h>
int main(void)
{
wchar_t * string = L"abcdef";
Length of "abcdef" is 6
*/
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “strlen() — Determine String Length” on page 358
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “<wcstr.h>” on page 17
| Threadsafe: Yes.
| Description
| The wcslocaleconv() function is the same as the localeconv function, except that it
| returns a pointer to a wcslconv structure, which is the wide version of a lconv
| structure. These elements are determined by the LC_UNI_MONETARY and
| LC_UNI_NUMERIC categories of the current locale.
| Return Value
| This example prints out the Unicode currency symbol for a French locale.
|
Threadsafe: Yes.
Description
The wcsncat() function appends up to count wide characters from string2 to the
end of string1, and appends a wchar_t null character to the result.
Return Value
#include <stdio.h>
#include <wcstr.h>
#include <string.h>
#define SIZE 40
int main(void)
{
wchar_t buffer1[SIZE] = L"computer";
wchar_t * ptr;
Related Information
v “strcat() — Concatenate Strings” on page 341
v “strncat() — Concatenate Strings” on page 361
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcsncmp() — Compare Wide-Character Strings”
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
Return Value
The wcsncmp() function returns a value indicating the relationship between the two
strings, as follows:
Value Meaning
Less than 0
string1 less than string2
0 string1 identical to string2
Greater than 0
string1 greater than string2.
This example demonstrates the difference between the wcscmp() function, which
compares the entire strings, and the wcsncmp() function, which compares only a
specified number of wide characters in the strings.
#define SIZE 10
int main(void)
{
int result;
int index = 3;
wchar_t buffer1[SIZE] = L"abcdefg";
wchar_t buffer2[SIZE] = L"abcfg";
void print_result( int, wchar_t *, wchar_t * );
Related Information
v “strcmp() — Compare Strings” on page 343
v “strcoll() — Compare Strings” on page 346
v “strncmp() — Compare Strings” on page 362
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “wcsncpy() — Copy Wide-Character Strings”
v “<wcstr.h>” on page 17
Threadsafe: Yes,
The wcsncpy() function copies up to count wide characters from string2 to string1.
If string2 is shorter than count characters, string1 is padded out to count characters
with wchar_t null characters.
Return Value
Related Information
v “strcpy() — Copy Strings” on page 347
v “strncpy() — Copy Strings” on page 364
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcsncat() — Concatenate Wide-Character Strings” on page 442
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
The __wcsnicmp() function operates on null terminated wide character strings. The
string arguments to the function are expected to contain a wchar_t null character
(L’\0’) marking the end of the string.
Return Value
int main(void)
{
wchar_t *str1 = L"STRING ONE";
wchar_t *str2 = L"string TWO";
int result;
if (result == 0)
printf("Strings compared equal.\n");
else if (result < 0)
printf("\"%ls\" is less than \"%ls\".\n", str1, str2);
else
printf("\"%ls\" is greater than \"%ls\".\n", str1, str2);
return 0;
}
/******** The output should be similar to: ***************
***********************************/
Related Information
v “strcmp() — Compare Strings” on page 343
v “strncmp() — Compare Strings” on page 362
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcschr() — Search for Wide Character” on page 431
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “__wcsicmp() — Compare Wide Character Strings without Case Sensitivity” on
page 439
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wcspbrk() function locates the first occurrence in the string pointed to by
string1 of any wide character from the string pointed to by string2.
The wcspbrk() function returns a pointer to the character. If string1 and string2
have no wide characters in common, the wcspbrk()function returns NULL.
This example uses wcspbrk() to find the first occurrence of either ″a″ or ″b″ in the
array string.
#include <stdio.h>
#include <wcstr.h>
int main(void)
{
wchar_t * result;
wchar_t * string = L"The Blue Danube";
wchar_t *chars = L"ab";
The first occurrence of any of the characters "ab" in "The Blue Danube"
is "anube"
******************************************************************/
Related Information
v “strchr() — Search for Character” on page 342
v “strcspn() — Find Offset of First Character Match” on page 348
v “strpbrk() — Find Characters in String” on page 367
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “<wcstr.h>” on page 17
| Threadsafe: Yes.
| Description
| Return Value
| Related Information
Threadsafe: Yes,
Description
The wcsrchr() function locates the last occurrence of character in the string pointed
to by string. The ending wchar_t null character is considered to be part of the
string.
Return Value
This example compares the use of wcschr() and wcsrchr(). It searches the string
for the first and last occurrence of p in the wide character string.
#define SIZE 40
int main(void)
{
wchar_t buf[SIZE] = L"computer program";
wchar_t * ptr;
int ch = ’p’;
Related Information
v “strchr() — Search for Character” on page 342
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strcspn() — Find Offset of First Character Match” on page 348
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “<wcstr.h>” on page 17
#include <wchar.h>
size_t wcsrtombs (char *dst, const wchar_t **src, size_t len,
mbstate_t *ps);
Description
If dst is not a null pointer, the object pointed to by src will be assigned either a null
pointer (if conversion stopped due to reaching a ending null character) or the
address of the code just past the last wide character converted. If conversion
stopped due to reaching a ending null wide character, the resulting state described
will be the initial conversion state.
Return Value
If the first code is not a valid wide character, an encoding error will occur.
wcsrtombs() stores the value of the macro EILSEQ in errno and returns (size_t) -1,
but the conversion state will be unchanged. Otherwise it returns the number of
bytes in the resulting multibyte character sequence, which is the same as the
number of array elements changed when dst is not a null pointer.
#define SIZE 20
int main(void)
{
char dest[SIZE];
wchar_t *wcs = L"string";
wchar_t *ptr;
size_t count = SIZE;
size_t length;
mbstate_t ps = 0;
Related Information
v “mblen() — Determine Length of a Multibyte Character” on page 182
v “mbrlen() — Determine Length of a Multibyte Character (Restartable)” on page
183
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “mbsrtowcs() — Convert a Multibyte String to a Wide Character String
(Restartable)” on page 191
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcstombs() — Convert Wide-Character String to Multibyte String” on page 460
v “<wchar.h>” on page 17
Threadsafe: Yes,
The wcsspn() function computes the number of wide characters in the initial
segment of the string pointed to by string1, which consists entirely of wide
characters from the string pointed to by string2.
Return Value
The wcsspn() function returns the number of wide characters in the segment.
This example finds the first occurrence in the array string of a wide character that
is not an a, b, or c. Because the string in this example is cabbage, the wcsspn()
function returns 5, the index of the segment of cabbage before a character that is
not an a, b, or c.
#include <stdio.h>
#include <wcstr.h>
int main(void)
{
wchar_t * string = L"cabbage";
wchar_t * source = L"abc";
int index;
Related Information
v “strchr() — Search for Character” on page 342
v “strcspn() — Find Offset of First Character Match” on page 348
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “wcscat() — Concatenate Wide-Character Strings” on page 430
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcsspn() — Find Offset of First Non-matching Wide Character” on page 453
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
Return Value
The wcsstr() function returns a pointer to the beginning of the first occurrence of
wcs2 in wcs1. If wcs2 does not appear in wcs1, the wcsstr() function returns NULL.
If wcs2 points to a wide-character string with zero length, it returns wcs1.
This example uses the wcsstr() function to find the first occurrence of ″hay″ in the
wide-character string ″needle in a haystack″.
#include <stdio.h>
#include <wchar.h>
int main(void)
{
wchar_t *wcs1 = L"needle in a haystack";
wchar_t *wcs2 = L"hay";
/***********************************************
The output should be similar to:
result: "haystack"
***********************************************/
}
Related Information
v “strstr() — Locate Substring” on page 375
v “wcschr() — Search for Wide Character” on page 431
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcswcs() — Locate Wide-Character Substring” on page 465
v “<wchar.h>” on page 17
Description
The wcstod() function converts the initial portion of the wide-character string
pointed to by nptr to a double value. The nptr parameter points to a sequence of
characters that can be interpreted as a numerical value of type double. The
wcstod() function stops reading the string at the first character that it cannot
recognize as part of a number. This character can be the wchar_t null character at
the end of the string.
The behavior of the wcstod() function is affected by the LC_CTYPE category of the
current locale.
Return Value
The wcstod() function returns the converted double value. If no conversion could
be performed, the wcstod() function returns 0. If the correct value is outside the
range of representable values, the wcstod() function returns +HUGE_VAL or
-HUGE_VAL (according to the sign of the value), and sets errno to ERANGE. If the
correct value would cause underflow, the wcstod() function returns 0 and sets
errno to ERANGE. If the string nptr points to is empty or does not have the
expected form, no conversion is performed, and the value of nptr is stored in the
object pointed to by endptr, provided that endptr is not a null pointer.
This example uses the wcstod() function to convert the string wcs to a
floating-point value.
#include <stdio.h>
#include <wchar.h>
int main(void)
{
wchar_t *wcs = L"3.1415926This stopped it";
wchar_t *stopwcs;
/**************************************************
The output should be similar to:
Threadsafe: Yes.
Description
The wcstok() function reads wcs1 as a series of zero or more tokens and wcs2 as
the set of wide characters serving as delimiters for the tokens in wcs1. A sequence
of calls to the wcstok() function locates the tokens inside wcs1. The tokens can be
separated by one or more of the delimiters from wcs2. The third argument points
to a wide-character pointer that you provide where the wcstok() function stores
information necessary for it to continue scanning the same string.
When the wcstok() function is first called for the wide-character string wcs1, it
searches for the first token in wcs1, skipping over leading delimiters. The wcstok()
function returns a pointer to the first token. To read the next token from wcs1, call
the wcstok() function with NULL as the first parameter (wcs1). This NULL
parameter causes the wcstok() function to search for the next token in the previous
token string. Each delimiter is replaced by a null character to end the token.
The wcstok() function always stores enough information in the pointer ptr so that
subsequent calls, with NULL as the first parameter and the unmodified pointer
value as the third, will start searching right after the previously returned token.
You can change the set of delimiters (wcs2) from call to call.
Return Value
The wcstok() function returns a pointer to the first wide character of the token, or
a null pointer if there is no token. In later calls with the same token string, the
wcstok() function returns a pointer to the next token in the string. When there are
no more tokens, the wcstok() function returns NULL.
This example uses the wcstok() function to locate the tokens in the wide-character
string str1.
#include <stdio.h>
#include <wchar.h>
/********************************************************************
The output should be similar to:
t = ’a’
t = ’?b’
t = ’’
t = ’c’
t = ’’
********************************************************************/
}
Related Information
v “strtok() — Tokenize String” on page 378
v “<wchar.h>” on page 17
Format (wcstoll())
#include <wchar.h>
long long int wcstoll(const wchar_t *nptr, wchar_t **endptr, int base);
Threadsafe: Yes.
Description
The wcstol() function converts the initial portion of the wide-character string
pointed to by nptr to a long integer value. The nptr parameter points to a sequence
of wide characters that can be interpreted as a numerical value of type long int.
The wcstol()function stops reading the string at the first wide character that it
cannot recognize as part of a number. This character can be the wchar_t null
character at the end of the string. The ending character can also be the first
numeric character greater than or equal to the base.
The behavior of the wcstol() function is affected by the LC_CTYPE category of the
current locale.
458 ILE C/C++ Run-Time Library Functions V5R3
| Note: This function is not available when LOCALETYPE(*CLD) is specified on the
| compilation command.
If the value of the endptr parameter is not null, then a pointer to the character that
ended the scan is stored in endptr. If a long long integer cannot be formed, the
value of the endptrparameter is set to that of the nptr parameter.
If the base parameter is a value between 2 and 36, the subject sequence’s expected
form is a sequence of letters and digits representing a long long integer whose
radix is specified by the base parameter. This sequence optionally is preceded by a
positive (+) or negative (-) sign. Letters from a (or A) to z (or Z) inclusive are
ascribed the values 10 to 35; only letters whose ascribed values are less than that of
the base parameter are permitted. If the base parameter has a value of 16, the
characters 0x or 0X optionally precede the sequence of letters and digits, following
the positive (+) or negative (-) sign, if present.
If the value of the base parameter is 0, the string determines the base. Therefore,
after an optional leading sign, a leading 0 indicates octal conversion, and a leading
0x or 0X indicates hexadecimal conversion.
Return Value
The wcstol() function returns the converted long integer value. If no conversion
could be performed, the wcstol() function returns 0. If the correct value is outside
the range of representable values, the wcstol()function returns LONG_MAX or
LONG_MIN (according to the sign of the value), and sets errno to ERANGE. If the
string nptr points to is empty or does not have the expected form, no conversion is
performed, and the value of nptr is stored in the object pointed to by endptr,
provided that endptr is not a null pointer.
Upon successful completion, the wcstoll() subroutine returns the converted value.
If no conversion could be performed, 0 is returned, and the errno global variable is
set to indicate the error. If the correct value is outside the range of representable
values, the wcstoll() subroutine returns a value of LONG_LONG_MAX or
LONG_LONG_MIN.
The value of errno may be set to ERANGE (range error), or EINVAL (invalid
argument).
This example uses the wcstol() function to convert the wide-character string wcs
to a long integer value.
#include <stdio.h>
#include <wchar.h>
/*******************************************************
The output should be similar to:
wcs = "10110134932"
wcstol = 45
Stopped scan at "34932"
wcstol = 4423
Stopped scan at "4932"
wcstol = 2134108
Stopped scan at "932"
*******************************************************/
}
Related Information
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “strtoul() — strtoull() — Convert Character String to Unsigned Long and
Unsigned Long Long Integer” on page 382
v “wcstod() — Convert Wide-Character String to Double” on page 455
v “wcstoul() — wcstoull() — Convert WideCharacter String to Unsigned Long and
Unsigned Long Long Integer” on page 463
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
| Return Value
| The wcstombs() function returns the length in bytes of the multibyte character
| string, not including a ending null character. The value (size_t)-1 is returned if an
| invalid multibyte character is encountered.
| The value of errno may be set to EILSEQ (conversion stopped due to input
| character), or ECONVERT (conversion error).
| Related Information
| v “mbstowcs() — Convert a Multibyte String to a Wide Character String” on page
| 192
| v “wcslen() — Calculate Length of Wide-Character String” on page 440
| v “wcsrtombs() — Convert Wide Character String to Multibyte String
| (Restartable)” on page 451
| v “wctomb() — Convert Wide Character to Multibyte Character” on page 469
| v “<stdlib.h>” on page 15
|
| wcstoul() — wcstoull() — Convert WideCharacter String to Unsigned
| Long and Unsigned Long Long Integer
| Format (wcstoul())
| #include <wchar.h>
| unsigned long int wcstoul(const wchar_t *nptr, wchar_t **endptr, int base);
| Format (wcstoull())
| #include <wchar.h>
| unsigned long long int wcstoull(const wchar_t *nptr, wchar_t **endptr, int base);
| Threadsafe: Yes.
| Description
If the value of the endptr parameter is not null, then a pointer to the character that
ended the scan is stored in endptr. If an unsigned long long integer cannot be
formed, the value of the endptr parameter is set to that of the nptr parameter.
If the base parameter is a value between 2 and 36, the subject sequence’s expected
form is a sequence of letters and digits representing an unsigned long long integer
whose radix is specified by the base parameter. This sequence optionally is
preceded by a positive (+) or negative (-) sign. Letters from a (or A) to z (or Z)
inclusive are ascribed the values 10 to 35; only letters whose ascribed values are
less than that of the base parameter are permitted. If the base parameter has a value
of 16, the characters 0x or 0X optionally precede the sequence of letters and digits,
following the positive (+) or negative (-) sign, if present.
If the value of the base parameter is 0, the string determines the base. Therefore,
after an optional leading sign, a leading 0 indicates octal conversion, and a leading
0x or 0X indicates hexadecimal conversion.
The value of errno may be set to EINVAL (endptr is null, no numbers are found, or
base is invalid), or ERANGE (converted value is outside the range).
Return Value
The wcstoul() function returns the converted unsigned long integer value. If no
conversion could be performed, the wcstoul() function returns 0. If the correct
value is outside the range of representable values, The wcstoul() function returns
ULONG_MAX and sets errno to ERANGE. If the string nptr points to is empty or
does not have the expected form, no conversion is performed, and the value of
nptr is stored in the object pointed to by endptr, provided that endptr is not a null
pointer.
This example uses the wcstoul() function to convert the string wcs to an unsigned
long integer value.
#include <stdio.h>
#include <wchar.h>
#define BASE 2
int main(void)
{
wchar_t *wcs = L"1000e13 camels";
wchar_t *endptr;
unsigned long int answer;
/*********************************************************************
The output should be similar to:
Related Information
v “strtod() — Convert Character String to Double” on page 376
v “strtol() — strtoll() — Convert Character String to Long and Long Long Integer”
on page 380
v “wcstod() — Convert Wide-Character String to Double” on page 455
v “wcstol() — wcstoll() — Convert Wide Character String to Long and Long Long
Integer” on page 458
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wcswcs() function locates the first occurrence of string2 in the wide-character
string pointed to by string1. In the matching process, the wcswcs() function ignores
the wchar_t null character that ends string2.
Return Value
This example finds the first occurrence of the wide character string pr in buffer1.
#include <stdio.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
wchar_t buffer1[SIZE] = L"computer program";
wchar_t * ptr;
wchar_t * wch = L"pr";
Related Information
v “strchr() — Search for Character” on page 342
v “strcspn() — Find Offset of First Character Match” on page 348
v “strpbrk() — Find Characters in String” on page 367
v “strrchr() — Locate Last Occurrence of Character in String” on page 373
v “strspn() —Find Offset of First Non-matching Character” on page 374
v “strstr() — Locate Substring” on page 375
v “wcschr() — Search for Wide Character” on page 431
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcscspn() — Find Offset of First Wide-Character Match” on page 436
v “wcspbrk() — Locate Wide Characters in String” on page 447
v “wcsrchr() — Locate Last Occurrence of Wide Character in String” on page 450
v “wcsspn() — Find Offset of First Non-matching Wide Character” on page 453
v “<wcstr.h>” on page 17
Threadsafe: Yes.
Description
Return Value
int main(void)
{
wchar_t *wcs = L"ABC";
Related Information
v “wcswidth() — Determine the Display Width of a Wide Character String” on
page 466
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
Return Value
The wcsxfrm() function returns the length of the transformed wide-character string
(not including the ending null wide character code). If the value returned is n or
more, the contents of the array pointed to by wcs1 are indeterminate.
#include <stdio.h>
#include <wchar.h>
int main(void)
{
wchar_t *wcs;
wchar_t buffer[80];
int length;
Related Information
v “strxfrm() — Transform String” on page 384
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
Return Value
This example uses the wctob() function to test if the wide character A is a valid
single-byte character.
#include <stdio.h>
#include <wchar.h>
int main(void)
{
wint_t wc = L’A’;
if (wctob(wc) == wc)
printf("%lc is a valid single byte character\n", wc);
else
printf("%lc is not a valid single byte character\n", wc);
return 0;
/************************************************************
The output should be similar to:
Related Information
v “mbtowc() — Convert Multibyte Character to a Wide Character” on page 196
v “wctomb() — Convert Wide Character to Multibyte Character”
v “wcstombs() — Convert Wide-Character String to Multibyte String” on page 460
v “<wchar.h>” on page 17
Description
The conversion of the wide character is the same as described in wcstombs(). See
this function for a Unicode example.
Return Value
The wctomb() function returns the length in bytes of the multibyte character. The
value -1 is returned if character is not a valid multibyte character. If string is a
NULL pointer, the wctomb() function returns nonzero if shift-dependent encoding
is used, or 0 otherwise.
#include <stdio.h>
#include <stdlib.h>
#include <wcstr.h>
#define SIZE 40
int main(void)
{
static char buffer[ SIZE ];
wchar_t wch = L’c’;
int length;
Related Information
v “mbtowc() — Convert Multibyte Character to a Wide Character” on page 196
v “wcslen() — Calculate Length of Wide-Character String” on page 440
v “wcrtomb() — Convert a Wide Character to a Multibyte Character (Restartable)”
on page 425
v “wcstombs() — Convert Wide-Character String to Multibyte String” on page 460
v “wcsrtombs() — Convert Wide Character String to Multibyte String
(Restartable)” on page 451
v “<stdlib.h>” on page 15
Threadsafe: Yes.
Description
The wctrans() function constructs a value with type wctrans_t. This value
describes a mapping between wide characters identified by the string argument
property. The two strings listed under the towctrans() function description shall be
valid in all locales as property arguments to the wctrans() function.
Return Value
int main()
{
char *alpha = "abcdefghijklmnopqrstuvwxyz";
char *tocase[2] = {"toupper", "tolower"};
wchar_t *wcalpha;
int i, j;
size_t alphalen;
alphalen = strlen(alpha)+1;
wcalpha = (wchar_t *)malloc(sizeof(wchar_t)*alphalen);
*******************************************************************/
Related Information
v “towctrans() — Translate Wide Character” on page 396
v “<wctype.h>” on page 17
Threadsafe: Yes.
Description
The wctype() function is defined for valid property names as defined in the
current locale. The property is a string that identifies a generic character class for
which locale specific type information is required. The function returns a value of
type wctype_t, which can be used as the second argument to a call of the
iswctype() function.
Return Value
| The wctype() function returns zero if the given property name is not valid for the
| current locale (category LC_CTYPE). Otherwise it returns a value of type wctype_t
| that can be used in calls to iswctype().
Threadsafe: Yes.
Description
The wcwidth() function determines the number of printing positions that a graphic
representation of wc occupies on a display device. Each of the printing wide
characters occupies its own number of printing positions on a display device. The
number is independent of its location on the device.
Return Value
#include <stdio.h>
#include <wchar.h>
int main(void)
{
wint_t wc = L’A’;
/**************************************************************************
The output should be similar to :
A has a width of 1
**************************************************************************/
Threadsafe: Yes
Description
Threadsafe: Yes.
Description
The wmemchr() function locates the first occurrence of c in the initial n wide
characters of the object pointed to by s. If n has the value 0, the wmemchr() function
finds no occurrence of c, and returns a NULL pointer.
Return Value
The wmemchr() function returns a pointer to the located wide character, or a NULL
pointer if the wide character does not occur in the object.
This example finds the first occurrence of ’A’ in the wide-character string.
main()
{
wchar_t *in = L"1234ABCD";
wchar_t *ptr;
wchar_t fnd = L’A’;
printf("\nEXPECTED: ABCD");
ptr = wmemchr(in, L’A’, 6);
if (ptr == NULL)
printf("\n** ERROR ** ptr is NULL, char L’A’ not found\n");
else
printf("\nRECEIVED: %ls \n", ptr);
}
Related Information
v “memchr() — Search Buffer” on page 197
v “strchr() — Search for Character” on page 342
v “wcschr() — Search for Wide Character” on page 431
v “wmemcmp() —Compare Wide-Character Buffers”
v “wmemcpy() —Copy Wide-Character Buffer” on page 478
v “wmemmove() — Copy Wide-Character Buffer” on page 479
v “wmemset() — Set Wide Character Buffer to a Value” on page 480
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wmemcmp() function compares the first n wide characters of the object pointed
to by s1 to the first n wide characters of the object pointed to by s2. If n has the
value 0, the wmemcmp() function returns 0.
Return Value
The wmemcmp() function returns a value according to the relationship between the
two strings, s1 and s2:
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
main()
{
int rc;
wchar_t *in = L"12345678";
wchar_t *out = L"12AAAAAB";
setlocale(LC_ALL, "POSIX");
/******************************************************
The output should be:
Related Information
v “memcmp() — Compare Buffers” on page 198
v “strcmp() — Compare Strings” on page 343
v “wcscmp() — Compare Wide-Character Strings” on page 433
v “wcsncmp() — Compare Wide-Character Strings” on page 443
v “wmemchr() —Locate Wide Character in Wide-Character Buffer” on page 476
v “wmemcpy() —Copy Wide-Character Buffer”
v “wmemmove() — Copy Wide-Character Buffer” on page 479
v “wmemset() — Set Wide Character Buffer to a Value” on page 480
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
Return Value
This example copies the first four characters from out to in. In the expected output,
the first four characters in both strings will be ″ABCD″.
#include <wchar.h>
#include <stdio.h>
main()
{
wchar_t *in = L"12345678";
wchar_t *out = L"ABCDEFGH";
wchar_t *ptr;
Related Information
v “memcpy() — Copy Bytes” on page 199
v “strcpy() — Copy Strings” on page 347
v “strncpy() — Copy Strings” on page 364
v “wcscpy() — Copy Wide-Character Strings” on page 435
v “wcsncpy() — Copy Wide-Character Strings” on page 445
v “wmemchr() —Locate Wide Character in Wide-Character Buffer” on page 476
v “wmemcmp() —Compare Wide-Character Buffers” on page 477
v “wmemmove() — Copy Wide-Character Buffer”
v “wmemset() — Set Wide Character Buffer to a Value” on page 480
v “<wchar.h>” on page 17
Threadsafe: Yes.
The wmemmove() function copies n wide characters from the object pointed to by s2
to the object pointed to by s1. Copying takes place as if the n wide characters from
the object pointed to by s2 are first copied into a temporary array, of n wide
characters, that does not overlap the objects pointed to by s1 or s2. Then, the
wmemmove() function copies the n wide characters from the temporary array into
the object pointed to by s1. If n has the value 0, the wmemmove() function copies 0
wide characters.
Return Value
This example copies the first five characters in a string to overlay the last five
characters in the same string. Since the string is only nine characters long, the
source and target overlap.
#include <wchar.h>
#include <stdio.h>
void main()
{
wchar_t *theString = L"ABCDEFGHI";
return;
/********************************************************
The output should be:
Related Information
v “memmove() — Copy Bytes” on page 202
v “wmemchr() —Locate Wide Character in Wide-Character Buffer” on page 476
v “wmemcpy() —Copy Wide-Character Buffer” on page 478
v “wmemcmp() —Compare Wide-Character Buffers” on page 477
v “wmemset() — Set Wide Character Buffer to a Value”
v “<wchar.h>” on page 17
Threadsafe: Yes.
The wmemset() function copies the value of c into each of the first n wide
characters of the object pointed to by s. If n has the value 0, the wmemset() function
copies 0 wide characters.
Return Value
This example sets the first 6 wide characters to the wide character ’A’.
#include <wchar.h>
#include <stdio.h>
void main()
{
wchar_t *in = L"1234ABCD";
wchar_t *ptr;
printf("\nEXPECTED: AAAAAACD");
ptr = wmemset(in, L’A’, 6);
if (ptr == in)
printf("\nResults returned - %ls \n", ptr);
else
{
printf("\n** ERROR ** wrong pointer returned\n");
}
}
Related Information
v “memset() — Set Bytes to Value” on page 203
v “wmemchr() —Locate Wide Character in Wide-Character Buffer” on page 476
v “wmemcpy() —Copy Wide-Character Buffer” on page 478
v “wmemcmp() —Compare Wide-Character Buffers” on page 477
v “wmemmove() — Copy Wide-Character Buffer” on page 479
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
This example prints the wide character a. Date and time may be formatted
according to your locale’s representation. The output goes to stdout.
#include <wchar.h>
#include <stdarg.h>
#include <locale.h>
int main(void)
{
setlocale(LC_ALL, "POSIX");
wprintf (L"%c\n", L’a’);
return(0);
}
Related Information
v “printf() — Print Formatted Characters” on page 211
v “btowc() — Convert Single Byte to Wide Character” on page 55
v “mbrtowc() — Convert a Multibyte Character to a Wide Character (Restartable)”
on page 186
v “vfwprintf() — Format Argument Data as Wide Characters and Write to a
Stream” on page 407
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “vswprintf() — Format and Write Wide Characters to Buffer” on page 418
v “<wchar.h>” on page 17
Threadsafe: Yes.
Description
The wscanf() function is equivalent to the fwscanf() function with the argument
stdin interposed before the arguments of the wscanf() function.
Return Value
Otherwise, the wscanf() function returns the number of input items assigned. It
can be fewer than provided for, or even zero, in the event of an early matching
failure.
#include <stdio.h>
#include <wchar.h>
int main(void)
{
int i;
float fp;
char c,s[81];
/********************************************************************
The output should be similar to:
Related Information
v “fscanf() — Read Formatted Data” on page 123
v “fwprintf() — Format Data as Wide Characters and Write to a Stream” on page
133
v “fwscanf() — Read Data from Stream Using Wide Character” on page 137
v “scanf() — Read Data” on page 313
v “sscanf() — Read Data” on page 339
v “swprintf() — Format and Write Wide Characters to Buffer” on page 385
v “swscanf() — Read Wide Character Data” on page 387
| v “vfscanf() — Read Formatted Data” on page 406
| v “vfwscanf() — Read Formatted Wide Character Data” on page 409
| v “vscanf() — Read Formatted Data” on page 412
| v “vsscanf() — Read Formatted Data” on page 416
| v “vswscanf() — Read Formatted Wide Character Data” on page 420
| v “vwscanf() — Read Formatted Wide Character Data” on page 423
errno Macros
The following table lists which error macros the ILE C library functions can set.
Table 12. errno Macros
Error Macro Description Set by Function
EBADDATA The message data is not perror, strerror
valid.
EBADF The catalog descriptor is not catclose, catgets, clearerr,
valid. fgetc, fgetpos, fgets, fileno,
freopen, fseek, fsetpos, getc,
rewind
EBADKEYLN The key length specified is _Rreadk, _Rlocate
not valid.
EBADMODE The file mode specified is fopen, freopen, _Ropen
not valid.
EBADNAME Bad file name specified. fopen, freopen, _Ropen
EBADPOS The position specified is not fsetpos
valid.
EBADSEEK Bad offset for a seek fgetpos, fseek
operation.
EBUSY The record or file is in use. perror, strerror
ECONVERT Conversion error. wcstomb, wcswidth
EDOM Domain error in math acos, asin, atan2, cos, exp,
function. fmod, gamma, hypot, j0, j1,
jn, y0, y1, yn, log, log10,
pow, sin, strtol, strtoul, sqrt,
tan
EGETANDPUT An illegal read operation fgetc, fread, getc, getchar
occurred after a write
operation.
EILSEQ The character sequence does fgetwc, fgetws, getwc,
not form a valid multibyte mblen,mbrlen, mbrtowc,
character. mbsrtowcs, mbstowcs,
mbtowc, printf, scanf,
ungetwc, wcrtomb,
wcsrtombs, wcstombs,
wctomb, wcswidth, wcwidth
EINVAL The signal is not valid. printf, scanf, signal, swprintf,
swscanf, wcstol, wcstoll,
wcstoul, wcstoull
The following table shows the initial state of the C signal values and their
handling action definitions with SYSIFCOPT(*ASYNCSIGNAL) is specified on the
compilation command.
Table 16. Default Actions for Signal Values
Value Default Action Meaning
SIGABRT 2 Abnormal termination.
SIGFPE 2 Arithmetic exceptions that are not masked, such
as overflow, division by zero, and incorrect
operation.
SIGILL 2 Detection of an incorrect function image.
SIGINT 2 Interactive attention.
SIGSEGV 2 Incorrect access to storage.
SIGTERM 2 Termination request sent to the program.
SIGUSR1 2 Intended for use by user applications.
SIGUSR2 2 Intended for use by user applications.
SIGALRM 2 A timeout signal that is sent by alarm().
SIGHUP 2 A controlling terminal is hung up, or the
controlling process ended.
SIGKILL 1 A termination signal that cannot be caught or
ignored.
SIGPIPE 3 A write to a pipe that is not being read.
SIGQUIT 2 A quit signal for a terminal.
SIGCHLD 3 An ended or stopped child process. SIGCLD is
an alias name for this signal.
SIGCONT 5 If stopped, continue.
SIGSTOP 4 A stop signal that cannot be caught or ignored.
SIGTSTP 4 A stop signal for a terminal.
SIGTTIN 4 A background process attempted to read from a
controlling terminal.
SIGTTOU 4 A background process attempted to write to a
controlling terminal.
SIGIO 3 Completion of input or output.
Default Actions:
1 End the process immediately
2 End the request.
3 Ignore the signal.
4 Stop the process.
5 Continue the process if it is currently stopped. Otherwise, ignore the
signal.
Some data types in the ILE C programming language have no direct equivalent in
other languages. However, you can simulate data types in other languages that use
ILE C data types.
The following table shows the ILE C data type compatibility with ILE RPG.
Table 21. ILE C Data Type Compatibility with ILE RPG
ILE C declaration ILE RPG D spec, columns 33
in prototype to 39 Length Comments
char[n] nA n An array of characters
char * where n=1 to 32766.
char 1A 1 An Indicator that is a
variable starting with *IN.
char[n] nS 0 n A zoned decimal.
The following table shows the ILE C data type compatibility with ILE COBOL.
Table 22. ILE C Data Type Compatibility with ILE COBOL
ILE C declaration ILE COBOL LINKAGE
in prototype SECTION Length Comments
char[n] PIC X(n). n An array of characters where
char * n=1 to 3,000,000
char PIC 1 INDIC .. 1 An indicator.
char[n] PIC S9(n) DISPLAY n A zoned decimal.
wchar_t[n] PIC G(n) 2n A graphic data type.
_Packed struct 05 VL-FIELD. n+2 A variable length field where i
{short i; char[n]} 10 i PIC S9(4) is the intended length and n is
COMP-4. the maximum length.
10 data PIC X(n).
char[n] PIC X(n). 6 A date field.
char[n] PIC X(n). 5 A day field.
char PIC X. 1 A day-of-week field.
char[n] PIC X(n). 8 A time field.
char[n] PIC X(n). 26 A time stamp field.
short int PIC S9(4) COMP-4. 2 A 2-byte signed integer with a
range of -9999 to +9999.
short int PIC S9(4) BINARY. 2 A 2-byte signed integer with a
range of -9999 to +9999.
The following table shows the ILE C data type compatibility with ILE CL.
The following table shows the ILE C data type compatibility with OPM
RPG/400®®.
Table 24. ILE C Data Type Compatibility with OPM RPG/400
OPM RPG/400 I spec,
ILE C declaration DS subfield columns
in prototype spec Length Comments
char[n] 1 10 n An array of characters where
char * n=1 to 32766.
char *INxxxx 1 An Indicator that is a variable
starting with *IN.
char[n] 1 nd (d>=0) n A zoned decimal. The limit of
n is 30.
char[2n+2] Not supported. 2n+2 A graphic data type.
_Packed struct Not supported. n+2 A variable length field where i
{short i; char[n]} is the intended length and n is
the maximum length.
char[n] Not supported. 6, 8, 10 A date field.
char[n] Not supported. 8 A time field.
char[n] Not supported. 26 A time stamp field.
short int B 1 20 2 A 2-byte signed integer with a
range of -9999 to +9999.
int B 1 40 4 A 4-byte signed integer with a
range of -999999999 to
+999999999.
The following table shows the ILE C data type compatibility with OPM
COBOL/400®®.
Table 25. ILE C Data Type Compatibility with OPM COBOL/400
ILE C declaration OPM COBOL
in prototype LINKAGE SECTION Length Comments
char[n] PIC X(n). n An array of characters where
char * n=1 to 3,000,000
char PIC 1 INDIC .. 1 An indicator.
char[n] PIC S9(n) USAGE IS n A zoned decimal. The limit of
DISPLAY n is 18.
_Packed struct 05 VL-FIELD. n+2 A variable length field where i
{short i; char[n]} 10 i PIC S9(4) is the intended length and n is
COMP-4. the maximum length.
10 data PIC X(n).
char[n] PIC X(n). 6, 8, 10 A date field.
char[n] PIC X(n). 8 A time field.
char[n] PIC X(n). 26 A time stamp field.
short int PIC S9(4) COMP-4. 2 A 2 byte signed integer with a
range of -9999 to +9999.
int PIC S9(9) COMP-4. 4 A 4-byte signed integer with a
range of -999999999 to
+999999999.
long int PIC S9(9) COMP-4. 4 A 4-byte signed integer with a
range of -999999999 to
+999999999.
The following table shows the ILE C data type compatibility with CL.
Table 26. ILE C Data Type Compatibility with CL
ILE C declaration in
prototype CL Length Comments
char[n] *CHAR LEN(&N) n An array of characters where
char * n=1 to 32766. A null terminated
string. For example, CHGVAR
&V1 VALUE (&V *TCAT X’00’)
where &V1 is one byte bigger
than &V. The limit of n is 9999.
char *LGL 1 Holds ’1’ or ’0’.
_Packed struct {short Not supported. n+2 A variable length field where i
i; char[n]} is the intended length and n is
the maximum length.
integer types Not supported. 1, 2, 4 A 1-, 2- or 4- byte signed or
unsigned integer.
float constants CL constants only. 4 A 4- or 8- byte floating point.
decimal(n,p) *DEC n/2+1 A packed decimal. The limit of
n is 15 and p is 9.
union.element Not supported. element An element of a union.
length
struct Not supported. n A structure. Use the _Packed
qualifier on the struct.
The following table shows how arguments are passed from a command line CL
call to an ILE C program.
Table 27. Arguments Passed From a Command Line CL Call to an ILE C Program
Command Line Argument Argv Array ILE C Arguments
argv[0] ″LIB/PGMNAME″
argv[1..255] normal parameters
’123.4’ argv[1] ″123.4″
123.4 argv[2] 0000000123.40000D
’Hi’ argv[3] ″Hi″
Lo argv[4] ″LO″
The following table shows how CL constants are passed from a compiled CL
program to an ILE C program.
Table 28. CL Constants Passed from a Compiled CL Program to an ILE C Program
Compile CL Program
Argument Argv Array ILE C Arguments
argv[0] ″LIB/PGMNAME″
argv[1..255] normal parameters
’123.4’ argv[1] ″123.4″
123.4 argv[2] 0000000123.40000D
’Hi’ argv[3] ″Hi″
Lo argv[4] ″LO″
The following table shows how CL variables are passed from a compiled CL
program to an ILE C program. All arguments are passed by reference from CL to
C.
Table 29. CL Variables Passed from a Compiled CL Program to an ILE C Program
CL Variables ILE C Arguments
DCL VAR(&v) TYPE(*CHAR) LEN(10) 123.4
VALUE(’123.4’)
CL variables and numeric constants are not passed to an ILE C program with
null-ended strings. Character constants and logical literals are passed as null-ended
strings, but are not padded with blanks. Numeric constraints such as packed
decimals are passed as 15,5 (8 bytes).
See the Globalization topic for more information on coding variant characters in
the other IBM CCSIDs.
Modules compiled to use the ASM can be intermixed with modules using the
Original Signal Model (OSM) in the same processes, programs, and service
programs. This is true even when SYSIFCOPT(*ASYNCSIGNAL) is not specified
on the compilation command for programs compiled with the OSM. There are
several differences between the two signal models:
v The OSM is based on exceptions, while the ASM is based on asynchronous
signals.
v Under the OSM, the signal vector and signal mask are scoped to the activation
group. Under ASM, there is one signal vector per process and one signal mask
per thread. Both types of signal vectors and signal masks are maintained during
compilation.
v The same asynchronous signal vector and signal masks are operated on by all
ASM modules in a thread, regardless of the activation group the signal vector
and signal masks belong to. You should save and restore the state of the signal
vector and signal masks to ensure that they are not changed by any ASM
modules. The OSM does not use the asynchronous signal vector and signal
masks.
v Signals raised by OSM programs will be sent as exceptions. Under the OSM, the
exceptions are received and handled by the _C_exception_router function,
which directly invokes the OSM signal handler of the the user.
Asynchronous signals are not mapped to exceptions, and are not handled by
signal handlers registered under the OSM. Under the ASM, the exceptions are
received and handled by the _C_async_exception_router function, which maps
the exception to an asynchronous signal, and uses the SNDSIG MI instruction to
raise an asynchronous signal. An ASM signal handler receives control from the
OS/400 asynchonous signal component.
When an OSM program raises a signal, the generated exception percolates up
the invocation stack until it finds an exception monitor. If the prior invocation is
| Unicode Support
| The Unicode Standard is a standardized character code designed to encode
| international texts for display and storage. It uses a unique 16- or 32–bit value to
| represent each individual character, regardless of platform, language, or program.
| Using Unicode, you can develop a software product that will work with various
| platforms, languages, and countries or regions. Unicode also allows data to be
| transported through many different systems.
| There are two different forms of Unicode support available from the compiler and
| run-time. This section describes the two forms of Unicode support as well as some
| of the features of and considerations for using that support. To obtain additional
| information about Unicode, visit the Unicode Home Page at www.unicode.org.
| When the UTF support is enabled, not only do the wide characters become UTF-32
| Unicode, but the narrow characters become UTF-8 Unicode as well. As an example,
| consider the following HelloWorld program.
| #include <stdio.h>
|
| int main() {
| printf("Hello World\n");
| return 0;
| }
| When this program is compiled with UTF support, the character string is stored
| within the program as UTF-8 characters and not EBCDIC characters. The printf()
| function knows this and is able to parse the UTF-8 characters and generate the
| output as expected. However, if this program called some other user-supplied
| routine that did not know how to handle UTF-8 characters, the other routine might
| yield incorrect results or behavior.
| Standard Files
| When using the UTF support, the default standard input and output files stdin,
| stdout, and stderr have some special processing done for them by the run-time.
| Since a program using UTF support contains data in UTF-8 and the standard files
| interact with the screen and spool files, there is a potential mismatch in data. The
| screen and spool file routines are provided by the operating system and thus
| expect EBCDIC. For stdout and stderr, the run-time will automatically convert
| UTF-8 data to EBCDIC. For stdin, the run-time will automatically convert the
| incoming EBCDIC to UTF-8 data.
| Considerations
| Because the default environment for OS/400 is primarily an EBCDIC environment,
| there are several things that you must be aware of when using UTF support in an
| application.
| If a program or service program has some modules compiled with the UTF
| support and some modules compiled without the UTF support, care must be taken
| to ensure that unexpected mismatches do not occur. The wide characters and wide
| character strings are two bytes in size for a non-UTF module and four bytes in size
| for a UTF module, so sharing wide characters between the modules may not work
| correctly. The narrow (non-wide) characters and character strings are in job CCSID
| for a non-UTF module and in CCSID 1208 for a UTF module, so sharing narrow
| characters between the modules may not work correctly either.
| In this case, the first printf() causes the CCSID 1208 string “Hello World” to be
| copied to the stdout buffer. Before the setlocale() is done, stdout should be
| flushed to copy that string to the screen. The second printf() causes the CCSID 37
| string “Hello World\n” to be copied to the stdout buffer. Because of the trailing
| newline character, the buffer is flushed at that point and the whole buffer is copied
| to the screen. Because the CCSID of the current locale is 37 and the screen can
| handle CCSID 37 without problems, the whole buffer is copied without conversion.
| The CCSID 1208 characters are displayed as unreadable characters. If a flush had
| been done, the CCSID 1208 characters would have been converted to CCSID 37
| and would have been displayed correctly.
| Nearly all of the run-time routines have been modified to support UTF, but there
| are a handful of them that have not. Routines and structures that deal with
| exception handling, such as the _GetExcData() function, the _EXCP_MSGID
| variable, and the exception handler structure _INTRPT_Hndlr_Parms_T are
| provided by the operating system, not the run-time. They are strictly EBCDIC. The
| getenv() and putenv() functions handle only EBCDIC. The QXXCHGDA() and
| QXXRTVDA() functions handle only EBCDIC. The argv and envp parameters are also
| EBCDIC only.
| Some of the record I/O routines (that is, functions beginning with _R) do not
| completely support UTF. The routines that do not support UTF are _Rformat(),
| _Rcommit(), _Racquire(), _Rrelease(), _Rpgmdev(), _Rindara(), and _Rdevatr().
| They are available when compiling with the UTF option, but they accept and
| generate only EBCDIC. In addition, any character data within the structures
| returned by the _R functions will be in EBCDIC rather than UTF.
| Other operating system routines have not been modified to support UTF. For
| example, the IFS routines such as open() still accept job CCSID. Other operating
| system APIs also still accept job CCSID. For UTF applications, the characters and
| character strings provided to these routines will need to be converted to job CCSID
| using QTQCVRT, iconv(), #pragma convert, or some other method.
| With UTF support, the job CCSID cannot be set to UTF-8 because of system
| limitations. When LOCALETYPE(*LOCALEUTF) is specified, the file CCSID
| defaults to the CCSID of the current locale. If the default locale is being used, the
| CCSID defaults to UTF-8 (CCSID 1208). If this default is not desired, the ccsid or
| o_ccsid keyword can be specified in the second parameter of the fopen() call.
| However, database files are an exception, because DB2 UDB for iSeries does not
| completely support UTF-8. When SYSIFCOPT(*NOIFSIO) is specified, and the
| CCSID of the current locale is 1208, the CCSID of the file defaults to CCSID 65535
| Newline Character
| When the UTF support is not used, the hex value generated by the compiler for
| the character \n and used by the run-time has two different values. The hex value
| 0x15 is used if SYSIFCOPT(*NOIFSIO) is specified on the compilation command.
| The hex value 0x25 is used if SYSIFCOPT(*IFSIO) or SYSIFCOPT(*IFS64IO) is
| specified on the compilation command. When the UTF support is used, the
| newline character in UTF-8 will be hex 0x0a regardless of what SYSIFCOPT value
| is used.
| Conversion Errors
| Some run-time routines perform a CCSID conversion from UTF-8 to an EBCDIC
| CCSID when required to interface with an operating system function that does not
| support UTF-8. When a conversion error occurs in these cases, a C2M1217 message
| is generated to the job log with the conversion information.
IBM may have patents or pending patent applications covering subject matter
described in this document. The furnishing of this document does not give you
any license to these patents. You can send license inquiries, in writing, to:
| IBM Director of Licensing
| IBM Corporation
| 500 Columbus Avenue
| Thornwood, NY 10594-1785
| U.S.A.
For license inquiries regarding double-byte (DBCS) information, contact the IBM
Intellectual Property Department in your country or send inquiries, in writing, to:
| IBM World Trade Asia Corporation
| Licensing
| 2-31 Roppongi 3-chome, Minato-ku
| Tokyo 106, Japan
The following paragraph does not apply to the United Kingdom or any other
country where such provisions are inconsistent with local law:
INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS
PUBLICATION “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS
FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or
implied warranties in certain transactions, therefore, this statement may not apply
to you.
Any references in this information to non-IBM Web sites are provided for
convenience only and do not in any manner serve as an endorsement of those Web
sites. The materials at those Web sites are not part of the materials for this IBM
product and use of those Web sites is at your own risk.
Licensees of this program who wish to have information about it for the purpose
of enabling: (i) the exchange of information between independently created
The licensed program described in this information and all licensed material
available for it are provided by IBM under terms of the IBM Customer Agreement,
IBM International Program License Agreement, or any equivalent agreement
between us.
This information contains examples of data and reports used in daily business
operations. To illustrate them as completely as possible, the examples include the
names of individuals, companies, brands, and products. All of these names are
fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.
COPYRIGHT LICENSE:
Each copy or any portion of these sample programs or any derivative work, must
include a copyright notice as follows:
© (your company name) (year). Portions of this code are derived from IBM Corp.
Sample Programs. © Copyright IBM Corp. _enter the year or years_. All rights
reserved.
If you are viewing this information softcopy, the photographs and color
illustrations may not appear.
IBM
Integrated Language Environment
iSeries
Operating System/400
OS/400
RPG/400
Java and all Java-based trademarks and logos are trademarks or registered
trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other
countries.
Other company, product, and service names may be trademarks or service marks
of others.
Index 541
library functions (continued) library functions (continued) library functions (continued)
exponential (continued) miscellaneous stream input/output (continued)
frexp 122 assert 45 fgetpos 91
ldexp 166 getenv 144 fgets 92
log 175 longjmp 178 fgetwc 94
log10 176 perror 209 fgetws 96
pow 210 putenv 223 fprintf 108
file handling rand 239 fputc 109
fileno 98 rand_r 239 fputs 112
remove 257 setjmp 321 fputwc 113
rename 257 srand 338 fputws 115
tmpfile 392 multibyte fread 116
tmpnam 393 _wcsicmp 439 freopen 120
locale _wcsnicmp 446 fscanf 123
localeconv 168 btowc 55 fseek 124
nl_langinfo 206 mblen 182 fsetpos 126
setlocale 322 mbrlen 183 ftell 128
strxfrm 384 mbrtowc 186 fwide 130
math mbsinit 190 fwprintf 133
acos 40 mbsrtowcs 191 fwrite 136
asin 44 mbstowcs 192 fwscanf 137
atan 47 mbtowc 196 getc 142
atan2 47 towctrans 396 getchar 142
bessel 52 wcrtomb 425 gets 146
ceil 63 wcscat 430 getwc 147
cos 66 wcschr 431 getwchar 149
cosh 67 wcscmp 433 printf 211
div 77 wcscoll 434 putc 221
erf 79 wcscpy 435 putchar 221
erfc 79 wcscspn 436 puts 224
floor 99 wcslen 440 putwc 225
fmod 99 wcslocaleconv 441 putwchar 227
frexp 122 wcsncat 442 scanf 313
gamma 140 wcsncmp 443 setbuf 319
hypot 155 wcsncpy 445 setvbuf 328
ldiv 166 wcspbrk 447 sprintf 335
log 175 wcsrchr 450 sscanf 339
log10 176 wcsrtombs 451 swprintf 385
modf 205 wcsspn 453 swscanf 387
sin 332 wcstombs 460 ungetc 399
sinh 333 wcswcs 465 ungetwc 401
sqrt 337 wcswidth 466 vfprintf 404
tan 389 wcsxfrm 467 vfscanf 406
tanh 390 wctob 468 vfwprintf 407
memory management wctomb 469 vfwscanf 409
_C_TS_malloc_debug 71 wctrans 470 vprintf 411
_C_TS_malloc_info 73 wctype 472 vscanf 412
calloc 57 wcwidth 475 vsnprintf 414
free 118 program vsprintf 415
malloc 180 abort 38 vsscanf 416
realloc 247 atexit 48 vswprintf 418
memory operations exit 80 vswscanf 420
memchr 197 signal 330 vwprintf 422
memcmp 198 regular expression vwscanf 423
memcpy 199 regcomp 250 wprintf 481
memmove 202 regerror 252 wscanf 482
memset 203 regexec 253 string manipulation
wmemchr 476 regfree 256 strcat 341
wmemcmp 477 searching strchr 342
wmemcpy 478 bsearch 54 strcmp 343
wmemmove 479 qsort 228 strcoll 346
wmemset 480 stream input/output strcpy 347
message catalog fclose 82 strcspn 348
catclose 59 feof 86 strlen 358
catgets 60 ferror 87 strncmp 362
catopen 61 fflush 87 strncpy 364
fgetc 89 strpbrk 367
Index 543
multibyte functions (continued) pseudorandom number functions record input/ouput (continued)
towctrans 396 (continued) _Rcommit 243
wcrtomb 425 srand 338 _Rdelete 244
wcscat 430 ptrdiff_t 13 _Rdevatr 246
wcschr 431 pushing characters 399 _Rfeod 260
wcscmp 433 putc() function 221 _Rfeov 261
wcscoll 434 putchar() function 221 _Rformat 262
wcscpn 436 putenv() function 223 _Rindara 264
wcscpy 435 puts() function 224 _Riofbk 266
wcscspn 436 putwc() function 225 _Rlocate 268
wcsicmp 439 putwchar() function 227 _Ropen 271
wcslen 440 _Ropnfbk 275
wcslocaleconv 441 _Rpgmdev 276
wcsncat 442
wcsncmp 443
Q _Rreadd 277
_Rreadf 279
qsort() function 228
wcsncpy 445 _Rreadindv 281
quick sort 228
wcsnicmp 446 _Rreadk 284
QXXCHGDA() function 230
wcspbrk 447 _Rreadl 288
QXXDTOP() function 231
wcsrchr 450 _Rreadn 289
QXXDTOZ() function 232
wcsrtombs 451 _Rreadnc 292
QXXITOP() function 233
wcsspn 453 _Rreadp 293
QXXITOZ() function 233
wcstombs 460 _Rreads 296
QXXPTOD() function 234
wcswcs 465 _Rrelease 297
QXXPTOI() function 235
wcswidth 466 _Rrlslck 299
QXXRTVDA() function 236
wcsxfrm 467 _Rrollbck 300
QXXZTOD() function 237
wctob 468 _Rupdate 302
QXXZTOI() function 238
wctomb 469 _Rupfb 304
wctrans 470 _Rwrite 305
wctype 472 _Rwrited 307
wcwidth 475 R _Rwriterd 310
raise() function 238 _Rwrread 311
RAND_MAX 15 record program ending 48
N rand_r() function 239
rand() function 239
redirection 120
regcomp() function 250
NDEBUG 3, 45
random access 124, 128 regerror() function 252
nl_langinfo() function 206
random number generator 239, 338 regex.h include file 12
nltypes.h include file 8
read operations regexec() function 253
nonlocal goto 178, 321
character from stdin 142 regfree() function 256
NULL pointer 14, 15
character from stream 142 remove() function 257
data items from stream 116 rename() function 257
formatted 123, 313, 339 reopening streams 120
O line from stdin 146 reserving storage
offsetof macro 14 line from stream 92 _C_TS_malloc_debug 71
opening reading a character 89 _C_TS_malloc_info 73
message catalog 61 scanning 123 malloc 180
reading realloc 247
character 142 retrieve data area 236
P data 313
data from stream using wide
retrieve locale information 206
rewind() function 259
passing
character 137
constants 502
data using wide-character format
variables 502
perror() function 209
string 482
formatted data 123
S
pointer.h include file 8 scanf() function 313
items 116
pow() function 210 searching
line 146
printf() function 211 bsearch function 54
messages 60
printing environment variables 144
stream 92
error messages 209 strings 342, 367, 374
wide character from stream 94, 147
process control strings for tokens 378, 379
wide-character string from stream 96
signal 330 searching and sorting functions 22
realloc() function 247
program termination seed 338
reallocation 247
abort 38 send signal 238
recfm 103
atexit 48 separate floating-point value 122
recio.h include file 8
exit 80 setbuf() function 319
record format 103
pseudo-random integers 239 setjmp.h include file 13
record input/ouput
pseudorandom number functions setjmp() function 321
_Racquire 240
rand 239 setlocale() function 322
_Rclose 241
rand_r 239
Index 545
testing (continued) trigonometric functions (continued) wcsptime() function 448
isalpha 156 asin 44 wcsrchr() function 450
iscntrl 156 atan 47 wcsrtombs() function 451
isdigit 156 atan2 47 wcsspn() function 453
isgraph 156 cos 66 wcsstr() function 455
islower 156 cosh 67 wcstod() function 455
isprint 156 sin 332 wcstok() function 457
ispunct 156 sinh 333 wcstol() function 458
isspace 156 tan 389 wcstoll() subroutine
isupper 156 tanh 390 wide character to long long
isxdigit 156 type conversion integer 458
state object for initial state 190 atof 49 wcstombs() function 460
wide alphabetic character 160 atoi 50 wcstoul() function 463
wide alphanumeric character 160 atol 51 wcstoull() subroutine
wide control character 160 strtod 376 wide-character string to unsigned long
wide decimal-digit character 160 strtol 380 long 463
wide hexadecimal digit 160 strtoul 382 wcstr.h include file 17
wide lowercase character 160 toascii 394 wcswcs() function 465
wide non-alphanumeric wcstod 455 wcswidth() function 466
character 160 wcstol 458 wcsxfrm() function 467
wide non-space character 160 wcstoul 463 wctob() function 468
wide printing character 160 wctomb() function 469
wide uppercase character 160 wctrans() function 470
wide whitespace character 160
testing state object for initial state 190
U wctype.h include file 17
wctype() function 472
ungetc() function 399
time wcwidth() function 475
ungetwc() function 401
asctime 41 wide character string functions 36
updating files 83
asctime_r 43 wmemchr() function 476
converting from structure to wmemcmp() function 477
string 41 wmemcpy() function 478
converting from structure to string V wmemmove() function 479
(restartable version) 43 va_arg() function 402 wmemset() function 480
correcting for local time 173, 174 va_end() function 402 wprintf() function 481
ctime 68 va_start() function 402 write operations
ctime_r 69 variable argument functions 32 character to stdout 109, 221
difftime 76 verify condition 45 character to stream 109, 221, 399
function 173, 174 vfprintf() function 404 data items from stream 136
functions 24 vfscanf() function 406 formatted 108, 211, 335
gmtime 151 vfwprintf() function 407 line to stream 224
gmtime_r 153 vfwscanf() function 409 printing 136
localtime 173 vprintf() function 411 string to stream 112
localtime_r 174 vscanf() function 412 writing
mktime 204 vsnprintf() function 414 character 109, 221
strftime 354 vsprintf() function 415 data items from stream 136
time 391 vsscanf() function 416 formatted data to a stream 108
time.h include file 16 vswprintf() function 418 string 112, 224
time() function 391 vswscanf() function 420 wide character 113, 225, 227
tm structure 151, 153 vwprintf() function 422 wide characters to a stream 133
TMP_MAX 393 vwscanf() function 423 wide-character string 115
tmpfile() function wscanf() function 482
names 14
number of 14 W
tmpnam() function
file names 14
wchar.h include file 17 X
wcrtomb() function 425 xxcvt.h include file 18
tmpnam() 393
wcscat() function 430 xxdtaa.h include file 18
toascii() function 394
wcschr() function 431 xxenv.h include file 18
tokens
wcscmp() function 433 xxfdbk.h include file 18
strtok 378
wcscoll() function 434
strtok_r 379
wcscpy() function 435
tokenize string 378
wcscspn() function 436
tolower() function 395
wcsftime() function 437
toupper() function 395
wcslen() function 440
towctrans() function 396
wcslocaleconv() function 441
towlower() function 397
wcsncat() function 442
towupper() function 397
wcsncmp() function 443
trigonometric functions
wcsncpy() function 445
acos 40
wcspbrk() function 447
Overall, how satisfied are you with the information in this book?
How satisfied are you that the information in this book is:
When you send comments to IBM, you grant IBM a nonexclusive right to use or distribute your comments in any
way it believes appropriate without incurring any obligation to you.
Name Address
Company or Organization
Phone No.
___________________________________________________________________________________________________
Readers’ Comments — We’d Like to Hear from You Cut or Fold
SC41-5607-02 Along Line
_ _ _ _ _ _ _Fold
_ _ _and
_ _ _Tape
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _Please
_ _ _ _ _do
_ _not
_ _ staple
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _Fold
_ _ _and
_ _ Tape
______
NO POSTAGE
NECESSARY
IF MAILED IN THE
UNITED STATES
IBM CORPORATION
ATTN DEPT 542 IDCLERK
3605 HWY 52 N
ROCHESTER MN 55901-7829
_________________________________________________________________________________________
Fold and Tape Please do not staple Fold and Tape
Cut or Fold
SC41-5607-02 Along Line
Printed in USA
SC41-5607-02