Functions
Intrinsic Functions
GnuCOBOL supports a wide variety of “intrinsic functions” that may be used anywhere in the PROCEDURE DIVISION where a literal is allowed. For example:
MOVE FUNCTION LENGTH(Employee-Last-Name) TO Employee-LN-Len
Note how the word FUNCTION is part of the syntax when you use an intrinsic function. You can use intrinsic functions without having to include the reserved word FUNCTION via settings in the REPOSITORY (see REPOSITORY) paragraph. You may accomplish the same thing by specifying the -fintrinsics switch to the GnuCOBOL compiler when you compile your programs.
User-written functions (see Subprogram Types) never require the FUNCTION keyword when they are executed, because each user-written function a program uses must be included in that program’s REPOSITORY paragraph, which therefore makes the FUNCTION keyword optional.
The following intrinsic functions, known to other “dialects” of COBOL, are defined to GnuCOBOL as reserved words but are not otherwise implemented currently. Any attempts to use these functions will result in a compile-time error message. However they are described at the end of this chapter.
BOOLEAN-OF-INTEGER
CHAR-NATIONAL
DISPLAY-OF
EXCEPTION-FILE-N
EXCEPTION-LOCATION-N
INTEGER-OF-BOOLEAN
NATIONAL-OF
STANDARD-COMPARE
Date and Time Formats
~~~~~~~~~~~~~~~~~~~~~
For functions FORMATTED-CURRENT-DATE, FORMATTED-DATE, FORMATTED-TIME and FORMATTED-DATETIME, the format literal argument indicates the format of the date or time value that is the result of the function. The result of the function will have the same type as its format literal, which can be alphanumeric, national or UTF-8.
For functions INTEGER-OF-FORMATTED-DATE, SECONDS-FROM-FORMATTED-TIME and TEST-FORMATTED-DATETIME, the format literal indicates the format of the date or time value specified as the second argument of the function.
The permissible format strings are listed as follows. For a full description of each subfield in the format literals, including a range of permissible values in data associated with the formats, see the Value meanings and limits section.
Integer Date Form:
~~~~~~~~~~~~~~~~~
A value in integer date form is a positive integer that represents the number of days since 31 December, 1600 in the Gregorian calendar.
It must be greater than zero and less than or equal to the value of FUNCTION INTEGER-OF-DATE (99991231), which is 3,067,671.
Standard Date Form:
~~~~~~~~~~~~~~~~~~
A value in standard date form is an integer of the form YYYYMMDD, calculated using (YYYY * 10,000) + (MM * 100) + DD, where:
YYYY represents the year in the Gregorian calendar. It must be an integer in the range [1601, 9999].
MM represents a month and must be an integer in the range [01, 12].
DD represents a day and must be an integer in the range [01, 31], valid for the specified month and year combination.
Julian Date Form:
~~~~~~~~~~~~~~~~
A value in Julian date form is an integer of the form YYYYDDD, calculated using (YYYY * 1000) + DDD, where:
YYYY represents the year in the Gregorian calendar. It must be an integer in the range [1601, 9999].
DDD represents the day of the year. It must be a positive integer in the range [1, 366], valid for the year specified.
UTC Offset Value:
~~~~~~~~~~~~~~~~
A UTC offset value is an integer representation of offset from UTC (Coordinated Universal Time) expressed in minutes. The value must be greater than or equal to -1439 and less than or equal to 1439.
Note: The offset value 1439 represents 23 hours 59 minutes, which is one minute less than a day.
Standard numeric time form
~~~~~~~~~~~~~~~~~~~~~~~~~~
A value in standard numeric time form is a numeric value representing seconds past midnight. The value must be greater than or equal to zero and less than 86,400
Date and Time Formats:
~~~~~~~~~~~~~~~~~~~~~
For functions FORMATTED-CURRENT-DATE, FORMATTED-DATE, FORMATTED-TIME and FORMATTED-DATETIME, the format literal argument indicates the format of the date or time value that is the result of the function. The result of the function will have the same type as its format literal, which can be alphanumeric, national or UTF-8.
For functions INTEGER-OF-FORMATTED-DATE, SECONDS-FROM-FORMATTED-TIME and TEST-FORMATTED-DATETIME, the format literal indicates the format of the date or time value specified as the second argument of the function.
The permissible format strings are listed as follows. For a full description of each subfield in the format literals, including a range of permissible values in data associated with the formats, see Value meanings and limits.
Field Sizes
~~~~~~~~~~~
Caution must be applied when using the above processes in that the data size used for days, MUST be in excess of any requirements in the future but in particular for the years 2038 onwards so that dates expressed as days from 1601 are not exceeded by the field format, i.e., 32 bit fields or larger must be used. e.g., 2038 - 1600 = 438 years, x 365.25 = 159,980 days, requires 4 bytes minimum as only 2 bytes provide for 64k only - far too small. Always assume that any application will be in use far beyond your expectations as proven by the year 2000 millennium bug that caused a lot of issues in 1999. Not that I can complain as I made a lot of money fixing such issues for various sites :)
Date formats Format literals
~~~~~~~~~~~~ ~~~~~~~~~~~~~~~
Basic calendar date YYYYMMDD
Extended calendar date YYYY-MM-DD
Basic ordinal date YYYYDDD
Extended ordinal date YYYY-DDD
Basic week date YYYYWwwD
Extended week date YYYY-Www-D
Integer-seconds time formats:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Integer-seconds time formats Format literals
Basic local time hhmmss
Extended local time hh:mm:ss
Basic Coordinated Universal Time (UTC) hhmmssZ
Extended UTC time hh:mm:ssZ
Basic offset time hhmmss+hhmm
Extended offset time hh:mm:ss+hh:mm
Fractional-seconds time formats:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Fractional-seconds time formats Format literals
Basic local time hhmmss.ssss
Extended local time hh:mm:ss.ssss
Basic Coordinated Universal Time (UTC) hhmmss.ssssZ
Extended UTC time hh:mm:ss.ssssZ
Basic offset time hhmmss.ssss+hhmm
Extended offset time hh:mm:ss.ssss+hh:mm
Note: The period is used as the decimal separator, and four "s" characters after the period are used for illustrative purposes. The number of "s" characters that might be specified after the decimal separator in these formats might range from 1 to 9.
Value Meanings and Limits:
~~~~~~~~~~~~~~~~~~~~~~~~~
The permissible date and time formats have the following meanings and limits:
Format Meaning and limits
YYYY Year, 1601-9999
MM Month, 01-12
DD Day of month, 01-{28|29|30|31} dependent on month sub-field
DDD Day of year for ordinal date formats, 001-365|366
ww Week of year, 01-53
D Day of week, 1-7
W
-
hh Hours, 00-23
mm Minutes, 00-59
ss Seconds, 00-59
.s Fractional seconds, always prefixed with '.' then 1-9 's'
+|-hh:mm UTC offset hours (extended times only), the offset can be adjusted
upward (by a '+' prefix) or downward (by a - prefix). A prefix of 0
(zero) indicates that an offset of UTC is not available on the system.
Z UTC time indicator
Value Meanings and Limits:
~~~~~~~~~~~~~~~~~~~~~~~~~
The permissible date and time formats have the following meanings and limits:
Format Meaning and Limits:
~~~~~~~~~~~~~~~~~~~~~~~~~~
YYYY Year, 1601-9999
MM Month, 01-12
DD Day of month, 01-{28|29|30|31} dependent on month sub-field
DDD Day of year for ordinal date formats, 001-365|366
ww Week of year, 01-53
D Day of week, 1-7
W
-
hh Hours, 00-23
mm Minutes, 00-59
ss Seconds, 00-59
.s Fractional seconds, always prefixed with '.' then 1-9 's'
+|-hh:mm UTC offset hours (extended times only), the offset can be adjusted
upward (by a '+' prefix) or downward (by a - prefix).
A prefix of 0 (zero) indicates that an offset of UTC is not available
on the system.
Z UTC time indicator
The GnuCOBOL intrinsic functions can be grouped into following categories:
+-------------------------------------------------------------------------------------+
| MATHEMATICAL FUNCTIONS |
+-------------------------------------------------------------------------------------+
| ABS(argument-1) | Returns the absolute value of argument-1 |
| ABSOLUTE-VALUE(argument-1) | Same as ABS(argument-1) |
| E | Returns the constant E |
| EXP(argument-1) | Returns e raised to the power of argument-1 |
| EXP10(argument-1) | Returns 10 raised to the power of argument-1 |
| FACTORIAL(argument-1) | Returns the factorial value of argument-1 |
| FRACTION-PART(number) | Returns number from the right of decimal point |
| INTEGER-PART(number) | Returns the integer portion of number |
| LOG(number) | Returns the natural logarithm (base e) of number |
| LOG10(number) | Returns the base 10 logarithm of number |
| MOD(value,modulus) | Returns the value of remainder from value / modulus |
| PI | Returns the constant PI |
| REM(number,divisor) | Returns the remainder of number divided by divisor |
| SIGN(number) | Returns -1 if number <0, 0 if number =0, 1 if number >0|
| SQRT(argument-1) | Returns the square root of argument-1 |
| SUM(number-1[,number-2]...)| Returns the sum of number-n arguments |
| SIN(argument-1) | Returns the sine of argument-1 (in radians) |
| COS(argument-1) | Returns the cosine of argument-1 (in radians) |
| TAN(argument-1) | Returns the tangent of argument-1 (in radians) |
| ASIN(argument-1) | Returns the arcsine (in radians) of argument-1 |
| ACOS(argument-1) | Returns the arccosine (in radians) of argument-1 |
| ATAN(argument-1) | Returns the arctangent (in radians) of argument-1 |
+-------------------------------------------------------------------------------------+
| STATISTICAL FUNCTIONS |
+-------------------------------------------------------------------------------------+
| MAX(num-1[,num-2]...) | Returns the maximum value from the list of numbers |
| MEAN(num-1[,num-2]...) | Returns the mean value of the list of numbers |
| MEDIAN(num-1[,num-2]...) | Returns the median value of the list of numbers |
| MIDRANGE(num-1[,num-2]...) | Returns the mean of minimum and maximum from list |
| MIN(num-1[,num-2]...) | Returns the minimum from the list of numbers |
| RANDOM[(seed)] | Returns a pseudo-random value in range 0 >= to < 1 |
| RANGE(num-1[,num-2 ]...) | Returns maximum number in the list minus the minimum |
| STANDARD-DEVIATION(num-1[,num-2]...) |
| | Returns the standard deviation of the list |
| VARIANCE(num-1[,num-2]...) | Returns the variance of the list of numbers |
+-------------------------------------------------------------------------------------+
| DATE / TIME FUNCTIONS |
+-------------------------------------------------------------------------------------+
| COMBINED-DATETIME(days,seconds) Returns 7 dig.as value of days, 5 digits as seconds |
| CURRENT-DATE | Returns the current date and time |
| INTEGER-OF-DATE(date) | Convert from YYYYMMDD to the num.of days since 16001231|
| DATE-OF-INTEGER(argument-1)| Returns a numeric calendar date in YYYYMMDD format |
| INTEGER-OF-DAY(date) | Convert from YYYYDDD to the num.of days since 16001231|
| DAY-OF-INTEGER(argument-1) | Returns a calendar date in YYYYDDD format |
| DATE-TO-YYYYMMDD(...) | Convert 6-digit date yymmdd to an 8-digit date yyymmdd |
| DAY-TO-YYYYDDD(...) | Convert 5-digit date yyddd to a 7-digit date yyyyddd |
| FORMATTED-CURRENT-DATE(arg-1)Returns current date/time from the system at runtime |
| FORMATTED-DATE(arg-1,arg-2)| Convert an integer date form to a date in the req.fmt |
| FORMATTED-DATETIME(arg-n..)| Uses a timedate form to convert in integer and num.time|
| FORMATTED-TIME (arg-n,...) | Converts seconds past midnight with optional offset |
| INTEGER-OF-FORMATTED-DATE(args..)Converts a date to integer date form |
| SECONDS-FROM-FORMATTED-TIME( Format,time) decodes the string,ret.the number of secs |
| SECONDS-PAST-MIDNIGHT | Returns curr.time of day as num.seconds since midnight |
| TEST-DATE-YYYYMMDD(date) | Determines if supplied date argument is a valid date |
| TEST-DAY-YYYYDDD(date) | Determines if the supplied date is a valid date |
| TEST-FORMATTED-DATETIME(arg-1,arg-2) Tests if literal is valid according to spec.fmt|
| YEAR-TO-YYYY(yy ...) | Converts yy to a four-digit format yyyy |
+-------------------------------------------------------------------------------------+
+-------------------------------------------------------------------------------------+
| FINANCIAL FUNCTIONS |
+-------------------------------------------------------------------------------------+
| ANNUITY(interest-rate, number-of-periods) |
| returns the ratio of an annuity paid at interest-rate for each of number-of-periods |
| PRESENT-VALUE(rate,value-1[,value-2]...) |
| returns pres.value of series of future periodend amounts at disc.rate by rate argumt|
+-------------------------------------------------------------------------------------+
| STRING AND CHARACTER HANDLING FUNCTIONS |
+-------------------------------------------------------------------------------------+
| BIT-OF(arg-1) | Returns string of 1&0 repres.bin.value of bytes in arg-1 |
| BIT-TO-CHAR(arg-1) | Returns a string that represents a bit pattern of arg-1 |
| BYTE-LENGTH(string) | Same as LENGTH-AN |
| CHAR(arg-1) | Returns char.in the ordinal position specified by arg-1 |
| CONCAT(arg-1,arg-2 ...) | Concatenates arg-1,arg-2, .. into a single string result |
| CONCATENATE | Same as CONCAT |
| CONTENT-LENGTH(arg-1) | Scans for a NUL byte delimiter and returns the length |
| CONTENT-OF(ptr{length}) | Returns a char.field of data addressed by pointer |
| HEX-OF(arg-1) | Returns a string of hexadecimal representation of arg-1 |
| HEX-TO-CHAR(arg-1) | Returns a string of characters representation from arg-1 |
| HIGHEST-ALGEBRAIC(num-id) Returns highest value could possibly be stored in num-id |
| INTEGER(number) | Returns the greatest integer value < or = equal to number |
| LOWER-CASE(string) | Returns the value of string converted to lower case |
| LOWEST-ALGEBRAIC(num-id)| Returns the lowest value could possibly stored in num-id |
| LENGTH(string) | Returns the length in characters of string |
| LENGTH-AN(string) | Returns the length in bytes of storage of string |
| ORD(char) | Returns the ordinal position corr.to the 1st char.of char |
| ORD-MAX(char-n...) | Returns ordinal pos.corr.to the char-n whose 1st character|
| | Has highest position in the program collating sequence |
| ORD-MIN(char-n...) | Returns ordinal pos.corr.to the char-n whose 1st character|
| | Has lowest position in the program collating sequence |
| REVERSE(string) | Returns the byte-by-byte reversed value of string |
| SUBSTITUTE(string,...) | Replace all occurrences with the corresponding to strings |
| SUBSTITUTE-CASE | Same as SUBSTITUTE but without regard to case |
| STORED-CHAR-LENGTH(strg)| Returns num.bytes of string minus num.of trailing spaces |
| TRIM(string[...]) | Removes LEADING or TRAILING spaces from string |
| UPPER-CASE(string) | Returns the value of string converted to upper case |
+-------------------------------------------------------------------------------------+
| GENERAL FUNCTIONS |
+-------------------------------------------------------------------------------------+
| CURRENCY-SYMBOL | Returns the currency symbol currently in effect |
| MONETARY-DECIMAL-POINT | Returns char.separate integer from frac.part of curr.value|
| MONETARY-THOUSANDS-SEPARATOR Returns char.separate thousands of monetary curr.values|
| NUMERIC-DECIMAL-POINT | Returns character separate integer from fractional part |
| NUMERIC-THOUSANDS-SEPARATOR Returns char.separate thousands of numeric values |
| NUMVAL(string) | Converts a string to its corresponding numeric value |
| NUMVAL-C(string... | Converts a string representing a currency to its num.value|
| NUMVAL-C-2(...) | Returns the num.value represented by the character string |
| NUMVAL-F(char) | Converts a string repr.a floating-point value to num.value|
| TEST-NUMVAL(string) | Evaluates string for being appropriate for NUMVAL function|
| TEST-NUMVAL-C(string...)| Evaluates string for being appropriate for NUMVAL-C funct.|
| TEST-NUMVAL-F (string) | Evaluates string for being appropriate for NUMVAL-F funct.|
+-------------------------------------------------------------------------------------+
| FROM ROUTINE "CBL_ERROR_PROC" |
+-------------------------------------------------------------------------------------+
|EXCEPTION-FILE | Returns exc.information from most recently executed I/O statemt |
|EXCEPTION-LOCATION | Returns exc.information from most recently failing statement |
|EXCEPTION-STATEMENT| Returns most recent COBOL statement that generated exc.condition|
|EXCEPTION-STATUS | Returns error type from most recent COBOL statement gen.exc.cond|
+-------------------------------------------------------------------------------------+
+-------------------------------------------------------------------------------------+
| LOCALE FUNCTIONS |
+-------------------------------------------------------------------------------------+
|LOCALE-COMPARE(...)| Returns a character indicating result of comparing |
|LOCALE-DATE(...) | Converts date from yyyymmdd format to the current locale format |
|LOCALE-TIME(...) | Converts hhmm or hmmss time to a current locale format |
|LOCALE-TIME-FROM-SECONDS(...) Converts num.of seconds since midnight to a locale fmt |
+-------------------------------------------------------------------------------------+
| MODULE FUNCTIONS |
+-------------------------------------------------------------------------------------+
|MODULE-CALLER-ID | Returns the entry-point name of program that called subprogram |
|MODULE-DATE | Returns date the program was compiled, in the form yyyymmdd |
|MODULE-FORMATTED-DATE Returns date & time when the program was compiled |
|MODULE-ID | Returns the name (in PROGRAM-ID) of the program |
|MODULE-PATH | Returns the path to the executable version of the program |
|MODULE-SOURCE | Returns the filename of the source code of the program |
|MODULE-TIME | Returns the time the program was compiled in the form hhmmss |
|WHEN-COMPILED | Returns the date and time the program was compiled |
+-------------------------------------------------------------------------------------+
The supported intrinsic functions are listed in the following sections, along with their syntax and usage notes.
ABS
ABS Function Syntax
=======================================================================
ABS | ABSOLUTE-VALUE (argument-1)
~~~ ~~~~~~~~~~~~~~
=======================================================================
This function determines and returns the absolute value of <argument-1> (a numeric literal or a numeric data item). Note that ABSOLUTE-VALUE has an alias for this function.
ACOS
ACOS Function Syntax
=======================================================================
ACOS(argument-1)
~~~~
=======================================================================
The ACOS function determines and returns a numeric value of an angle in radians that approximates the trigonometric arc-cosine, or inverse cosine, of <argument-1> (a numeric literal, a numeric data item or an arithmetic expression with value from -1 to +1).
The returned value is an angle, expressed in radians, greater than or equal to zero and less than or equal to PI (from 0 to 180 degrees). You can convert radians to degrees as follows:
COMPUTE degrees = ( radians / FUNCTION PI ) * 180
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTACOS. *> SAMPLE PROGRAM
DATA DIVISION. WORKING-STORAGE SECTION.
01 wDegrees PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
display 'a.ACOS 0: ' FUNCTION ACOS(0)
compute wDegrees = (FUNCTION ACOS(0) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'b.ACOS +1: ' FUNCTION ACOS(+1)
compute wDegrees = (FUNCTION ACOS(+1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'c.ACOS -1: ' FUNCTION ACOS(-1)
compute wDegrees = (FUNCTION ACOS(-1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
ACCEPT OMITTED STOP RUN.
Output:
a.ACOS 0: 1.57079632679489661923132169163975144209858469968755291048747229
615390820314310449931401741267106
Degrees : +090.000000000000000000000000000000
b.ACOS +1: 000000000
Degrees : +000.000000000000000000000000000000
c.ACOS -1: 3.141592653589793238462643383279502884197169399375105820974944592
30781640628620899862803482534212
Degrees : +180.000000000000000000000000000000
ANNUITY
ANNUITY Function Syntax
=======================================================================
ANNUITY(interest-rate, number-of-periods)
~~~~~~~
=======================================================================
This function returns a numeric value approximating the ratio of an annuity paid at <interest-rate> (numeric data item or literal) for each of <number-of-periods> (numeric data items or literals).
<interest-rate> is the rate of interest paid at each payment. If you only have an annual interest rate and you wish to compute monthly annuity payments, divide the annual interest rate by 12 and use that value for <interest-rate>.
Multiply the result of this function times the desired principal amount to determine the amount of each period’s payment.
A note for the financially challenged: an annuity is basically a reverse loan; an accountant would take the result of this function multiplied by -1 times the principal amount to compute a loan payment you are making.
Here is an example of a program using this function. Given a total amount of 100,000 USD and an annual interest of 5% the program calculates the monthly payment for the duration of one year, two years ... up to 10 years.
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. PANNUITY. *> Given a total amount of 100,000 and an annual interest of 5% *> the program calculates monthly payment for a duration of 1 year, 2 years *> ...up to 10 years. DATA DIVISION. WORKING-STORAGE SECTION. 01 Total-Loan Pic 9(9)V99 value 100000. 01 Interest-Rate Pic 999V99 value 0.05. 01 Interest-RateP Pic 999V99 value zero. 01 Months Pic 999 value zero. 01 Years Pic 999 value zero. 01 Monthly-Payment Pic 9(9)V99. 01 Total-Payments Pic 9(9)V99. PROCEDURE DIVISION. DISPLAY SPACE COMPUTE Interest-RateP = Interest-Rate * 100 DISPLAY 'Total Loan: ' Total-Loan ' USD - Interest Rate: ' Interest-RateP '%' DISPLAY SPACE DISPLAY ' Y M Monthly Amount Total Payments' DISPLAY '--- --- ------------- --------------' PERFORM 10 TIMES ADD 12 to Months COMPUTE Monthly-Payment = Total-Loan * FUNCTION ANNUITY ((Interest-Rate / 12), Months) COMPUTE Total-Payments = Monthly-payment * Months COMPUTE Years = Months / 12 DISPLAY Years ' ' Months ' ' Monthly-Payment ' USD ' Total-Payments END-PERFORM ACCEPT omitted GOBACK.Other additional documentation:
When the value of Interest-Rate is zero, the value returned by the function is the approximation of:
(1 / Number-Periods).When the value of Interest-Rate is not zero, the value of the function is the approximation of:
(Interest-Rate / (1 - (1 + Interest-Rate) ** (- (Number-Periods) ))).
ASIN
ASIN Function Syntax
=======================================================================
ASIN(argument-1)
~~~~
=======================================================================
The ASIN function determines and returns a numeric value of an angle in radians that approximates the trigonometric arc-sine, or inverse sine, of <argument-1> (a numeric literal, a numeric data item or an arithmetic expression with value from -1 to +1).
The returned value is an angle, expressed in radians, greater than or equal to -PI/2 and less than or equal to +PI/2 (from -90 to +90 degrees).
You can convert radians to degrees as follows:
COMPUTE degrees = ( radians / FUNCTION PI ) * 180
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTASIN. *> SAMPLE PROGRAM
DATA DIVISION. WORKING-STORAGE SECTION.
01 wDegrees PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
display 'a.ASIN 0: ' FUNCTION ASIN(0)
compute wDegrees = (FUNCTION ASIN(0) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'b.ASIN +1: ' FUNCTION ASIN(+1)
compute wDegrees = (FUNCTION ASIN(+1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'c.ASIN -1: ' FUNCTION ASIN(-1)
compute wDegrees = (FUNCTION ASIN(-1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
ACCEPT OMITTED STOP RUN.
Output:
a.ASIN 0: 000000000
Degrees : +000.000000000000000000000000000000
b.ASIN +1: 1.57079632679489661923132169163975144209858469968755291048747229
615390820314310449931401741267106
Degrees : +090.000000000000000000000000000000
c.ASIN -1: -1.57079632679489661923132169163975144209858469968755291048747229
615390820314310449931401741267106
Degrees : -090.000000000000000000000000000000
ATAN
ATAN Function Syntax
=======================================================================
ATAN(argument-1)
~~~~
=======================================================================
The ATAN function determines and returns a numeric value of an angle in radians that approximates the trigonometric arc-tangent, or inverse tangent, of <argument-1> (a numeric literal, a numeric data item or an arithmetic expression with value from -infinity to +infinity).
The returned value is an angle, expressed in radians, greater than (but not equal to) -PI/2 and less than (but not equal to) +PI/2 (from -90 to +90 degrees).
You can convert radians to degrees as follows:
COMPUTE degrees = ( radians / FUNCTION PI ) * 180
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTATAN. *> SAMPLE PROGRAM
DATA DIVISION. WORKING-STORAGE SECTION.
01 wDegrees PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
display 'a.ATAN 0: ' FUNCTION ATAN(0)
compute wDegrees = (FUNCTION ATAN(0) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'b.ATAN +1: ' FUNCTION ATAN(+1)
compute wDegrees = (FUNCTION ATAN(+1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
display 'c.ATAN -1: ' FUNCTION ATAN(-1)
compute wDegrees = (FUNCTION ATAN(-1) / FUNCTION PI) * 180
display ' Degrees : ' wDegrees
ACCEPT OMITTED STOP RUN.
Output:
a.ATAN 0: 000000000
Degrees : +000.000000000000000000000000000000
b.ATAN +1: 0.785398163397448309615660845819875721049292349843776455243736148
076954101571552249657008706335529
Degrees : +044.999999999999999999999999999999
c.ATAN -1: -0.785398163397448309615660845819875721049292349843776455243736148
076954101571552249657008706335529
Degrees : -044.999999999999999999999999999999
BIT-OF
BIT-OF Function Syntax
=======================================================================
BIT-OF (argument-1)
~~~~~~
=======================================================================
BIT-OF function returns an alphanumeric character string of ‘1’ and ‘0’ characters, which represents the binary value of each byte in the argument used on input.
The function type is alphanumeric.
<argument-1> must be a data item, literal, or an intrinsic function result of any data class.
Returned values:
An alphanumeric character string consisting of the binary representation of each byte in <argument-1>.
The length of the character string returned, in bytes, is eight times the length of <argument-1>, in bytes.
>>SOURCE FREE
*> Example of use of function BIT-OF
identification division.
program-id. pgmbitof.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 AAA PIC XXX VALUE "1 2".
01 BBB PIC XXX VALUE "A B".
procedure division.
display BIT-OF(1) at 0110
display BIT-OF(2) at 0210
display BIT-OF(3) at 0310
display BIT-OF(0123) at 0410
display BIT-OF(AAA) at 0510
display BIT-OF(BBB) at 0610
accept omitted
stop run.
Produces :
00110001
00110010
00110011
00110000001100010011001000110011
001100010010000000110010
010000010010000001000010
BIT-TO-CHAR
BIT-TO-CHAR Function Syntax
=======================================================================
BIT-TO-CHAR {argument-1)
~~~~~~~~~~~
=======================================================================
BIT-TO-CHAR function returns a character string that represents a bit pattern supplied on input.
The function type is alphanumeric.
<argument-1> must be an alphanumeric literal, alphanumeric data item, or alphanumeric group item.
<argument-1> must consist only of the characters "0" and "1".
The length of <argument-1> must be a multiple of 8 bytes.
Returned values:
A character string consisting of bytes representing the sequence of "0" and "1" characters in <argument-1>.
The length of the result string is equal to the length of the input string divided by 8.
>>SOURCE FREE
*> Example of use of function BIT-TO-CHAR
identification division.
program-id. pgmbittochar.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 AAA PIC X(8) VALUE "0110000".
procedure division.
display BIT-TO-CHAR("00110000") at 0610
display BIT-TO-CHAR("00110001") at 0710
display BIT-TO-CHAR("00110010") at 0810
display BIT-TO-CHAR("00110011") at 0910
display BIT-TO-CHAR(AAA) at 1010
accept omitted
stop run.
Produces:
0
1
2
3
a
BYTE-LENGTH
BYTE-LENGTH Function Syntax
=======================================================================
BYTE-LENGTH(string)
~~~~~~~~~~~
=======================================================================
BYTE-LENGTH returns the length — in bytes — of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal). This intrinsic function is identical to the LENGTH-AN (see LENGTH-AN) function. Note that the value returned by this function is not necessarily the number of characters comprising <string>, but rather the number of actual bytes required to store it.
For example, if <string> is encoded using a double-byte character set such as Unicode UTF-16 (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whose PICTURE (see PICTURE) is N(4) would return a value of 8 rather than the value 4.
Contrast this with the LENGTH (see LENGTH) function.
CHAR
CHAR Function Syntax
=======================================================================
CHAR(integer)
~~~~
=======================================================================
This function returns the character in the ordinal position specified by <integer> (a numeric integer literal or data item with a value of 1 or greater) from the COLLATING SEQUENCE (see OBJECT-COMPUTER) being used by the program.
For example, if the program is using the (default) ASCII character set, CHAR(34) returns the 34th character in the ASCII character set — an exclamation-point (‘!’). If you are using this function to convert a numeric value to its corresponding ASCII character, you must use an argument value one greater than the numeric value.
If an argument whose value is less than 1 or greater than 256 is specified, the character in the program collating sequence corresponding to a value of all zero bits is returned.
The following code is an alternative approach when you just wish to convert a number to its ASCII equivalent:
01 Char-Value.
05 Numeric-Value USAGE BINARY-CHAR.
…
MOVE numeric-character-value TO Numeric-Value
The Char-Value item now has the corresponding ASCII character value.
COMBINED-DATETIME
COMBINED-DATETIME Function Syntax
=======================================================================
COMBINED-DATETIME(days, seconds)
~~~~~~~~~~~~~~~~~
=======================================================================
This function returns a 12-digit numeric result, the first seven digits of which are the integer value of <days> argument (a numeric data item or literal) and the last five of which are the integer value of <seconds> argument (also a numeric data item or literal).
If <days> is less than 1 or greater than 3,067,671, or if <seconds> is less than 1 or greater than 86,400, a value of 0 is returned and a runtime error will result.
<days> Must be in integer date form. For details, see Integer date form. A value in integer date form is a positive integer that represents a number of days succeeding 31 December 1600, in the Gregorian calendar. It is based on a starting date of Monday, 1 January 1601 and integer date 1 represents Monday, 1 January 1601.
<seconds> Must be in standard numeric time form. For details, see Standard numeric time form. A value in standard numeric time form is a numeric value representing seconds past midnight.
The returned value is determined by arithmetic expression Days-1 + (Seconds-2/100000). The date occupies the integer part of the returned value and the time is represented in the fractional part of the returned value.
Example Given the integer date form value "143951", which represents the date 15 February 1995, and the standard numeric time form value "18867.812479168304", which represents the time "05:14:27.812479168304", the returned value would be exactly "143951.1886781247".
CONCAT
CONCAT Function Syntax
=======================================================================
CONCAT | CONCATENATE (argument-1 [, argument-2 ]...)
~~~~~~ ~~~~~~~~~~~
=======================================================================
This function concatenates the <argument-1>, <argument-2>, … (group items, USAGE DISPLAY elementary items and/or alphanumeric literals) together into a single string result.
If a numeric literal or PIC 9 identifier is specified as an argument, decimal points, if any, will be removed and negative signs in PIC S9 fields or numeric literals will be inserted as defined by the SIGN (see SIGN) clause (or absence thereof) of the field. Numeric literals are processed as if SIGN IS TRAILING SEPARATE were in effect.
Note that CONCATENATE (a GnuCOBOL extension) is an alias for this CONCAT function.
CONTENT-LENGTH
CONTENT-LENGTH Function Syntax
=======================================================================
CONTENT-LENGTH argument-1
~~~~~~~~~~~~~~
=======================================================================
Scans for a NUL byte delimiter of the data starting at address in given pointer, and returns the length. The NUL byte is not included in the count. An EC-DATA-PTR-NUL exception is set to exist if the pointer is NUL, and a zero length is returned.
Function CONTENT-LENGTH is a GnuCOBOL extention.
Example:
01 ptr USAGE POINTER.
01 str PIC X(4) VALUE z"abc".
SET ptr TO ADDESS OF str.
DISPLAY FUNCTION CONTENT-LENGTH (str).
Will display 3.
CONTENT-OF
CONTENT-OF Function Syntax
=======================================================================
CONTENT-OF pointer-1 { length }
~~~~~~~~~~
=======================================================================
Takes a pointer and optional length. Returns a character field of the data addressed by the pointer, either up to a NUL byte or to the given length.
The NUL byte is not included in the data when no optional length is given. With an optional count, the character field can hold any content including NUL bytes,
An EC-DATA-PTR-NUL exception is set to exist if the pointer is NUL, and a zero length space is returned.
An EC-SIZE-TRANCATION is set if the resulting field would exceed character field limits and the data is truncated.
Reference modification is allowed on resulting field.
Function CONTENT-OF is a GnuCOBOL extention.
COS
COS Function Syntax
=======================================================================
COS(argument-1)
~~~
=======================================================================
The COS function determines and returns a numeric value that approximates the cosine of an angle, expressed in radians, that is specified by <argument-1> (a numeric literal, a numeric data item or an arithmetic expression). The returned value is:
-1 <= "returned-value" <= +1
If you need to determine the cosine of an angle measured in degrees, you first need to convert that angle to radians as follows:
COMPUTE radians = ( degrees / 180 ) * FUNCTION PI
For example, the angles 0, 90, 180, and 360 degrees correspond to 0, PI/2, PI, and 2PI radians, respectively.
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTCOS. *> SAMPLE PROGRAM
DATA DIVISION.
WORKING-STORAGE SECTION.
01 wRESULT PIC s99v9999999999999999999999999999999.
01 wRadians PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
compute wRadians rounded = ( 0 / 180 * FUNCTION PI)
move FUNCTION COS(wRadians) to wRESULT
DISPLAY 'a. COS 0: ' wRESULT
display 'b. COS 0: ' FUNCTION COS(wRadians)
display 'c. COS 0: ' FUNCTION COS ( 0 / 180 * FUNCTION PI)
compute wRadians rounded = (90 / 180 * FUNCTION PI)
move FUNCTION COS(wRadians) to wRESULT
DISPLAY 'a. COS 90: ' wRESULT
display 'b. COS 90: ' FUNCTION COS(wRadians)
display 'c. COS 90: ' FUNCTION COS ( 90 / 180 * FUNCTION PI)
compute wRadians rounded = (180 / 180 * FUNCTION PI)
move FUNCTION COS(wRadians) to wRESULT
DISPLAY 'a. COS 180: ' wRESULT
display 'b. COS 180: ' FUNCTION COS(wRadians)
display 'c. COS 180: ' FUNCTION COS (180 / 180 * FUNCTION PI)
ACCEPT OMITTED STOP RUN.
a. COS 0: +01.0000000000000000000000000000000
b. COS 0: 000000001
c. COS 0: 000000001
a. COS 90: -00.0000000000000000000000000000002
b. COS 90: -.000000000000000000000000000000248557901415300312447089512527703846091
796856895500685982587326382105466833141286072737454653224
c. COS 90: -.000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000001466008925956743358846676453077695224708884
13732029593575944127485794864903073944722017768852552
a. COS 180: -00.9999999999999999999999999999999
b. COS 180: -0.99999999999999999999999999999999999999999999999999999999999987643793
9288043701869080329790702566
c. COS 180: -000000001
CURRENCY-SYMBOL
CURRENCY-SYMBOL Function Syntax
=======================================================================
CURRENCY-SYMBOL
~~~~~~~~~~~~~~~
=======================================================================
The CURRENCY-SYMBOL function returns the currency symbol character currently in effect for the locale under which your program is running. On UNIX systems, your locale is established via the LANG run-time environment variable (see Run Time Environment Variables) environment variable. On Windows, the Control Panel’s "Regional and Language Options" define the locale.
Changing the currency symbol via the SPECIAL-NAMES (see SPECIAL-NAMES) paragraph’s CURRENCY SYMBOL setting will not affect the value returned by this function.
CURRENT-DATE
CURRENT-DATE Function Syntax
=======================================================================
CURRENT-DATE
~~~~~~~~~~~~
=======================================================================
Returns the current date and time as the following 21-character structure:
01 CURRENT-DATE-AND-TIME.
05 CDT-Year PIC 9(4).
05 CDT-Month PIC 9(2). *> 01-12
05 CDT-Day PIC 9(2). *> 01-31
05 CDT-Hour PIC 9(2). *> 00-23
05 CDT-Minutes PIC 9(2). *> 00-59
05 CDT-Seconds PIC 9(2). *> 00-59
05 CDT-Hundredths-Of-Secs PIC 9(2). *> 00-99
05 CDT-GMT-Diff-Hours PIC S9(2)
SIGN LEADING SEPARATE.
05 CDT-GMT-Diff-Minutes PIC 9(2). *> 00 or 30
Since this function has no arguments, no parenthesis should be specified.
DATE-OF-INTEGER
DATE-OF-INTEGER Function Syntax
=======================================================================
DATE-OF-INTEGER(integer)
~~~~~~~~~~~~~~~
=======================================================================
This function returns a numeric calendar date in yyyymmdd (i.e. Gregorian) format. The date is determined by adding the number of days specified as <integer> (a numeric integer data item or literal) to the date December 31, 1600. For example, DATE-OF-INTEGER(1) returns 16010101 while DATE-OF-INTEGER(150000) returns 20110908.
A value less than 1 or greater than 3067671 (9999/12/31) will return a result of 0.
DATE-TO-YYYYMMDD
DATE-TO-YYYYMMDD Function Syntax
=======================================================================
DATE-TO-YYYYMMDD(yymmdd [, yy-cutoff [, yy-execution-time ]])
~~~~~~~~~~~~~~~~
=======================================================================
You can use this function to convert the six-digit Gregorian date specified as <yymmdd> (a numeric integer data item or literal) to an eight-digit format (yyyymmdd).
The optional <yy-cutoff> (a numeric integer data item or literal) argument is the year cutoff used to delineate centuries; if the year component of the date meets or exceeds this cutoff value, the result will be 19yymmdd; if the year component of the date is less than the cutoff value, the result will be 20yymmdd. The default cutoff value if no second argument is given will be 50.
The optional <yy-execution-time> argument (a numeric integer data item or literal) The default execution time value if no third argument is given will be now equivalent to specifying (FUNCTION NUMVAL (FUNCTION CURRENT-DATE (1:4))).
DAY-OF-INTEGER
DAY-OF-INTEGER Function Syntax
=======================================================================
DAY-OF-INTEGER(integer)
~~~~~~~~~~~~~~
=======================================================================
This function returns a calendar date in yyyyddd (i.e. Julian) format. The date is determined by adding the number of days specified as integer (a numeric integer data item or literal) to December 31, 1600. For example, DAY-OF-INTEGER(1) returns 1601001 while DAY-OF-INTEGER(250000) returns 2011251.
A value less than 1 or greater than 3067671 (9999/12/31) will return a result of 0.
DAY-TO-YYYYDDD
DAY-TO-YYYYDDD Function Syntax
=======================================================================
DAY-TO-YYYYDDD(yyddd [, yy-cutoff [, yy-execution-time ]])
~~~~~~~~~~~~~~
=======================================================================
You can use this function to convert the five-digit Julian date specified as <yyddd> (a numeric integer data item or literal) to a seven-digit numeric Julian format (yyyyddd).
The optional <yy-cutoff> argument (a numeric integer data item or literal) is the year cutoff used to delineate centuries; if the year component of the date meets or exceeds this cutoff value, the result will be 19yyddd; if the year component of the date is less than the cutoff, the result will be 20yyddd. The default cutoff value if no second argument is given will be 50.
The optional <yy-execution-time> argument (a numeric integer data item or literal) The default execution time value if no third argument is given will be now equivalent to specifying (FUNCTION NUMVAL (FUNCTION CURRENT-DATE (1:4))).
E
E Function Syntax
=======================================================================
E
~
=======================================================================
This function returns the mathematical constant E (the base of natural logarithms). The maximum precision with which this value may be returned is 2.7182818284590452353602874713526625.
Since this function has no arguments, no parenthesis should be specified.
EXCEPTION-FILE
EXCEPTION-FILE Function Syntax
=======================================================================
EXCEPTION-FILE
~~~~~~~~~~~~~~
=======================================================================
This function returns I/O exception information from the most-recently executed input or output statement. The information is returned as a 34-character string, where the first two characters are the two-digit file status value (see File Status Codes) and the remaining 32 are the <file-name-1> specification from the file’s SELECT (see SELECT) statement.
The name returned after the file status information will be returned only if the returned file status value is not 00.
Since this function has no arguments, no parenthesis should be specified.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
EXCEPTION-LOCATION
EXCEPTION-LOCATION Function Syntax
=======================================================================
EXCEPTION-LOCATION
~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns exception information from the most-recently failing statement. The information is returned to a 1023 character string in one of the following formats, depending on the nature of the failure:
primary-entry-point-name; paragraph OF section; statement-number
primary-entry-point-name; section; statement-number
primary-entry-point-name; paragraph; statement-number
primary-entry-point-name; statement-number
Since this function has no arguments, no parenthesis should be specified.
The program must be compiled with the -debug switch, -ftraceall switch or -g switch for this function to return any meaningful information.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
EXCEPTION-STATEMENT
EXCEPTION-STATEMENT Function Syntax
=======================================================================
EXCEPTION-STATEMENT
~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the most-recent COBOL statement that generated an exception condition.
Since this function has no arguments, no parenthesis should be specified.
The program must be compiled with the -debug switch, -ftraceall switch or -g switch for this function to return any meaningful information.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
EXCEPTION-STATUS
EXCEPTION-STATUS Function Syntax
=======================================================================
EXCEPTION-STATUS
~~~~~~~~~~~~~~~~
=======================================================================
This function returns the error type (a text string — see column 2 of the upcoming table for the possible values) from the most-recent COBOL statement that generated an exception condition.
Since this function has no arguments, no parenthesis should be specified.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
An alternative to the use of EXCEPTION-STATUS intrinsic function is to use the PROCEDURE DIVISION statement: ACCEPT identifier-1 FROM EXCEPTION STATUS END-ACCEPT.
The following are the error type strings, and their corresponding exception codes and descriptions.
| Code | Error Type | Description |
|---|---|---|
0101 |
EC-ARGUMENT-FUNCTION |
Function argument error |
0202 |
EC-BOUND-ODO |
OCCURS … DEPENDING ON data item out of bounds |
0204 |
EC-BOUND-PTR |
Data-pointer contains an address that is out of bounds |
0205 |
EC-BOUND-REF-MOD |
Reference modifier out of bounds |
0207 |
EC-BOUND-SUBSCRIPT |
Subscript out of bounds |
0303 |
EC-DATA-INCOMPATIBLE |
Incompatible data exception |
0500 |
EC-I-O |
input-output exception |
0501 |
EC-I-O-AT-END |
I-O status 1x |
0502 |
EC-I-O-EOP |
An end of page condition occurred |
0504 |
EC-I-O-FILE-SHARING |
I-O status 6x |
0505 |
EC-I-O-IMP |
I-O status 9x |
0506 |
EC-I-O-INVALID-KEY |
I-O status 2x |
0508 |
EC-I-O-LOGIC-ERROR |
I-O status 4x |
0509 |
EC-I-O-PERMANENT-ERROR |
I-O status 3x |
050A |
EC-I-O-RECORD-OPERATION |
I-O status 5x |
0601 |
EC-IMP-ACCEPT |
Implementation-defined accept condition |
0602 |
EC-IMP-DISPLAY |
Implementation-defined display condition |
0A00 |
EC-OVERFLOW |
Overflow condition |
0A02 |
EC-OVERFLOW-STRING |
STRING overflow condition |
0A03 |
EC-OVERFLOW-UNSTRING |
UNSTRING overflow condition |
0B05 |
EC-PROGRAM-NOT-FOUND |
Called program not found |
0D03 |
EC-RANGE-INSPECT-SIZE |
Size of replace item in inspect differs |
1000 |
EC-SIZE |
Size error exception |
1004 |
EC-SIZE-OVERFLOW |
Arithmetic overflow in calculation |
1005 |
EC-SIZE-TRUNCATION |
Significant digits truncated in store |
1007 |
EC-SIZE-ZERO-DIVIDE |
Division by zero |
1202 |
EC-STORAGE-NOT-ALLOC |
The data-pointer specified in a FREE statement does not identify currently allocated storage |
1203 |
EC-STORAGE-NOT-AVAIL |
The amount of storage requested by an ALLOCATE statement is not available |
EXP
EXP Function Syntax
=======================================================================
EXP(number)
~~~
=======================================================================
Computes and returns the value of the mathematical constant e raised to the power specified by <number> (a numeric literal or data item).
EXP10
EXP10 Function Syntax
=======================================================================
EXP10(number)
~~~~~
=======================================================================
Computes and returns the value of 10 raised to the power specified by <number> (a numeric literal or data item).
FACTORIAL
FACTORIAL Function Syntax
=======================================================================
FACTORIAL(number)
~~~~~~~~~
=======================================================================
This function computes and returns the factorial value of <number> (a numeric literal or data item).
FORMATTED-CURRENT-DATE
FORMATTED-CURRENT-DATE Function Syntax
=======================================================================
FORMATTED-CURRENT-DATE ( argument-1 )
~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
FORMATTED-CURRENT-DATE returns the current date and time provided by the system at run-time, formatted according to date-and-time-format according to the argument type.
FUNCTION FORMATTED-CURRENT-DATE gives you exactly what you asked it to, including up to nanoseconds (8 decimal positions in the seconds) [but the system may only provide miliseconds, especially on older win32].
The function argument must be a national or alphanumeric literal and the content, a combined date and time format.
The returned value is formatted to the same form as <argument-1>.
FORMATTED-DATE
FORMATTED-DATE Function Syntax
=======================================================================
FORMATTED-DATE ( argument-1, argument-2 )
~~~~~~~~~~~~~~
=======================================================================
FORMATTED-DATE uses a format to convert a date in integer date form to a date in the requested format. The returned value will be in date format.
<argument-1> shall be a national or alphanumeric literal.
<argument-2> shall be a value in integer date form.
Example Given the date format "YYYYMMDD" and the value "143951", which represents the date 15 February 1995, the returned value would be "19950215".
FORMATTED-DATETIME
FORMATTED-DATETIME Function Syntax
=======================================================================
FORMATTED-DATETIME ( argument-1, argument-2, argument-3, argument-4 )
~~~~~~~~~~~~~~~~~~
=======================================================================
FORMATTED-DATETIME uses a combined time and date form to convert and combine a date in integer form and a numeric time expressed as seconds past midnight in UTC. See Date and Time Formats for details.
<argument-1> shall be a national or alphanumeric literal.
<argument-2> shall be a value in integer date form.
<argument-3> shall be a value in standard numeric time form.
<argument-4> is an integer specifying the offset from UTC expressed in minutes. If specified must have a value equal or less than 1439. Note: The offset value 1439 represents 23 hours 59 minutes which is one minutes less than a day.
<argument-4> must not be specified if the time portion in <argument-1> is neither a UTC nor an offset format.
The returned value is a representation of the date contained in <argument-2> combined with the time contained in <argument-3> according to the format in <argument-1>.
If the format in <argument-1> indicates that the returned value is to be expressed in UTC, the time portion of the returned value reflects the adjustment of the value in <argument-3> by the offset in <argument-4>.
If the format in <argument-1> indicates that the time is to be returned as an offset from UTC, the value in <argument-3> is reflected directly in the time portion of the returned value and the offset in <argument-4> is reflected directly in the offset portion of the returned value.
Example If the first argument has the format "YYMMDDThhmmss.ss+hhmm", the second argument the value "143951", the third argument the value "18867.812479168304", and the fourth argument the value "+300", the returned value would be "19950215T05142781+0500".
FORMATTED-TIME
FORMATTED-TIME Function Syntax
=======================================================================
FORMATTED-TIME ( argument-1, argument-2, argument-3 )
~~~~~~~~~~~~~~
=======================================================================
FORMATTED-TIME converts a value representing seconds past midnight formatted time of day with optional offset.
<argument-1> shall be a national or alphanumeric literal.
<argument-2> shall be a value in integer time form.
<argument-3> is an integer specifying the offset from UTC expressed in minutes. If specified but have a value equal or less than 1439.
The offset value 1439 represents 23 hours 59 minutes which is one minutes less than a day.
<argument-3> must not be specified if the time portion in <argument-1> is neither a UTC nor an offset format.
Returned value : Is a representation of the standard numeric time contained in <argument-2> according to the format in <argument-1>.
If the format in <argument-1> indicates that the returned value is to be expressed in UTC, the time portion of the returned value reflects the adjustment of the value in <argument-2> by the offset in <argument-3>.
If the format in <argument-1> indicates that the time is to be returned as an offset from UTC, the value in <argument-2> is reflected directly in the time portion of the returned value and the offset in <argument-3> is reflected directly in the offset portion of the returned value.
Example If the first argument has the format "hhmmss.ss+hhmm", the second argument the value "18867.812479168304" which represents the local time, and the third argument the value "-300", which represents the five hours that Eastern Standard Time (EST) differs from UTC, the returned value would be "05142781-0500".
FRACTION-PART
FRACTION-PART Function Syntax
=======================================================================
FRACTION-PART(number)
~~~~~~~~~~~~~
=======================================================================
This function returns that portion of <number> (a numeric data item or a numeric literal) that occurs to the right of the decimal point. FRACTION-PART(3.1415), for example, returns a value of 0.1415. This function is equivalent to the expression:
number -- FUNCTION INTEGER-PART(number)
Example: display "base - " FUNCTION FRACTION-PART(FLOATER).
Gives: base - 000.456789
When moved to a variable, it MUST have a preceding ‘V’ in the PICTURE, i.e., PIC v(4).
HEX-OF
HEX-OF Function Syntax
=======================================================================
HEX-OF {argument-1)
~~~~~~
=======================================================================
HEX-OF function returns an alphanumeric character string consisting of a hexadecimal representation of the argument used on input.
The type of the function is alphanumeric.
<argument-1> must be a data item, literal, or an intrinsic function result of any data class.
Returned values:
An alphanumeric character string consisting of a hexadecimal representation of <argument-1>.
The length of the character string returned, in bytes, is twice the length of <argument-1>, in bytes.
HEX-TO-CHAR
HEX-TO-CHAR Function Syntax
=======================================================================
HEX-TO-CHAR {argument-1)
~~~~~~~~~~~
=======================================================================
HEX-TO-CHAR function returns a character string that represents the hexadecimal digit characters supplied on input.
The type of the function is alphanumeric.
<argument-1> must be an alphanumeric literal, alphanumeric data item, or alphanumeric group item.
<argument-1> must consist only of the characters ‘0’ through ‘9’, ‘A’ through ‘F’, and ‘a’ through ‘f’.
The length of <argument-1> must be a multiple of 2 bytes.
Returned values:
A character string of bytes representing the hexadecimal digit characters of <argument-1>.
The length of the result string is equal to the length of the input string divided by 2.
HIGHEST-ALGEBRAIC
HIGHEST-ALGEBRAIC Function Syntax
=======================================================================
HIGHEST-ALGEBRAIC(numeric-identifier)
~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the highest (i.e. largest or farthest away from 0 in a positive direction if <numeric-identifier> is signed) value that could possibly be stored in <numeric-identifier>. Or in other words the HIGHEST-ALGEBRAIC function provide the ability to manipulate numeric data items in a manner similar to the means that HIGH-VALUES permit with alphanumeric data items, but without the risks of the data incompatibilities associated with those figurative constants.
INTEGER
INTEGER Function Syntax
=======================================================================
INTEGER(number)
~~~~~~~
=======================================================================
The INTEGER function returns the greatest integer value that is less than or equal to <number> (a numeric literal or data item).
INTEGER-OF-DATE
INTEGER-OF-DATE Function Syntax
=======================================================================
INTEGER-OF-DATE(date)
~~~~~~~~~~~~~~~
=======================================================================
This function converts <date> (a numeric integer data item or literal) — presumed to be a Gregorian calendar form standard date (YYYYMMDD) — to internal date form (the number of days that have transpired since 1600/12/31).
Once in that form, mathematical operations may be performed against the internal date before it is transformed back into a date using the DATE-OF-INTEGER (see DATE-OF-INTEGER) or DAY-OF-INTEGER (see DAY-OF-INTEGER) function.
A particular use of this function could also to find the day of the week for a date. See the following example.
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTINTEGEROFDATE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 wDATE PIC 9(08) value zero.
01 wDOFW PIC X(10) value space.
PROCEDURE DIVISION.
move FUNCTION CURRENT-DATE(1:8) to wDATE
evaluate FUNCTION MOD(FUNCTION INTEGER-OF-DATE(wDATE), 7)
when 0 move 'SUNDAY' to wDOFW
when 1 move 'MONDAY' to wDOFW
when 2 move 'TUESDAY' to wDOFW
when 3 move 'WEDNESDAY' to wDOFW
when 4 move 'THURSDAY' to wDOFW
when 5 move 'FRIDAY' to wDOFW
when 6 move 'SATURDAY' to wDOFW
end-evaluate
display 'Today ' wDATE ' IS ' wDOFW
STOP RUN.
INTEGER-OF-DAY
INTEGER-OF-DAY Function Syntax
=======================================================================
INTEGER-OF-DAY(date)
~~~~~~~~~~~~~~
=======================================================================
This function converts <date> (a numeric integer data item or literal) — presumed to be a Julian calendar form standard date (YYYYDDD) — to internal date form (the number of days that have transpired since 1600/12/31).
Once in that form, mathematical operations may be performed against the internal date before it is transformed back into a date using the DATE-OF-INTEGER (see DATE-OF-INTEGER) or DAY-OF-INTEGER (see DAY-OF-INTEGER) function.
INTEGER-OF-FORMATTED-DATE
INTEGER-OF-FORMATTED-DATE Function Syntax
=======================================================================
INTEGER-OF-FORMATTED-DATE ( argument-1, argument-2 )
~~~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
INTEGER-OF-FORMATTED-DATE converts a date that is in specified format to integer date form.
<argument-1> shall be a national or alphanumeric literal. The content must be either a date format or a combined date and time format.
<argument-2> shall be a data item of the same type as <argument-1>.
If <argument-1> is a date format the content of <argument-2> shall be a valid date in that format.
If <argument-1> is a combined date and time format, the content of <argument-2> shall be a valid combined date and time in same format.
INTEGER-PART
INTEGER-PART Function Syntax
=======================================================================
INTEGER-PART(number)
~~~~~~~~~~~~
=======================================================================
Returns the integer portion of <number> (a numeric literal or data item).
LENGTH
LENGTH Function Syntax
=======================================================================
LENGTH(string)
~~~~~~
=======================================================================
Returns the length — in characters — of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal).
The value returned by this function is not the number of bytes of storage occupied by string, but rather the number of actual characters making up the string. For example, if <string> is encoded using a double-byte character set such as Unicode UTF-16 (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whose PICTURE is X(4) would return a value of 4 rather than the value 8 (the actual number of bytes of storage occupied by that item).
Contrast this function with the BYTE-LENGTH (see BYTE-LENGTH) and LENGTH-AN (see LENGTH-AN) functions.
LENGTH-AN
LENGTH-AN Function Syntax
=======================================================================
LENGTH-AN(string)
~~~~~~~~~
=======================================================================
This function returns the length — in bytes of storage — of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal).
This intrinsic function is identical to the BYTE-LENGTH (see BYTE-LENGTH) function.
Note that the value returned by this function is not the number of characters making up the <string>, but rather the number of actual bytes of storage required to store <string>. For example, if <string> is encoded using a double-byte character set such as Unicode UTF-16 (where each character is represented by 16 bits of storage, not the 8-bits inherent to character sets like ASCII or EBCDIC), then calling this function with a <string> argument whose PICTURE is N(4) would return a value of 8 rather than the value 4.
Contrast this with the LENGTH (see LENGTH) function.
LOCALE-COMPARE
LOCALE-COMPARE Function Syntax
=======================================================================
LOCALE-COMPARE(argument-1, argument-2 [ , locale ])
~~~~~~~~~~~~~~
=======================================================================
The LOCALE-COMPARE function returns a character indicating the result of comparing <argument-1> and <argument-2> using a culturally-preferred ordering defined by a <locale>.
Either or both of the 1st two arguments may be an alphanumeric literal, a group item or an elementary item appropriate to storing alphabetic or alphanumeric data. If the lengths of the two arguments are unequal, the shorter will be assumed to be padded to the right with spaces.
The two arguments will be compared, character by character, against each other until their relationship to each other can be determined. The comparison is made according to the cultural rules in effect for <locale> name or for the current locale if no <locale> argument is specified. Once that relationship is determined, a one-character alphanumeric value will be returned as follows:
‘
<’ — If <argument-1> is determined to be less than <argument-2>‘
=’ — If the two arguments are equal to each other‘
>’ — If <argument-1> is determined to be greater than <argument-2>
See LOCALE Names, for a list of typically-available locale names.
LOCALE-DATE
LOCALE-DATE Function Syntax
=======================================================================
LOCALE-DATE(date [, locale ])
~~~~~~~~~~~
=======================================================================
Converts the eight-digit Gregorian <date> (a numeric integer data item or literal) from yyyymmdd format to the format appropriate to the current locale. On a Windows system, this will be the “short date” format as set using Control Panel.
You may include an optional second argument to specify the <locale> name (group item or PIC X identifier) you’d like to use for date formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.
LOCALE-TIME
LOCALE-TIME Function Syntax
=======================================================================
LOCALE-TIME(time [, locale ])
~~~~~~~~~~~
=======================================================================
Converts the four- (hhmm) or six-digit (hhmmss) <time> (a numeric integer data item or literal) to a format appropriate to the current locale. On a Windows system, this will be the “time” format as set using Control Panel.
You may include an optional <locale> name (a group item or PIC X identifier) you’d like to use for time formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.
LOCALE-TIME-FROM-SECONDS
LOCALE-TIME-FROM-SECONDS Function Syntax
=======================================================================
LOCALE-TIME-FROM-SECONDS(seconds [, locale ])
~~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
Converts the number of <seconds> since midnight (a numeric integer data item or literal) to a format appropriate to the current locale. On a Windows system, this will be the “time” format as set using Control Panel.
You may include an optional <locale> name (a group item or PIC X identifier) you’d like to use for time formatting. If used, this second argument must be an identifier. Locale names are specified using UNIX-standard names.
See LOCALE Names, for a list of typically-available locale names.
LOG
LOG Function Syntax
=======================================================================
LOG(number)
~~~
=======================================================================
Computes and returns the natural logarithm (base e) of <number> (a numeric literal or data item).
LOG10
LOG10 Function Syntax
=======================================================================
LOG10(number)
~~~~~
=======================================================================
Computes and returns the base 10 logarithm of <number> (a numeric literal or data item).
LOWER-CASE
LOWER-CASE Function Syntax
=======================================================================
LOWER-CASE(string)
~~~~~~~~~~
=======================================================================
This function returns the value of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal), converted entirely to lower case.
What constitutes a “letter” (or upper/lower case too, for that manner) may be influenced through the use of a CHARACTER CLASSIFICATION (see OBJECT-COMPUTER).
LOWEST-ALGEBRAIC
LOWEST-ALGEBRAIC Function Syntax
=======================================================================
LOWEST-ALGEBRAIC(numeric-identifier)
~~~~~~~~~~~~~~~~
=======================================================================
This function returns the lowest (i.e. smallest or farthest away from 0 in a negative direction if <numeric-identifier> is signed) value that could possibly be stored in <numeric-identifier>. Or in other words this function LOWEST-ALGEBRAIC provides the ability to manipulate numeric data items in a manner similar to the means that LOW-VALUES permit with alphanumeric data items, but without the risks of the data incompatibilities associated with those figurative constants.
MAX
MAX Function Syntax
=======================================================================
MAX(number-1 [, number-2 ]...)
~~~
=======================================================================
This function returns the maximum value from the specified list of numbers (each <number-n> may be a numeric data item or a numeric literal).
MEAN
MEAN Function Syntax
=======================================================================
MEAN(number-1 [, number-2 ]...)
~~~~
=======================================================================
This function returns the statistical mean value of the specified list of numbers (each <number-n> may be a numeric data item or a numeric literal).
MEDIAN
MEDIAN Function Syntax
=======================================================================
MEDIAN(number-1 [, number-2 ]...)
~~~~~~
=======================================================================
This function returns the statistical median value of the specified list of numbers (each <number-n> may be a numeric data item or a numeric literal).
MIDRANGE
MIDRANGE Function Syntax
=======================================================================
MIDRANGE(number-1 [, number-2 ]...)
~~~~~~~~
=======================================================================
The MIDRANGE (middle range) function returns a numeric value that is the arithmetic mean (average) of the values of the minimum and maximum numbers from the supplied list. Each <number-n> may be a numeric data items or a numeric literal.
MIN
MIN Function Syntax
=======================================================================
MIN(number-1 [, number-2 ]...)
~~~
=======================================================================
This function returns the minimum value from the specified list of numbers (each <number-n> may be a numeric data item or a numeric literal).
MOD
MOD Function Syntax
=======================================================================
MOD(value, modulus)
~~~
=======================================================================
This function returns the value of <value> modulo <modulus> (essentially the remainder from the division of <value> by <modulus>).
Both arguments may be numeric data items or numeric literals.
Either (or both) may have a non-integer value which is an GnuCobol extension only. The default usage is: <value> and <modulus> shall be integers, and the value of <modulus> shall not be zero. If this rule isn’t matched, GnuCOBOL will internally change the arguments to have the same "scale" and ignore the decimal [e.g. if arg-1 is 1.234 and arg-2 is 0.5 GnuCOBOL will calculate 1234 / 500], but that isn’t portable across compilers.
MODULE-CALLER-ID
MODULE-CALLER-ID Function Syntax
=======================================================================
MODULE-CALLER-ID
~~~~~~~~~~~~~~~~
=======================================================================
This function returns the null string if it is executed within a main program. When executed with a subprogram, it returns the entry-point name of the program that called the subprogram.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-DATE
MODULE-DATE Function Syntax
=======================================================================
MODULE-DATE
~~~~~~~~~~~
=======================================================================
This function Returns the date the GnuCOBOL program that is executing the function was compiled, in the form yyyymmdd.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-FORMATTED-DATE
MODULE-FORMATTED-DATE Function Syntax
=======================================================================
MODULE-FORMATTED-DATE
~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the fully-formatted date and time when the program executing the function was compiled. The exact format of this returned string value may vary depending on the operating system and GnuCOBOL build type.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-ID
MODULE-ID Function Syntax
=======================================================================
MODULE-ID
~~~~~~~~~
=======================================================================
This function returns the primary entry-point name (i.e. the PROGRAM-ID or FUNCTION-ID of the program. See IDENTIFICATION DIVISION, for information on those clauses.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-PATH
MODULE-PATH Function Syntax
=======================================================================
MODULE-PATH
~~~~~~~~~~~
=======================================================================
This function returns the full path to the executable version of this GnuCOBOL program. The filename component of this value will be exactly as typed on the command line, down to the use of upper- and lower-case letters and presence (or absence) of any extension.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-SOURCE
MODULE-SOURCE Function Syntax
=======================================================================
MODULE-SOURCE
~~~~~~~~~~~~~
=======================================================================
The filename of the source code of the program (as specified on the cobc command when the program was compiled) is returned by this function.
The discussion of the MODULE-TIME (see MODULE-TIME) function includes a sample program that uses this function.
Since this function has no arguments, no parenthesis should be specified.
MODULE-TIME
MODULE-TIME Function Syntax
=======================================================================
MODULE-TIME
~~~~~~~~~~~
=======================================================================
This function returns the time the GnuCOBOL program was compiled, in the form hhmmss.
Since this function has no arguments, no parenthesis should be specified.
The following sample program uses all the MODULE- Functions:
IDENTIFICATION DIVISION.
PROGRAM-ID. DEMOMODULE.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.
PROCEDURE DIVISION.
000-Main.
DISPLAY "MODULE-CALLER-ID = [" MODULE-CALLER-ID ‘]’
DISPLAY "MODULE-DATE = [" MODULE-DATE ‘]’
DISPLAY "MODULE-FORMATTED-DATE = [" MODULE-FORMATTED-DATE ‘]’
DISPLAY "MODULE-ID = [" MODULE-ID ‘]’
DISPLAY "MODULE-PATH = [" MODULE-PATH ‘]’
DISPLAY "MODULE-SOURCE = [" MODULE-SOURCE ‘]’
DISPLAY "MODULE-TIME = [" MODULE-TIME ‘]’
STOP RUN
.
The program produces this output when executed:
MODULE-CALLER-ID = []
MODULE-DATE = [20180522]
MODULE-FORMATTED-DATE = [May 22 2018 12:43:14]
MODULE-ID = [DEMOMODULE]
MODULE-PATH = [/home/vince/cobolsrc/ACAS/demomodule]
MODULE-SOURCE = [demomodule.cbl]
MODULE-TIME = [124314]
MONETARY-DECIMAL-POINT
MONETARY-DECIMAL-POINT Function Syntax
=======================================================================
MONETARY-DECIMAL-POINT
~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
MONETARY-DECIMAL-POINT returns the character used to separate the integer portion from the fractional part of a monetary currency value according to the rules currently in effect for the locale under which your program is running.
On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the LANG run-time environment variable (see Run Time Environment Variables) environment variable. On Windows, the Control Panel’s Regional and Language Options define the locale.
Using the DECIMAL-POINT IS COMMA (see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.
Since this function has no arguments, no parenthesis should be specified.
MONETARY-THOUSANDS-SEPARATOR
MONETARY-THOUSANDS-SEPARATOR Function Syntax
=======================================================================
MONETARY-THOUSANDS-SEPARATOR
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the character used to separate the thousands digit groupings of monetary currency values according to the rules currently in effect for the locale under which your program is running.
On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the LANG run-time environment variable (see Run Time Environment Variables) environment variable. On Windows, the Control Panel’s Regional and Language Options define the locale.
Using the DECIMAL-POINT IS COMMA (see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.
Since this function has no arguments, no parenthesis should be specified.
NUMERIC-DECIMAL-POINT
NUMERIC-DECIMAL-POINT Function Syntax
=======================================================================
NUMERIC-DECIMAL-POINT
~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the character used to separate the integer portion of a non-integer numeric item from the fractional part according to the rules currently in effect for the locale under which your program is running.
On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the LANG run-time environment variable (see Run Time Environment Variables) environment variable. On Windows, the Control Panel’s Regional and Language Options define the locale.
Using the DECIMAL-POINT IS COMMA (see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.
Since this function has no arguments, no parenthesis should be specified.
NUMERIC-THOUSANDS-SEPARATOR
NUMERIC-THOUSANDS-SEPARATOR Function Syntax
=======================================================================
NUMERIC-THOUSANDS-SEPARATOR
~~~~~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the character used to separate the thousands digit groupings of numeric values according to the rules currently in effect for the locale under which your program is running.
On UNIX (including OSX, Windows/Cygwin and Windows/MinGW) systems, your locale is established via the LANG run-time environment variable (see Run Time Environment Variables) environment variable. On Windows, the Control Panel’s Regional and Language Options define the locale.
Using the DECIMAL-POINT IS COMMA (see SPECIAL-NAMES) clause in your program will not affect the value returned by this function.
Since this function has no arguments, no parenthesis should be specified.
NUMVAL
NUMVAL Function Syntax
=======================================================================
NUMVAL(string)
~~~~~~
=======================================================================
The NUMVAL function converts a <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) to its corresponding numeric value.
The <string> must have any of the following formats, where ‘#’ represents a sequence of one or more decimal digits:
# -# +# #- #+ #CR #DB
#.# -#.# +#.# #.#- #.#+ #.#CR #.#DB
There must be at least one digit character in the string.
Leading and/or trailing spaces are allowed, as are spaces before the first digit.
The character period in <argument-1> <string>, represents the decimal separator. The character comma in <argument-1> represents the grouping separator. When the DECIMAL-POINT IS COMMA clause is specified, the character comma shall be used in <argument-1> to represent the decimal separator and the character period shall be used to represent the grouping separator.
Note: Locale-based functionality equivalent to NUMVAL can be obtained by using the NUMVAL-C function with the LOCALE keyword. A currency sign is optional in NUMVAL-C. The locale category LC_MONETARY will be used because there is no sign convention specified in locale category LC_NUMERIC.
Returned values:
The returned value is the numeric value represented by <string>.
If it contains a CR, DB, or the minus sign (‘-’), the returned value is negative.
NUMVAL-C
NUMVAL-C Function Syntax
=======================================================================
NUMVAL-C (string [, symbol ]
~~~~~~~~
[, LOCALE locale-name-1 ] [, ANYCASE ])
=======================================================================
This function converts a <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) representing a currency value to its corresponding numeric value.
The currency string if any, and any grouping separators preceding the decimal separator are ignored. Optionally, the currency string, sign convention, grouping separator and the decimal separator permitted in the character string may be specified by locale category LC-MONETARY, or the currency string may be specified by <symbol>.
The optional <symbol> character represents the currency symbol (a non-space single-character group item, USAGE DISPLAY elementary item or alphanumeric literal) that may be used as the currency character in <string>. Any spaces including leading or trailing are ignored. If no <symbol> is specified, the value that would be returned by the CURRENCY-SYMBOL intrinsic function (see CURRENCY-SYMBOL) will be used.
If this references the LOCALE :
Changing the currency symbol via the SPECIAL-NAMES paragraph’s CURRENCY SYMBOL setting will not affect the value returned by this function.
While NUMVAL-C will always use the currency symbol that is specified via the SPECIAL-NAMES paragraph’s CURRENCY SYMBOL (or the system default which is currently always ‘$’).
<string> may have any of the following formats, where ‘#’ represents a sequence of one or more decimal digits and ‘$’ represents the <symbol> character:
# -# +# #- #+ #CR #DB
#.# -#.# +#.# #.#- #.#+ #.#CR #.#DB
$# -$# +$# $#- $#+ $#CR $#DB
$#.# -$#.# +$#.# $#.#- $#.#+ $#.#CR $#.#DB
There must be at least one digit character in the string.
Leading and/or trailing spaces are allowed, as are spaces before and/or after the currency symbol, sign, CR and DB characters.
If the ANYCASE keyword is used the matching rules for detecting a currency string in <argument-1> are case-insensitive. If the ANYCASE keyword is not specified, the matching rules are case-sensitive.
If neither symbol nor the LOCALE keyword is specified, there shall be only one currency string used, either the default currency sign or a currency string specified in the SPECIAL-NAMES paragraph.
The returned value is the numeric value represented by string.
When the LOCALE keyword is specified, the returned value is negative if string contains a negative sign.
When the LOCALE keyword is not specified, the returning value is negative if string contains CR, DB, or a minus sign.
NUMVAL-C-2
NUMVAL-C Function Syntax
=======================================================================
NUMVAL-C (argument-1 [, argument-2 ]
~~~~~~~~
[, LOCALE locale-name-1 ] [, ANYCASE ])
=======================================================================
This function returns the numeric value represented by the character string specified by <argument-1> and defined as alphanumeric.
<argument-2>, the currency string if any, and any grouping separators preceding the decimal separator are ignored. Optionally, the currency string, sign convention, grouping separator and the decimal separator permitted in the character string may be specified by locale category LC-MONETARY, or the currency string may be specified by <argument-2>.
The optional alphanumeric <argument-2> character represents the currency symbol (a non-space and at least one single-character item, that may be used as the currency character in <argument-1>. Any spaces including leading or trailing are ignored. If no <argument-2> is specified, the value that would be returned by the CURRENCY-SYMBOL intrinsic function (see CURRENCY-SYMBOL) will be used. <argument-2> must not contain any of the digits - through 9, characters ‘*’, ‘+’, ‘-’, ‘,’ or ‘.’; or the two consecutive letters CR or DB, whether upper or lower case or a combination of both.
<argument-2> specifies a currency string that may appear in <argument-1>.
If the ANYCASE keyword is specified, the matching rules for detecting a currency string in <argument-1> are case-insensitive. If not specified, the matching rules are case-sensitive.
If neither <argument-2> nor the LOCALE keyword is specified, there shall be only one currency string used, either the default currency sign or a currency string specified in the SPECIAL-NAMES paragraph.
While NUMVAL-C will always use the currency symbol that is specified via the SPECIAL-NAMES paragraph’s CURRENCY SYMBOL (or the system default which is currently always ‘$’) <argument-1> shall have any of the following formats, where ‘#’ represents a sequence of one or more decimal digits and ‘$’ represents the <symbol> character:
# -# +# #- #+ #CR #DB
#.# -#.# +#.# #.#- #.#+ #.#CR #.#DB
$# -$# +$# $#- $#+ $#CR $#DB
$#.# -$#.# +$#.# $#.#- $#.#+ $#.#CR $#.#DB
There must be at least one digit character in the string.
Leading and/or trailing spaces are allowed, as are spaces before and/or after the currency symbol, sign, CR and DB characters.
The returned value is the numeric value represented by <argument-1>.
When the LOCALE keyword is specified, the returned value is negative if string contains a negative sign and when not specified, the returning value is negative if string contains CR, DB, or a minus sign.
NUMVAL-F
NUMVAL-F Function Syntax
=======================================================================
NUMVAL-F(char)
~~~~~~~~
=======================================================================
This function converts a <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) representing a floating-point value to its corresponding numeric value.
# -# +# #E# -#E# +#E#
#E+# -#E+# +#E+# #E-# -#E-# +#E-#
#.# -#.# +#.# #.#E# -#.#E# +#.#E#
#.#E+# -#.#E+# +#.#E+# #.#E-# -#.#E-# +#.#E-#
There must be at least one digit character both before and after the E in the string.
Leading and/or trailing spaces are allowed, as are spaces before and/or after any sign characters.
ORD
ORD Function Syntax
=======================================================================
ORD(char)
~~~
=======================================================================
This function returns the ordinal position in the program character set (usually ASCII) corresponding to the 1st character of <char> argument (a group item, USAGE DISPLAY elementary item or alphanumeric literal).
For example, assuming the program is using the standard ASCII collating sequence, ORD('!') returns 34 because ‘!’ is the 34th ASCII character. If you are using this function to convert an ASCII character to its numeric value, you must subtract one from the result. The following code is an alternative approach when you just wish to convert an ASCII character to its numeric equivalent:
01 Char-Value.
05 Numeric-Value USAGE BINARY-CHAR.
…
MOVE "character" TO Char-Value
Numeric-Value now has the numeric value of character.
ORD-MAX
ORD-MAX Function Syntax
=======================================================================
ORD-MAX(char-1 [, char-2 ]...)
~~~~~~~
=======================================================================
This function returns the ordinal position in the argument list corresponding to the <char-n> whose 1st character has the highest position in the program collating sequence (usually ASCII).
For example, assuming the program is using the standard ASCII collating sequence, ORD-MAX('Z', 'z', '!') returns 2 because the 2nd character in the argument list (the ASCII character ‘z’) occurs after ‘Z’ and ‘!’ in the program collating sequence. Each <char-n> argument may be a group item, USAGE DISPLAY elementary item or alphanumeric literal.
ORD-MIN
ORD-MIN Function Syntax
=======================================================================
ORD-MIN(char-1 [, char-2 ]...)
~~~~~~~
=======================================================================
This function returns the ordinal position in the argument list corresponding to the <char-n> whose 1st character has the lowest position in the program collating sequence (usually ASCII).
For example, assuming the program is using the standard ASCII collating sequence, ORD-MIN('Z', 'z', '!') returns 3 because the 3rd character in the argument list (the ASCII character ‘!’) occurs before ‘Z’ and ‘z’ in the program collating sequence. Each <char-n> argument may be a group item, USAGE DISPLAY elementary item or alphanumeric literal.
PI
PI Function Syntax
=======================================================================
PI
~~
=======================================================================
This function returns the mathematical constant PI. The maximum precision with which this value may be returned is 3.1415926535897932384626433832795029.
Since this function has no arguments, no parenthesis should be specified.
PRESENT-VALUE
PRESENT-VALUE Function Syntax
=======================================================================
PRESENT-VALUE(rate, value-1 [, value-2 ])
~~~~~~~~~~~~~
=======================================================================
The PRESENT-VALUE function returns a value that approximates the present value of a series of future period-end amounts specified by the various <value-n> arguments at a discount rate specified by the <rate> argument. All arguments are numeric data items and/or numeric literals.
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. PPresValue.
*> The sample: you pay for a machine 1500 USD
*> You rent the machine at 350 USD per year per 5 years (= 1750).
*> The program calculates (NET)PRESENT VALUE of 1750
*> when the discount rate is 1%, 2% up to 10%.
DATA DIVISION. WORKING-STORAGE SECTION.
01 PaymentsNum constant as 5.
01 PaymentsAmount constant as 350.
01 Expenditure PIC 999999V99 value 1500.
01 TOTAL-CASH-FLOW PIC 999999V99 value zero.
01 DiscountRate PIC S99V99 VALUE 0.00.
77 DiscountRateP PIC S99V99 VALUE 0.00.
01 filler.
05 PaymentAmount PIC S9999V99 OCCURS PaymentsNum TIMES VALUE PaymentsAmount.
01 PresValue PIC 9(6)V99 value zero.
01 NET-PresValue PIC S9(6)V99 value zero.
PROCEDURE DIVISION.
COMPUTE TOTAL-CASH-FLOW =
FUNCTION SUM (PaymentAmount(1) PaymentAmount(2) PaymentAmount(3)
PaymentAmount(4) PaymentAmount(5))
DISPLAY SPACE
DISPLAY 'Expenditure: ' Expenditure ' Total Cashflow: ' TOTAL-CASH-FLOW
DISPLAY SPACE
PERFORM 10 TIMES
COMPUTE DiscountRate = DiscountRate + 0.01
COMPUTE DiscountRateP = DiscountRate * 100
COMPUTE PresValue ROUNDED =
FUNCTION PRESENT-VALUE (DiscountRate PaymentAmount(1) PaymentAmount(2)
PaymentAmount(3) PaymentAmount(4) PaymentAmount(5))
COMPUTE NET-PresValue = - Expenditure + PresValue
DISPLAY 'DiscountRate: ' DiscountRateP '% PresValue: ' PresValue
' NET-PresValue: ' NET-PresValue
END-PERFORM
ACCEPT omitted GOBACK.
This is a case where passing parameters to the intrinsic function PRESENT-VALUE would need the ability to indicate "ALL" and then write the statement as:
FUNCTION PRESENT-VALUE(DiscountRate PaymentAmount(ALL))This feature (ALL parameter) has not yet been implemented.
RANDOM
RANDOM Function Syntax
=======================================================================
RANDOM[(seed)]
~~~~~~
=======================================================================
This function returns a pseudo-random non-integer value in the range 0 >= to < 1 (for example: 0.123456789).
The purpose of the optional <seed> argument, is to initialize the chain of pseudo-random numbers that will be returned by the function. Not only will calls to this function using the same <seed> value return the same pseudo-random number, but so will all subsequent executions of the function without a <seed>. This is actually a good thing when you are testing your program because you can rely on always receiving the same sequence of “random” numbers if you always start using the same <seed>.
The <seed> may be any form of literal or data item or arithmetic expression but MUST be class numeric. Its numeric value will serve as the seed value.
GnuCOBOL has an extension that if that rule is not met it internally calls FUNCTION NUMVAL (see NUMVAL) on the given argument and passes that as a seed.
Take, for example, the following sample program:
IDENTIFICATION DIVISION.
PROGRAM-ID. DEMORANDOM.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Pseudo-Random-Number USAGE COMP-1.
PROCEDURE DIVISION.
MOVE FUNCTION RANDOM(1) TO Pseudo-Random-Number
DISPLAY Pseudo-Random-Number
PERFORM 4 TIMES
MOVE FUNCTION RANDOM() TO Pseudo-Random-Number
DISPLAY Pseudo-Random-Number
END-PERFORM
STOP RUN.
Every time this program is executed, it will produce the same output, because the same sequence of pseudo-random numbers will be generated:
0.5441364
0.047651578
0.77186662
0.056523036
0.63045478
Once your program has been thoroughly tested, you’ll want different sequences to be generated each time the program runs. One possible way to accomplish this is to use a <seed> that is likely to be different every time the program is executed, as is likely to be the case if the first MOVE statement in the previous example were replaced by this:
MOVE RANDOM(FUNCTION CURRENT-DATE(1:16)) TO Pseudo-Random-Number
The first 16 characters returned by the CURRENT-DATE (see CURRENT-DATE) function will be a number in the format YYYYMMDDhhmmssnn, where YYYYMMDD is the current calendar date and hhmmssnn is the current time of day to the one one-hundredth of a second. Since two different executions of the program will never get identical CURRENT-DATE values (unless they are executed in extremely close time frames to one another), using those first sixteen characters as the RANDOM seed will guarantee that receiving a duplicate sequence of pseudo-random numbers in two different executions of the program will be highly unlikely.
If you do not use a seed then the RANDOM function will automatically determine an internal different seed at each execution using the NUMVAL function.
Often you need to generate a random number between two numbers. Following example shows how to do it.
>>source free
IDENTIFICATION DIVISION.
PROGRAM-ID. RANDOM-IN-RANGE.
*> Generate random numbers from 25 and 70
DATA DIVISION.
WORKING-STORAGE SECTION.
01 RANDOM-NUMBER PIC 999 value zero.
PROCEDURE DIVISION.
perform 10 times
compute RANDOM-NUMBER = 25 + ( (70 - 25) * (FUNCTION RANDOM) )
display RANDOM-NUMBER
end-perform
display space
*> or, to include the upper value 70 as possible choice
perform 10 times
compute RANDOM-NUMBER = 25 + ( (70 - 25 + 1) * (FUNCTION RANDOM) )
display RANDOM-NUMBER
end-perform
accept omitted
STOP RUN.
RANGE
RANGE Function Syntax
=======================================================================
RANGE(number-1 [, number-2 ]...)
~~~~~
=======================================================================
The RANGE function returns a value that is equal to the value of the maximum <number-n> in the argument list minus the value of the minimum <number-n> argument.
All <number-n> arguments are numeric data items and/or numeric literals.
REM
REM Function Syntax
=======================================================================
REM(number,divisor)
~~~
=======================================================================
This function returns a numeric value that is the remainder of <number> divided by <divisor>. Both arguments must be numeric data items or numeric literals.
REVERSE
REVERSE Function Syntax
=======================================================================
REVERSE(string)
~~~~~~~
=======================================================================
This function returns the byte-by-byte reversed value of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal).
SECONDS-FROM-FORMATTED-TIME
SECONDS-FROM-FORMATTED-TIME Function Syntax
=======================================================================
SECONDS-FROM-FORMATTED-TIME(format,time)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function decodes the string <time> — whose value represents a formatted time — and returns the total number of seconds that string represents.
The <time> string must contain hours, minutes and seconds. The time argument may be specified as a group item, USAGE DISPLAY elementary item or an alphanumeric literal.
The <format> argument is a string (a group item, USAGE DISPLAY elementary item or an alphanumeric literal) documenting the format of <time> using hh, mm and ss to denote where the respective time information can be found. Any other characters found in <format> represent character positions that will be ignored. For example, a format of hhmmss indicates that <time> will be treated as a six-digit string value where the first two characters are the number of hours, the next two represent minutes and the last two represent seconds. A <format> of hh:mm:ss, however, describes <time> as an eight-character string where characters 3 and 6 will be ignored.
SECONDS-PAST-MIDNIGHT
SECONDS-PAST-MIDNIGHT Function Syntax
=======================================================================
SECONDS-PAST-MIDNIGHT
~~~~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the current time of day expressed as the total number of elapsed seconds since midnight. Since this function has no arguments, no parenthesis should be specified.
SIGN.
SIGN Function Syntax
=======================================================================
SIGN(number)
~~~~
=======================================================================
The SIGN function returns a -1 if the value of <number> (a numeric literal or numeric data item) is negative, a zero if the value of <number> is exactly zero and a 1 if the value of <number> if greater than 0. Caution. Please do not confuse the SIGN Intrinsic Function with the SIGN clause of Data Division.
SIN
SIN Function Syntax
=======================================================================
SIN(argument-1)
~~~
=======================================================================
The SIN function determines and returns a numeric value that approximates the sine of an angle, expressed in radians, that is specified by <argument-1> (a numeric literal, a numeric data item or an arithmetic expression). The returned value is:
-1 <= "returned-value" <= +1
If you need to determine the sine of an angle measured in degrees, you first need to convert that angle to radians as follows:
COMPUTE radians = ( degrees / 180 ) * FUNCTION PI
For example, the angles 0, 90, 180, and 360 degrees correspond to 0, PI/2, PI, and 2PI radians, respectively.
>>SOURCE FREE
IDENTIFICATION DIVISION. *> SAMPLE PROGRAM
PROGRAM-ID. TESTSIN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 wRESULT PIC s99v9999999999999999999999999999999.
01 wRadians PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
compute wRadians rounded = ( 0 / 180 * FUNCTION PI)
move FUNCTION SIN(wRadians) to wRESULT
DISPLAY 'a. SIN 0: ' wRESULT
display 'b. SIN 0: ' FUNCTION SIN(wRadians)
display 'c. SIN 0: ' FUNCTION SIN ( 0 / 180 * FUNCTION PI)
compute wRadians rounded = (90 / 180 * FUNCTION PI)
move FUNCTION SIN(wRadians) to wRESULT
DISPLAY 'a. SIN 90: ' wRESULT
display 'b. SIN 90: ' FUNCTION SIN(wRadians)
display 'c. SIN 90: ' FUNCTION SIN ( 90 / 180 * FUNCTION PI)
compute wRadians rounded = (180 / 180 * FUNCTION PI)
move FUNCTION SIN(wRadians) to wRESULT
DISPLAY 'a. SIN 180: ' wRESULT
display 'b. SIN 180: ' FUNCTION SIN(wRadians)
display 'c. SIN 180: ' FUNCTION SIN (180 / 180 * FUNCTION PI)
ACCEPT OMITTED STOP RUN.
Output:
a. SIN 0: +00.0000000000000000000000000000000
b. SIN 0: 000000000
c. SIN 0: 000000000
a. SIN 90: +00.9999999999999999999999999999999
b. SIN 90: 0.99999999999999999999999999999999999999999999999999999999999996910948
4822010925467270082447675642
c. SIN 90: 000000001
a. SIN 180: -00.0000000000000000000000000000004
b. SIN 180: -.000000000000000000000000000000497115802830600624894179025055407692183
593713791001371965174637408047681109389828428819578507325
c. SIN 180: -.000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000002932017851913486717693352906155390449417768
27464059187151888254971589729806147889444035537705105
SQRT
SQRT Function Syntax
=======================================================================
SQRT (number)
~~~~
=======================================================================
The SQRT function returns a numeric value that approximates the square root of <number> (a numeric data item or numeric literal with a non-negative value).
The following two statements produce identical results:
01 Result PIC 9(4).9(10).
…
MOVE FUNCTION SQRT(15) TO Result
COMPUTE Result = 15 ** 0.5
STANDARD-DEVIATION
STANDARD-DEVIATION Function Syntax
=======================================================================
STANDARD-DEVIATION(number-1 [, number-2 ]...)
~~~~~~~~~~~~~~~~~~
=======================================================================
This function returns the statistical standard deviation of the list of <number-n> arguments (numeric data items or numeric literals).
STORED-CHAR-LENGTH
STORED-CHAR-LENGTH Function Syntax
=======================================================================
STORED-CHAR-LENGTH(string)
~~~~~~~~~~~~~~~~~~
=======================================================================
Returns the length — in bytes — of the specified string (a group item, USAGE DISPLAY elementary item or alphanumeric literal), minus the total number of trailing spaces, if any.
SUBSTITUTE
SUBSTITUTE Function Syntax
=======================================================================
SUBSTITUTE(string, from-1, to-1 [, from-n, to-n ]...)
~~~~~~~~~~
=======================================================================
This function parses <string>, replacing all occurrences of <from-n> strings with the corresponding <to-n> strings. The <from-n> strings must match sequences in <string> exactly with regard to value and case. A <from-n> string does not have to be the same length as its corresponding <to-n> string. All arguments are group items, USAGE DISPLAY elementary items or alphanumeric literals. A null <to-n> string will be treated as a single space.
When using Variables in place of <string> attention to NOT wanting Leading or trailing spaces usage of function TRIM needs to be utilised as failure to do so will result in variables treated with any unwanted spaces leading and/or trailing, i.e.,
move function SUBSTITUTE(WS-Dest-File-Path, function TRIM(WS-Inbound-Path),
function TRIM(WS-Desc-Path)) to WS-Dest-File-Path
SUBSTITUTE-CASE
SUBSTITUTE-CASE Function Syntax
=======================================================================
SUBSTITUTE-CASE(string, from-1, to-1 [, from-n, to-n ]...)
~~~~~~~~~~~~~~~
=======================================================================
The SUBSTITUTE-CASE function operates the same as the SUBSTITUTE (see SUBSTITUTE) function, except that <from-n> string matching is performed without regard to case.
All arguments are group items, USAGE DISPLAY elementary items or alphanumeric literals.
When using Variables in place of <string> attention to NOT wanting Leading or trailing spaces usage of function TRIM needs to be utilised as failure to do so will result in variables treated with any unwanted spaces leading and/or trailing, i.e.,
move function SUBSTITUTE-CASE(WS-Dest-File-Path, function TRIM(WS-Inbound-Path),
function TRIM(WS-Desc-Path)) to WS-Dest-File-Path
SUM.
SUM Function Syntax
=======================================================================
SUM(number-1 [, number-2 ]...)
~~~
=======================================================================
The SUM function returns a value that is the sum of <number-n> arguments (these may be numeric data items or numeric literals). Caution. Please do not confuse the SUM Intrinsic Function with the SUM clause of Data Division.
TAN
TAN Function Syntax
=======================================================================
TAN(argument-1)
~~~
=======================================================================
The TAN function determines and returns a numeric value that approximates the trigonometric tangent of an angle, expressed in radians, that is specified by <argument-1> (a numeric literal, a numeric data item or an arithmetic expression).
If you need to determine the tangent of an angle measured in degrees, you first need to convert that angle to radians as follows:
COMPUTE radians = ( degrees / 180 ) * FUNCTION PI
For example, the angles 0, 90, 180, and 360 degrees correspond to 0, PI/2, PI, and 2PI radians, respectively.
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. TESTTAN. *> SAMPLE PROGRAM
DATA DIVISION.
WORKING-STORAGE SECTION.
*> 01 wRESULT PIC s999999999999999v999.
01 wRESULT COMP-2.
01 wRadians PIC s999v999999999999999999999999999999.
PROCEDURE DIVISION.
compute wRadians rounded = ( 0 / 180 * FUNCTION PI)
move FUNCTION TAN(wRadians) to wRESULT
DISPLAY 'a. TAN 0: ' wRESULT
display 'b. TAN 0: ' FUNCTION TAN(wRadians)
display 'c. TAN 0: ' FUNCTION TAN ( 0 / 180 * FUNCTION PI)
compute wRadians rounded = (45 / 180 * FUNCTION PI)
move FUNCTION TAN(wRadians) to wRESULT
DISPLAY 'a. TAN 45: ' wRESULT
display 'b. TAN 45: ' FUNCTION TAN(wRadians)
display 'c. TAN 45: ' FUNCTION TAN ( 45 / 180 * FUNCTION PI)
compute wRadians rounded = (90 / 180 * FUNCTION PI)
move FUNCTION TAN(wRadians) to wRESULT
DISPLAY 'a. TAN 90: ' wRESULT
display 'b. TAN 90: ' FUNCTION TAN(wRadians)
display 'c. TAN 90: ' FUNCTION TAN ( 90 / 180 * FUNCTION PI)
ACCEPT OMITTED STOP RUN.
Output:
a. TAN 0: 0
b. TAN 0: 000000000
c. TAN 0: 000000000
a. TAN 45: 1
b. TAN 45: 1.0000000000000000000000000000002485579014153003124470895125277347
3660697484597003341590013965842
c. TAN 45: 000000001
a. TAN 90: -4.023207447061442E+30
b. TAN 90: -4023207447061442195699607700869.101702063500460378079285495421043
5558831701825450723174164966234
c. TAN 90: -06821240868962529064771258430010129008736353403959449607967148259
65664542783567559961486449405413
TEST-DATE-YYYYMMDD
TEST-DATE-YYYYMMDD Function Syntax
=======================================================================
TEST-DATE-YYYYMMDD (date)
~~~~~~~~~~~~~~~~~~
=======================================================================
This function determines if the supplied <date> argument (a numeric integer data item or literal) is a valid date. A valid date is one of the form yyyymmdd in the range 1601/01/01 to 9999/12/31, with no more than the expected maximum number of days in the month, accounting for leap year. If the <date> is valid, a 0 value is returned. If it isn’t, a value of 1, 2 or 3 is returned signalling the problem lies with the year, month or day, respectively.
TEST-DAY-YYYYDDD
TEST-DAY-YYYYDDD Function Syntax
=======================================================================
TEST-DAY-YYYYDDD (date)
~~~~~~~~~~~~~~~~
=======================================================================
This function determines if the supplied <date> (a numeric integer data item or literal) is a valid date. A valid date is one of the form yyyyddd in the range 1601001 to 9999365. Leap year is accounted for in determining the maximum number of days in a year. If the date is valid, a 0 value is returned. If it isn’t, a value of 1 or 2 is returned signalling the problem lies with the year or day, respectively.
TEST-FORMATTED-DATETIME
TEST-FORMATTED-DATETIME Function Syntax
=======================================================================
TEST-FORMATTED-DATETIME ( argument-1, argument-2 )
~~~~~~~~~~~~~~~~~~~~~~~
=======================================================================
TEST-FORMATTED-DATETIME tests whether a date literal representing a date, a time or a combined date and time is valid according to the specified format.
<argument-1> must a literal of type alphanumeric, UTF-8 or national, that contains a date, time or combined data time format. See Date and Time formats for details.
<argument-2> must be a data item of the same type as <argument-1>.
Returned value: if no format or range problems occur during evaluation of <argument-2> according to the format in <argument-1>, the returned value is zero. Otherwise the returned value is the ordinal character position at which the first error in <argument-2> was detected.
Example: using following arguments will generates a ret.value of 5, as the fifth char of argument-2 ("4") contains an incorrect value for the first digit of the month representation.
FUNCTION TEST-FORMATTED-DATETIME("YYYYMMDD", "20124523")
TEST-NUMVAL
TEST-NUMVAL Function Syntax
=======================================================================
TEST-NUMVAL (string)
~~~~~~~~~~~
=======================================================================
The TEST-NUMVAL function evaluates <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) for being appropriate for use as the <string> argument to a NUMVAL (see NUMVAL) function, returning to a integer a zero value if it is appropriate otherwise if one or more characters are in error, the position of the first character in error or the length of the field plus one for other cases such as all spaces. Note that these errors include but are not limited to: argument (<string>) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string ‘+.’.
TEST-NUMVAL-C
TEST-NUMVAL-C Function Syntax
=======================================================================
TEST-NUMVAL-C (string[,symbol])
~~~~~~~~~~~~~
=======================================================================
This function evaluates <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) for being appropriate for use as the <string> argument to a NUMVAL-C (see NUMVAL-C) function, returning to a integer a zero value if it is appropriate otherwise if one or more characters are in error, the position of the first character in error or the length of the field plus one for other cases such as all spaces. Note that these errors include but are not limited to: argument (<string>) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string ‘+.’. The optional <symbol> argument serves the same function — and has the same default and possible values — as the corresponding argument of the NUMVAL-C function.
TEST-NUMVAL-F
TEST-NUMVAL-F Function Syntax
=======================================================================
TEST-NUMVAL-F (string)
~~~~~~~~~~~~~
=======================================================================
This function evaluates <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal) for being appropriate for use as the <string> argument to a NUMVAL-F (see NUMVAL-F) function, returning to a integer a zero value if it is appropriate otherwise if one or more characters are in error, the position of the first character in error or the length of the field plus one for other cases such as all spaces. Note that these errors include but are not limited to: argument (string) is zero length, contains only spaces or contains valid characters but is incomplete, such as the string ‘+.’.
TRIM
TRIM Function Syntax
=======================================================================
TRIM(string [, LEADING|TRAILING ])
~~~~ ~~~~~~~ ~~~~~~~~
=======================================================================
This function removes LEADING or TRAILING spaces from <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal).
The second argument is specified as a keyword, not a quoted string or identifier. If no second argument is specified, both leading and trailing spaces will be removed. The case (upper, lower or mixed) of this argument is irrelevant.
UPPER-CASE
UPPER-CASE Function Syntax
=======================================================================
UPPER-CASE(string)
~~~~~~~~~~
=======================================================================
This function returns the value of <string> (a group item, USAGE DISPLAY elementary item or alphanumeric literal), converted entirely to upper case.
What constitutes a “letter” (or upper/lower case too, for that manner) may be influenced through the use of a CHARACTER CLASSIFICATION (see OBJECT-COMPUTER).
VARIANCE
VARIANCE Function Syntax
=======================================================================
VARIANCE(number-1 [, number-2 ]...)
~~~~~~~~
=======================================================================
This function returns the statistical variance of the specified list of <number-n> arguments (these may be numeric data items or numeric literals).
WHEN-COMPILED
WHEN-COMPILED Function Syntax
=======================================================================
WHEN-COMPILED
~~~~~~~~~~~~~
=======================================================================
The WHEN-COMPILED intrinsic function, not to be confused with the WHEN-COMPILED (see Special Registers) special register, returns the date and time the program was compiled, in ASCII.
Since this function has no arguments, no parenthesis should be specified.
Unlike the WHEN-COMPILED special register, which has an ASCII value of the compilation date/time in the format mm/dd/yyhh.mm.ss, the WHEN-COMPILED intrinsic function returns the compilation date/time as an ASCII string in the format yyyymmddhhmmssnnooooo, where yyyymmdd is the date, hhmmss is the time, nn is the hundredths of a second component of the compilation time, if available (or 00 if it isn’t) and ooooo is the time zone offset from GMT.
If the -fintrinsics=WHEN-COMPILED switch or -fintrinsics=ALL switch is specified to the compiler or the REPOSITORY (see REPOSITORY) paragraph specifies either FUNCTION WHEN-COMPILED INTRINSIC or FUNCTION ALL INTRINSIC, then references to WHEN-COMPILED (without a leading FUNCTION keyword will always reference this intrinsic function and there will be no way to access the WHEN-COMPILED special register.
YEAR-TO-YYYY
YEAR-TO-YYYY Function Syntax
=======================================================================
YEAR-TO-YYYY(yy [, yy-cutoff [, yy-execution-time ]])
~~~~~~~~~~~~
=======================================================================
YEAR-TO-YYYY converts <yy> — a two-digit year — to a four-digit format (yyyy).
The optional <yy-cutoff> argument is the year cutoff used to delineate centuries; if <yy> meets or exceeds this cutoff value, the result will be 19yy; if <yy> is less than the cutoff, the result will be 20yy. The default cutoff value if no second argument is given will be 50.
The optional <yy-execution-time> argument (a numeric integer data item or literal) The default execution time value if no third argument is given will be now equivalent to specifying (FUNCTION NUMVAL (FUNCTION CURRENT-DATE (1:4))).
All arguments must be numeric data items or numeric literals.
BOOLEAN-OF-INTEGER
BOOLEAN-OF-INTEGER Function Syntax
=======================================================================
BOOLEAN-OF-INTEGER(argument-1 argument-2)
~~~~~~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
BOOLEAN-OF-INTEGER returns a boolean item of usage bit representing the binary value of <argument-1>. <argument-2> specifies the length of the boolean data item that is returned.
<argument-1> must be a positive integer.
<argument-2> must be a positive non-zero integer
Returned value is a boolean item of usage bit that has the same bit configuration as the binary representation of the value of <argument-1>, where the rightmost boolean position is the low-order binary digit. The boolean value is zero-filled or truncated on the left, if necessary, in order to return a boolean item whose length is specified by <argument-2> in terms of boolean positions.
CHAR-NATIONAL
CHAR-NATIONAL Function Syntax
=======================================================================
CHAR-NATIONAL(argument-1)
~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
CHAR-NATIONAL returns a one character value that is a character in the national program collating sequence having the ordinal position equal to the value of the argument.
<argument-1> must be a integer and greater than zero and less than or equal to the number of positions in the national program collating sequence.
DISPLAY-OF
DISPLAY-OF Function Syntax
=======================================================================
DISPLAY-OF(argument-1 [ argument-2] )
~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
DISPLAY-OF returns a character string containing the alphabetic coded character set representation of the national characters in the argument.
<argument-1> must be of class national.
<argument-2> must be a of class alphabetic or alphanumeric and is one character position in length. It specifies an alphanumeric substitution character for use in conversion of national characters for which there is no corresponding alphanumeric character.
A character string is returned with each national character of <argument-1> converted to its corresponding alphanumeric character representation, if any.
If <argument-2> is specified, the alphanumeric substitution character is returned for each national character in <argument-1> that has no corresponding alphanumeric character representation.
If <argument-2> is un-specified, and <argument-1> contains a national character for which there is no corresponding alphanumeric character representation, a substitution character is used as the corresponding alphanumeric character and the EC-DATA-CONVERSION exception condition is set. The length of the returned value is the number of character positions of usage display required to hold the converted argument and depends on the number of characters contained in <argument-1>.
EXCEPTION-FILE-N
EXCEPTION-FILE-N Function Syntax
=======================================================================
EXCEPTION-FILE-N
~~~~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
EXCEPTION-FILE-N returns a national character string that is the I/O status value and file-name of the file connector, if any, associated with the last exception status.
The value returned has a length that is based on its contents and the contents are as follows: If the last exception status is not an EC-I-O exception condition, the returned value is two national zeros.
The returned value is two national spaces when the last exception status indicates an EC-I-O exception condition that originates from one of the following statements:
a
RAISEstatement.an
EXITor aGOBACKstatement with aRAISINGphrase that specifies anEC-I-Oexception-name.
Otherwise the returned value is a character string that is as long as is needed to contain the I-O status value and the filename. The first two characters are the I-O status value in national characters. The succeeding characters contain the file-name exactly as specified in the SELECT clause converted at runtime to the runtime national character set.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
EXCEPTION-LOCATION-N
EXCEPTION-LOCATION-N Function Syntax
=======================================================================
EXCEPTION-LOCATION-N
~~~~~~~~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
EXCEPTION-LOCATION-N returns an national character string containing exception information from the most-recently failing statement. The information is returned to a 1023 character string in one of the following formats, depending on the nature of the failure:
primary-entry-point-name; paragraph OF section; statement-number
primary-entry-point-name; section; statement-number
primary-entry-point-name; paragraph; statement-number
primary-entry-point-name; statement-number
Since this function has no arguments, no parenthesis should be specified.
The program must be compiled with the -debug switch, -ftraceall switch or -g switch for this function to return any meaningful information.
The documentation of the CBL_ERROR_PROC built-in system subroutine (see CBL_ERROR_PROC) built-in subroutine illustrates the use of this function.
INTEGER-OF-BOOLEAN
INTEGER-OF-BOOLEAN Function Syntax
=======================================================================
INTEGER-OF-BOOLEAN(argument-1)
~~~~~~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
INTEGER-OF-BOOLEAN returns the numeric value of the boolean string in <argument-1> which is class boolean.
Returned value as <argument-1> is assigned to a temporary boolean data item of usage bit described with the same number of boolean positions.
The unsigned binary value represented by the same bit configuration as the bit configuration of that temporary boolean data item is determined.
Note: Binary representation is a mathematical concept. It is not required that this representation be the same as a COBOL representation.
NATIONAL-OF
NATIONAL-OF Function Syntax
=======================================================================
NATIONAL-OF(argument-1 [argument-2] )
~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
NATIONAL-OF returns a character string containing the national character representation of the characters in the argument which must be of class boolean.
A character string is returned with each alphanumeric character in <argument-1> converted to its corresponding national coded character set representation.
If <argument-2> is specified, each character in <argument-1> that has no corresponding national representation is converted to the substitution character specified by <argument-2>.
If <argument-2> is unspecified and <argument-1> contains an alphanumeric character for which there is no corresponding national character representation, a substitution character is used as the corresponding national character and the EC-DATA-CONVERSION exception condition is set to exist.
The length of the returned value is the number of character positions of usage national required to hold the converted argument and depends on the number of characters contained in <argument-1>.
STANDARD-COMPARE
STANDARD-COMPARE Function Syntax
=======================================================================
STANDARD-COMPARE(argument-1 argument-2 [ordering-name-1] [argument-4] )
~~~~~~~~~~~~~~~~
This option is not yet implemented.
The included file NEWS will indicate when it is.
=======================================================================
STANDARD-COMPARE returns a character indicating the result of comparing <argument-1> as a alphanumeric and <argument-2> using a cultural ordering table.
<argument-1> shall be of class alphabetic, alphanumeric, or national.
<argument-2> shall be of class alphabetic, alphanumeric, or national.
<argument-1> and <argument-2> may be of different classes.
Neither <argument-1> nor <argument-2> shall be a zero-length literal.
<ordering-name-1>, if specified, shall be associated with a cultural ordering table in the
ORDER TABLEclause of theSPECIAL-NAMESparagraph. It identifies the ordering table to be used for the comparison. If <ordering-name-1> is not specified, the default ordering table ‘ISO14651_2010_TABLE1’ described in Appendix A of ISO/IEC 14651:2011 shall be used.<argument-4>, if specified, shall be a positive nonzero integer.
Returned values:
If <argument-4> is unspecified, the highest level defined in the ordering table is used for the comparison.
If the cultural ordering table is not available on the processor, or the specified ordering level is not available, or the level number specified by <argument-4> is not defined in the ordering table, the
EC-ORDER-NOT-SUPPORTEDexception condition is set.If the arguments are of different classes, and one is national, the other argument is converted to class national for purposes of comparison.
For purposes of comparison, trailing spaces are truncated from the operands except that an operand consisting of all spaces is truncated to a single space.
<argument-1> and <argument-2> are compared in accordance with the ordering table and ordering level being used. Note: This comparison is culturally sensitive and the default ordering table is acceptable for most cultures. It is not necessarily a character-by-character comparison and not necessarily a case-sensitive comparison. In order to use this function, users should understand the types of comparisons specified by ISO/IEC 14651:2D11 and the ordering tables in use for their installation.
The returned value is:
- ‘
=’ -
the arguments compare equal,
- ‘
<’ -
<argument-1> is less than <argument-2>,
- ‘
>’ -
<argument-1> is greater than <argument-2>.
- ‘
The length of the returned value is 1.
Built-In System Subroutines
There are a number of built-in system subroutines included with GnuCOBOL.
Generally, these routines are intended to match those available in Micro Focus COBOL, ACUCOBOL and directly for GnuCOBOL.
It is recommended to change the CBL_OC routines to CBL_GC for forward compatibility as at some point they will be removed as they are a hangover from Open Cobol.
Prefix explanation:
C$-
–>
ACU CBL_-
–>
MF CBL_GC_-
(For backwards compatibility some routines are also available as
CBL_OC_as well): but these wonderful extensions are only available with GnuCOBOL.
These routines, all executed via their upper-case names via the CALL statement (see CALL), are capable of performing the following functions:
Changing the current directory
Copying files
Creating a directory
Creating, Opening, Closing, Reading and Writing byte-stream files
Deleting directories (folders)
Deleting files
Determining how many arguments were passed to a subroutine
Getting file information (size and last-modification date/time)
Getting the length (in bytes) of an argument passed to a subroutine
Justifying a field left-, right- or center-aligned
Moving files (a destructive “copy”)
Putting the program “to sleep”, specifying the sleep time in seconds
Putting the program “to sleep”, specifying the sleep time in nanoseconds; Caveat: although you’ll express the time in nanoseconds, Windows systems will only be able to sleep at a millisecond granularity
Retrieving information about the currently-executing program
Submitting a command to the shell environment appropriate for the version of GnuCOBOL you are using for execution
Early versions of Micro Focus COBOL allowed programmers to access various runtime library routines by using a single two-digit hexadecimal number as the entry-point name. These were known as call-by-number routines. Over time, Micro Focus COBOL evolved, replacing most of the call-by-number routines with ones accessible using a more conventional call-by-name technique.
Most of the call-by-number routines have evolved into even more powerful call-by-name routines, many of which are supported by GnuCOBOL.
Some of the original call-by-number routines never evolved call-by-name equivalents; GnuCOBOL supports some of these routines. See all currently used in Appendix’s C and D.
GnuCOBOL provides and supports built-in system subroutines of following categories:
+-------------------------------------------------------------------------------------+
| Directory Routines |
+-------------------------------------------------------------------------------------+
| CBL_GET_CURRENT_DIR | Retrieves the fully-qualified pathname of current directory |
| CBL_CREATE_DIR | With this routine you may create a new directory |
| C$MAKEDIR | Same as CBL_CREATE_DIR |
| CBL_CHANGE_DIR | Makes a directory-path the current directory |
| C$CHDIR | Same as CBL_CHANGE_DIR |
| CBL_DELETE_DIR | This subroutine deletes an empty directory |
+-------------------------------------------------------------------------------------+
| File Routines |
+-------------------------------------------------------------------------------------+
| CBL_CHECK_FILE_EXIST| Retrieve the size, date, time modified of a file |
| C$FILEINFO | Same as CBL_CHECK_FILE_EXIST |
| CBL_COPY_FILE | Copy source file to destination file |
| C$COPY | Same as CBL_COPY_FILE |
| CBL_RENAME_FILE | Use this subroutine to rename a file |
| CBL_DELETE_FILE | Deletes the file specified |
| C$DELETE | Same as CBL_DELETE_FILE |
| CBL_FLUSH_FILE | This routine is non-functional in GnuCOBOL |
+-------------------------------------------------------------------------------------+
| Byte-stream File Routines |
+-------------------------------------------------------------------------------------+
| CBL_CREATE_FILE | Creates new file & opens it for output as a byte-stream file |
| CBL_OPEN_FILE | Opens an existing file for use as a byte-stream file |
| CBL_READ FILE | Reads n bytes from the byte-stream file |
| CBL_WRITE_FILE | Writes n bytes of data to the byte-stream file |
| CBL_CLOSE_FILE | Closes a byte stream file previously opened |
+-------------------------------------------------------------------------------------+
| Virtual Heap Routines |
+-------------------------------------------------------------------------------------+
| CBL_OPEN_VFILE | Opens a "virtual file" (heap) |
| CBL_WRITE_VFILE | Writes bytes to heap; offset 4 byte binary |
| CBL_READ_VFILE | Reads bytes from heap; offset 4 byte binary |
| CBL_CLOSE_VFILE | Closes the heap handle |
| CBL_GC_OPEN_VFILE64 | Opens a "virtual file" (heap) |
| CBL_GC_WRITE_VFILE64| Writes bytes to heap; offset 8 byte binary |
| CBL_GC_READ_VFILE64 | Reads bytes from heap; offset 8 byte binary |
| CBL_GC_CLOSE_VFILE64| Closes the heap handle |
+-------------------------------------------------------------------------------------+
| Text Routines |
+-------------------------------------------------------------------------------------+
| CBL_TOLOWER | Convert the first "n" characters of a data-item to lower-case |
| C$TOLOWER | Same as CBL_TOLOWER |
| CBL_TOUPPER | Convert the first "n" characters of a data-item to upper-case |
| C$TOUPPER | Same as CBL_TOUPPER |
| C$JUSTIFY | Use to left, right or center justify a data-item |
+-------------------------------------------------------------------------------------+
| Logic Operator Routines |
+-------------------------------------------------------------------------------------+
| CBL_AND | Performs a bit-by-bit logical AND between 2 data items |
| CBL_OR | Performs a bit-by-bit logical OR between 2 data items |
| CBL_NOR | Performs the NEGATION of a bit-by-bit logical OR b/data items |
| CBL_XOR | Performs a bit-by-bit logical XOR between 2 data items |
| CBL_EQ | Performs a bit-by-bit logical comparison between 2 data items |
| CBL_NOT | "Flips" the bits of item changing 0 bits to 1, & 1 bits to 0 |
| CBL_IMP | Performs a bit-by-bit logical IMPLIES between 2 data items |
| CBL_NIMP | Performs the NEGATION of a bit-by-bit logical IMPLIES |
+-------------------------------------------------------------------------------------+
+-------------------------------------------------------------------------------------+
| Screen Routines |
+-------------------------------------------------------------------------------------+
| CBL_GET_SCR_SIZE | Retrieve the current console screen size |
| CBL_GC_SET_SCR_SIZE | Set the current console screen size |
| CBL_GC_SCR_DUMP | Writes the current contents of the screen to a dump file |
| CBL_GC_SCR_RESTORE | Restore the screen from a dump file |
| CBL_GC_WINDOW | Implement multiple TUI (Text User Interface) window support |
| CBL_GET_CSR_POS | Retrieve the current cursor location on the screen |
| CBL_SET_CSR_POS | Set the current cursor position on the screen |
| CBL_ALARM_SOUND | Create a noise (a beep) using the internal speaker |
| CBL_BELL_SOUND | Same as CBL_ALARM_SOUND |
| X"E5" | Same as CBL_ALARM_SOUND |
| X"E4" | Use X"E4" to clear the screen |
+-------------------------------------------------------------------------------------+
| Keyboard Routines |
+-------------------------------------------------------------------------------------+
| CBL_READ_KBD_CHAR | Waits until a character is typed from the terminal and then |
| | read it with no echo |
+-------------------------------------------------------------------------------------+
| Bit-packing Routines |
+-------------------------------------------------------------------------------------+
| X"F4" | Packs rightmost bit from eight 1-byte items into |
| | corresponding bit positions of a single-byte data item |
| X"F5" | Unpacks bit of the single-byte data item into the rightmost |
| | bit of corresponding eight 1-byte items |
+-------------------------------------------------------------------------------------+
| Run-unit Handling Routines |
+-------------------------------------------------------------------------------------+
| C$CALLEDBY | Returns the program name that called the executing program |
| C$NARG | Returns the numb.of parameters passed to the current program |
| C$PARAMSIZE | Returns the numb.of bytes passed by caller for a parameter |
| CBL_GC_GETOPT | Adapts the option parser "getopt" to GnuCOBOL |
| CBL_OC_GETOPT | Same as CBL_GC_GETOPT but deprecated |
| CBL_ERROR_PROC | Registers a general error-handling routine |
| CBL_EXIT_PROC | Registers a general exit-handling routine |
| CBL_GC_HOSTED | Provides access to some C hosted variables |
| CBL_OC_HOSTED | Same as CBL_GC_HOSTED but deprecated |
| CBL_GC_NANOSLEEP | Puts the program to sleep for specified number of nanoseconds |
| CBL_OC_NANOSLEEP | Same as CBL_GC_NANOSLEEP but deprecated |
| C$SLEEP | Puts the program to sleep for specified number of seconds |
| CBL_GC_PRINTABLE | Converts the contents of a data-item to printable characters |
| C$PRINTABLE | Same as CBL_GC_PRINTABLE |
| CBL_GC_WAITPID | Allows you to wait until another system process ended |
| C$GETPID | Return the PID (process ID) of the executing GnuCOBOL program |
| CBL_GC_FORK | Allows you to fork the current COBOL process to a new one |
| CBL_RUNTIME_ERROR | exiting the runtime as a hard error |
+-------------------------------------------------------------------------------------+
| Operating System Routines |
+-------------------------------------------------------------------------------------+
| SYSTEM | Submits command to a command shell for execution |
+-------------------------------------------------------------------------------------+
+-------------------------------------------------------------------------------------+
| Miscellaneous Routines |
+------------------------- -----------------------------------------------------------+
| EXTFH | Callable File Handler, is primarily an API for file I-O |
| X"91" | Routine capable of providing a wide variety of functions |
| Function code 11 | Sets all eight of the COBOL switches (0 - 7) |
| Function code 12 | Reads all eight of the COBOL switches (0 - 7) |
| Function code 13 | Allow access to runtime switches A - Z (11 - 36) - UNFINISHED |
| Function code 14 | Allow access to runtime switches A - Z (11 - 36) - UNFINISHED |
| Function code 16 | Retrieves the number of arguments passed to the program |
| Function code 35 | Prepare for DOS EXEC call [ EXEC call "like DOS 4B call ] |
"in testing": EXEC call "like DOS 4B call"
| | - - - UNFINISHED - - - |
| |
>> GnuCOBOL 4 additionally provides (as the FD related file io settings a 4+ feature):
| Function code 46-47| Prepare for file specific settings LS NULLS - Enable / Disable|
| Function code 48-49| Prepare for file specific settings LS TABS - Enable / Disable |
>> The following two are NOT supported within GnuCobol at this time :
| Function code 15 | Checks to see if a program exists |
| | |
| Function code 69 | Prepare for directory search |
+-------------------------------------------------------------------------------------+
Note UNFINISHED means just that do not use unless you are helping to test GC v3.3++
The following sections describe the various built-in subroutines. All subroutine arguments are mandatory except where explicitly noted to the contrary. Any subroutine returning a value to the RETURN-CODE special register (see Special Registers) could utilize the RETURNING clause on the CALL statement to return the result back to the full-word binary data item of your choice.
C$CALLEDBY
C$CALLEDBY Built-In Subroutine Syntax
=======================================================================
CALL "C$CALLEDBY" USING prog-name-area
~~~~ ~~~~~
=======================================================================
This routine returns the name of the program that called the currently-executing program. The program name will be returned, left-justified and space filled, in <prog-name-area> argument, which should be a PIC X elementary item or a group item. If <prog-name-area> is too small to receive the entire program name, the program name value will be truncated (on the right) to fit.
The RETURN-CODE special register (see Special Registers) will be set to one of the following values:
| -1 | An error occurred. The <prog-name-area> contents will be unchanged. |
| 0 | The program calling C$CALLEDBY was not called by any other program (in other words, it is a main program). The <prog-name-area> contents will be set entirely to spaces. |
| 1 | The program calling C$CALLEDBY was indeed called by another program, and that program’s name has been saved in <prog-name-area>. |
C$CHDIR
C$CHDIR Built-In Subroutine Syntax
=======================================================================
CALL "C$CHDIR" USING directory-path, result
~~~~ ~~~~~
=======================================================================
This routine makes <directory-path> (an alphanumeric literal or identifier) the current directory.
The return code of the operation is returned both in the <result> argument (any non-edited numeric identifier) as well as in the RETURN-CODE special register (see Special Registers). The return code of the operation will be either 0=Success or 128=failure.
The directory change remains in effect until the program terminates (in which the original current directory at the time the program was started will be automatically restored) or until another C$CHDIR or a CBL_CHANGE_DIR built-in system subroutine (see CBL_CHANGE_DIR) is executed.
C$COPY
C$COPY Built-In Subroutine Syntax
=======================================================================
CALL "C$COPY" USING src-file-path, dest-file-path, 0
~~~~ ~~~~~
=======================================================================
Use this subroutine to copy file <src-file-path> to <dest-file-path> as if it were done via the cp (Unix/OSX) or COPY (Windows) command.
Both file path arguments may be alphanumeric literals or identifiers.
The third argument is required, but is unused.
If the attempt to copy the file fails (for example, it or the destination directory doesn’t exist), the RETURN-CODE special register (see Special Registers) will be set to 128; on successful completion it will be set to 0.
C$DELETE
C$DELETE Built-In Subroutine Syntax
=======================================================================
CALL "C$DELETE" USING file-path, 0
~~~~ ~~~~~
=======================================================================
This routine deletes the file specified by the <file-path> argument (an alphanumeric literal or identifier) just as if that were done using the rm (Unix/OSX) or ERASE (Windows) command.
The second argument is required, but is unused.
If the attempt to delete the file fails (for example, it doesn’t exist), the RETURN-CODE special register (see Special Registers) will be set to 128; on successful completion it will be set to 0.
See also CBL_DELETE_FILE routine and the DELETE FILE statement of PROCEDURE DIVISION.
C$FILEINFO
C$FILEINFO Built-In Subroutine Syntax
=======================================================================
CALL "C$FILEINFO" USING file-path, file-info
~~~~ ~~~~~
=======================================================================
With this routine you may retrieve the size of the file specified as the <file-path> argument (an alphanumeric literal or identifier) and the date/time that file was last modified. File size information may not be available in the particular GnuCOBOL build / Operating System combination you are using and may therefore always be returned as zero. The information is returned to the <file-info> argument, which is defined as the following 16-byte area:
01 File-Info.
05 File-Size-In-Bytes PIC 9(18) COMP.
05 Mod-YYYYMMDD PIC 9(8) COMP. *> Modification Date
05 Mod-HHMMSS00 PIC 9(8) COMP. *> Modification Time
The last two decimal digits in the modification time will always be 00.
If the subroutine is successful, a value of 0 will be returned in the RETURN-CODE special register (see Special Registers). Failure to retrieve the needed statistics on the file will cause a RETURN-CODE special register value of 35 to be passed back. Supplying less than two arguments will generate a 128 RETURN-CODE special register value.
C$GETPID
C$GETPID Built-In Subroutine Syntax
=======================================================================
CALL "C$GETPID"
~~~~
=======================================================================
Use this subroutine to return the PID (process ID) of the executing GnuCOBOL program. The PID value is returned into the RETURN-CODE special register (see Special Registers).
There are no arguments to this routine.
The Process ID (PID) is a unique number that identifies each process / program running on Linux or windows.
To find the PID with Linux do ps -la if you are the usr running it or ps aux | grep app-name.
For windows a bit more complex - isn’t it always - To find the PID of an application on Windows:
a. Task Manager: Open Task Manager by pressing CTRL + SHIFT + ESC. Select the application whose PID you want to find and click Details. The PID of the application will be displayed in the PID column.
b. Command Prompt: Open Command Prompt and type “tasklist”. The PID of all running applications will be displayed in the PID column.
c. PowerShell: Open PowerShell and type “Get-Process”. The PID of all running applications will be displayed in the Id column.
C$JUSTIFY
C$JUSTIFY Built-In Subroutine Syntax
=======================================================================
CALL "C$JUSTIFY" USING data-item, "justification-type"
~~~~ ~~~~~
=======================================================================
Use C$JUSTIFY to left, right or center-justify an alphabetic, alphanumeric or numeric edited data-item. The optional <justification-type> argument indicates the type of the justification to be performed. Its value is interpreted as follows:
- ‘
C’ -
the value will be centered
- ‘
R’ -
the value will be right-justified, space-filled to the left
- ‘
L’ -
the value will be left-justified, space-filled to the right
If it begins with anything else, or is absent, it will be treated as if it is present and begins with a capital ‘R’
C$MAKEDIR
C$MAKEDIR Built-In Subroutine Syntax
=======================================================================
CALL "C$MAKEDIR" USING dir-path
~~~~ ~~~~~
=======================================================================
With this routine you may create a new directory — the name of which is supplied as the <dir-path> argument (an alphanumeric literal or identifier).
Only the lowest-level directory (last) in the specified path can be created — all others must already exist. This subroutine will not behave as a mkdir -p (Unix) or mkdir /p (Windows).
The RETURN-CODE special register (see Special Registers) will be set to the return code of the operation; the value will be either 0=Success or 128=failure.
C$NARG
C$NARG Built-In Subroutine Syntax
=======================================================================
CALL "C$NARG" USING arg-count-result
~~~~ ~~~~~
=======================================================================
This subroutine returns the number of arguments passed to the program that calls it back to in the numeric field <arg-count-result>. When called from within a user-defined function, a value of one (1) is returned if any arguments were passed to the function or a zero (0) otherwise.
When called from a main program, the returned value will always be 0.
C$PARAMSIZE
C$PARAMSIZE Built-In Subroutine Syntax
=======================================================================
CALL "C$PARAMSIZE" USING argument-number
~~~~ ~~~~~
=======================================================================
This subroutine returns the size (in bytes) of the subroutine argument supplied using the <argument-number> parameter (a numeric literal or data item).
The size is returned in the RETURN-CODE special register (see Special Registers).
If the specified argument does not exist, or an invalid argument number is specified, a value of 0 is returned.
C$PRINTABLE
C$PRINTABLE Built-In Subroutine Syntax
=======================================================================
CALL "C$PRINTABLE" USING data-item [ , char ]
~~~~ ~~~~~
=======================================================================
The C$PRINTABLE subroutine converts the contents of the data-item specified as the first argument to printable characters. Those characters that are deemed printable (as defined by the character set used by <data-item>) will remain unchanged, while those that are NOT printable will be converted to the character specified as the second argument.
If no <char> argument is provided, a period (‘.’) will be used.
Note: CBL_GC_PRINTABLE replaces this although it is currently still supported for legacy reasons.
C$SLEEP
C$SLEEP Built-In Subroutine Syntax
=======================================================================
CALL "C$SLEEP" USING seconds-to-sleep
~~~~ ~~~~~
=======================================================================
C$SLEEP puts the program to sleep for the specified number of seconds and/or fractions of a second. The <seconds-to-sleep> argument may be a numeric literal or data item.
Sleep times less than 1 will be interpreted as 0, subject to the speed of the CPU and the O/S (Operating System) used, as well as the timing of the generated C code, which will immediately returns control to the calling program without any sleep delay.
When using a variable argument defined as 9(n)v9(m) where n is maximum seconds in 7 days, i.e., (60 x 60 x 24 x 7) = 604,800 (seconds) and m is at a point too fast for the CPU and O/S. In practice m should be 2 for a hundredth of a second but actual testing against the target CPU would be needed.
The maximum time can be adjusted by the define MAX_SLEEP_TIME during compilation of the compiler [and no I do not know where it is in the codebase] e.g.:
/* maximum sleep time in seconds, currently 7 days */
#define MAX_SLEEP_TIME 3600*24*7
Extract from a working program :-
This routine completes a process on newly arrived files at 30 minutes past each hour
When complete sleeps for 60 minutes - time past nn:30:
*> In WS: Computed last finished, based on Sleep secs
*> changes depend on UPDATE run & finished time.
01 WS-Cycle-Process-Data.
03 WS-Sleep-Minutes pic 9(5) value 60. *>Default 60 = 1 hour
03 WS-Sleep-Seconds pic 9(5) value zeros.
03 WS-Cycle-Start pic 99 value 30. *> time to run past the hour
03 WS-Cycle-Secs pic s9(6) value zeros.
03 WS-Tmp-Secs1 pic s9(6) value zero.
03 WS-Rerun-Cycles-No pic s999 value -1.
03 WS-Tmp-Sleep pic 9(6) value zero.
01 Current-Date-And-Time.
03 CDT-DateTime. *> 16
05 CDT-Year pic 9(4).
05 CDT-Month pic 9(2). *> 01-12
05 CDT-Day pic 9(2). *> 01-31
05 CDT-Hour pic 9(2). *> 00-23
05 CDT-Minutes pic 9(2). *> 00-59
05 CDT-Seconds pic 9(2). *> 00-59
05 CDT-Huns-Of-Secs pic 9(2). *> 00-99
03 filler redefines CDT-DateTime.
05 CDT-DDT pic 9(8).
05 filler pic x(8).
03 filler.
05 CDT-GMT-Diff-HH pic S9(2) sign leading separate.
05 CDT-GMT-Diff-MMM pic 9(2). *> 00 or 30
*> In Procedure Division: Now if set to sleep do so,
*> for normal processing multi (24) times per day
*> First use minutes & at end convert to secs
move FUNCTION Current-Date to Current-Date-And-Time
compute WS-Tmp-Secs1 = WS-Cycle-Secs - ((CDT-Minutes * 60) + CDT-Seconds)
if WS-Tmp-Secs1 is negative
or WS-Tmp-Secs1 = zero
add WS-Sleep-Seconds to WS-Tmp-Secs1
end-if
move WS-Tmp-Secs1 to WS-Tmp-Sleep
move spaces to Log-Msg
string "Time Now "
CDT-Hour ":" CDT-Minutes ":" CDT-Seconds
space "Sleep time " WS-Tmp-Sleep into Log-Msg
display FUNCTION TRIM (Log-Msg) at 1601 with erase eol
*> Code skipped
*>
*> Allow ESCape to terminate after NEXT update cycle but time will be out 1 sec
accept Accept-Reply at line WS-Lines col 42 TIME-OUT 1
if Cob-Crt-Status = Cob-Scr-Esc
go to AA040-EOJ end-if
call "C$SLEEP" using WS-Tmp-Sleep
go to AA032-Test-Update
C$TOLOWER
C$TOLOWER Built-In Subroutine Syntax
=======================================================================
CALL "C$TOLOWER" USING data-item, BY VALUE convert-length
~~~~ ~~~~~ ~~~~~
=======================================================================
This routine will converts the <convert-length> (a numeric literal or data item) leading characters of <data-item> (an alphanumeric identifier) to lower-case.
The <convert-length> argument must be specified BY VALUE (see CALL). Any characters in <data-item> after the <convert-length> point will remain unchanged.
If <convert-length> is negative or zero, no conversion will be performed.
C$TOUPPER
C$TOUPPER Built-In Subroutine Syntax
=======================================================================
CALL "C$TOUPPER" USING data-item, BY VALUE convert-length
~~~~ ~~~~~ ~~~~~
=======================================================================
This routine will converts the <convert-length> (a numeric literal or data item) leading characters of <data-item> (an alphanumeric identifier) to upper-case.
The <convert-length> argument must be specified BY VALUE (see CALL). Any characters in <data-item> after the <convert-length> point will remain unchanged.
If <convert-length> is negative or zero, no conversion will be performed.
CBL_ALARM_SOUND
CBL_ALARM_SOUND Built-In Subroutine Syntax
=======================================================================
CALL "CBL_ALARM_SOUND"
~~~~
=======================================================================
This routine will create a noise (a beep) using the internal speaker if present. Works the same as function CBL_BELL_SOUND and X"E5".
CBL_BELL_SOUND
CBL_BELL_SOUND Built-In Subroutine Syntax
=======================================================================
CALL "CBL_BELL_SOUND"
~~~~
=======================================================================
This routine works the same as function CBL_ALARM_SOUND and X"E5".
CBL_AND
CBL_AND Built-In Subroutine Syntax
=======================================================================
CALL "CBL_AND" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs a bit-by-bit logical AND operation between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the AND process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_CHANGE_DIR
CBL_CHANGE_DIR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_CHANGE_DIR" USING directory-path
~~~~ ~~~~~
=======================================================================
This routine makes <directory-path> (an alphanumeric literal or identifier) the current directory.
The return code of the operation, which will be either 0=Success or 128=failure, is returned in the RETURN-CODE special register (see Special Registers).
The directory change remains in effect until the program terminates (in which the original current directory at the time the program was started will be automatically restored) or until another CBL_CHANGE_DIR or a C$CHDIR built-in system subroutine (see C$CHDIR) is executed.
CBL_CHECK_FILE_EXIST
CBL_CHECK_FILE_EXIST Built-In Subroutine Syntax
=======================================================================
CALL "CBL_CHECK_FILE_EXIST" USING file-path, file-info
~~~~ ~~~~~
=======================================================================
With this routine you may retrieve the size of the file specified as the <file-path> argument (an alphanumeric literal or identifier) and the date/time that file was last MODIFIED. File size information may not be available in the particular GnuCOBOL build / Operating System combination you are using and may therefore always be returned as zero.
The information is returned to the <file-info> argument, which is defined as the following 16-byte area:
01 file-info.
05 File-Size-In-Bytes PIC 9(18) COMP.
05 Mod-DD PIC 9(2) COMP. *> Modification Date
05 Mod-MO PIC 9(2) COMP.
05 Mod-YYYY PIC 9(4) COMP.
05 Mod-HH PIC 9(2) COMP. *> Modification Time
05 Mod-MM PIC 9(2) COMP.
05 Mod-SS PIC 9(2) COMP.
05 FILLER PIC 9(2) COMP. *> Always 00
If the subroutine is successful, a value of 0 will be returned in the RETURN-CODE special register (see Special Registers). Failure to retrieve the needed statistics on the file will cause a RETURN-CODE special register value of 35 to be passed back. Supplying less than two arguments will generate a 128 RETURN-CODE special register value.
CBL_CLOSE_FILE
CBL_CLOSE_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_CLOSE_FILE" USING file-handle
~~~~ ~~~~~
=======================================================================
The CBL_CLOSE_FILE subroutine closes a byte stream file previously opened by either the CBL_OPEN_FILE built-in system subroutine (see CBL_OPEN_FILE) or CBL_CREATE_FILE built-in system subroutine (see CBL_CREATE_FILE) subroutines.
If the file defined by the <file-handle> argument (a PIC X(4) USAGE COMP-X data item) was opened for output, an implicit CBL_FLUSH_FILE built-in system subroutine (see CBL_FLUSH_FILE) will be performed before the file is closed.
If the subroutine is successful, a value of 0 will be returned in the RETURN-CODE special register (see Special Registers). Failure will cause a RETURN-CODE special register value of -1 to be passed back.
An example of the use of OPEN, CLOSE, READ etc., can be found in Contribs program printcbl.cbl which is basically also in cobxref.cbl as program 3.
CBL_COPY_FILE
CBL_COPY_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_COPY_FILE" USING src-file-path, dest-file-path
~~~~ ~~~~~
=======================================================================
Use this subroutine to copy file <src-file-path> to <dest-file-path> as if it were done via the cp (Unix/OSX) or COPY (Windows) command.
Both arguments may be alphanumeric literals or identifiers.
If the attempt to copy the file fails (for example, it or the destination directory doesn’t exist), the RETURN-CODE special register (see Special Registers) will be set to 128; on successful completion it will be set to 0.
CBL_CREATE_DIR
CBL_CREATE_DIR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_CREATE_DIR" USING dir-path
~~~~ ~~~~~
=======================================================================
With this routine you may create a new directory — the name of which is supplied as the <dir-path> argument (an alphanumeric literal or identifier).
Only the lowest-level directory (last) in the specified path can be created — all others must already exist. This subroutine will not behave as a mkdir -p (Unix) or mkdir /p (Windows).
The RETURN-CODE special register (see Special Registers) will be set to the return code of the operation; The value will be either 0 = Success or 128 = failure.
CBL_CREATE_FILE
CBL_CREATE_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_CREATE_FILE" USING file-path, 2, 0, 0, file-handle
~~~~ ~~~~~
=======================================================================
The CBL_CREATE_FILE subroutine creates the new file specified using the file-path argument and opens it for output as a byte-stream file usable by CBL_WRITE_FILE built-in system subroutine (see CBL_WRITE_FILE).
Arguments 2, 3 and 4 should be coded as the constant values shown. CBL_CREATE_FILE is actually a special-case of the CBL_OPEN_FILE built-in system subroutine (see CBL_OPEN_FILE) routine — see that routine for a description of the meanings of arguments 2, 3 and 4.
A <file-handle> (PIC X(4) USAGE COMP-X) will be returned, for use on any subsequent CBL_WRITE_FILE built-in system subroutine (see CBL_WRITE_FILE) or CBL_CLOSE_FILE built-in system subroutine (see CBL_CLOSE_FILE) calls.
The success or failure of the subroutine will be reported back in the RETURN-CODE special register (see Special Registers), with a value of -1 indicating an invalid argument and a value of 0 indicating success.
CBL_DELETE_DIR
CBL_DELETE_DIR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_DELETE_DIR" USING dir-path
~~~~ ~~~~~
=======================================================================
This subroutine deletes an empty directory.
The only argument — <dir-path> (an alphanumeric literal or identifier) — is the name of the directory to be deleted.
Only the lowest-level directory (last) in the specified path will be deleted, and that directory must be empty to be deleted.
The RETURN-CODE special register (see Special Registers) will be set to the return code of the operation; the value will be either 0=Success or 128=failure.
CBL_DELETE_FILE
CBL_DELETE_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_DELETE_FILE" USING file-path
~~~~ ~~~~~
=======================================================================
This routine deletes the file specified by the <file-path> argument (an alphanumeric literal or identifier) just as if that were done using the rm (Unix/OSX) or ERASE (Windows) command.
If the attempt to delete the file fails (for example, it doesn’t exist), the RETURN-CODE special register (see Special Registers) will be set to 128; on successful completion it will be set to 0.
See also C$DELETE routine and the DELETE FILE statement of PROCEDURE DIVISION.
CBL_EQ
CBL_EQ Built-In Subroutine Syntax
=======================================================================
CALL "CBL_EQ" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs a bit-by-bit comparison between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the EQ process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_ERROR_PROC
CBL_ERROR_PROC Built-In Subroutine Syntax
=======================================================================
CALL "CBL_ERROR_PROC" USING function, program-pointer
~~~~ ~~~~~
=======================================================================
This routine registers a general error-handling routine.
The <function> argument must be a numeric literal or a 32-bit binary data item (USAGE BINARY-LONG, for example) with a value of 0 or 1. A value of 0 means that you will be registering (“installing”) an error procedure while a value of 1 indicates you’re de-registering (“uninstalling”) a previously-installed error procedure.
The <program-pointer> must be a data item with a USAGE (see USAGE) of PROGRAM-POINTER containing the address of your error procedure. This item should be given a value using the SET Program-Pointer statement (see SET Program-Pointer). If the error procedure is written in GnuCOBOL, it must be a subroutine, not a user-defined function.
A success (0) or failure (non-0) result will be passed back in the RETURN-CODE special register (see Special Registers).
A custom error procedure will trigger when a runtime error condition is encountered. An error procedure may be registered by a main program or a subprogram, but regardless of from where it was registered, it applies to the overall program compilation group and will trigger when a runtime error occurs anywhere in the executable program. If the error procedure was defined by a subprogram, that program must be loaded at the time the error procedure is executed.
An error procedure may be used to take whatever actions might be warranted to display additional information or to gracefully close down work in progress, but it cannot prevent the termination of program execution; should the error procedure not issue its own STOP RUN, control will return back to the standard error routine when the error procedure exits.
The code within the handler will be executed and — once the handler issues a return, if it was written in C, or an EXIT PROGRAM statement (see EXIT) or GOBACK statement, if it was written in GnuCOBOL, the system-standard error handling routine will be executed.
Only one user-defined error procedure may be in effect at any time.
The following is a sample GnuCOBOL program that registers an error procedure. The output of that program is shown as well. As as you can see, the error handler’s messages appear followed by the standard GnuCOBOL message.
1. IDENTIFICATION DIVISION.
2. PROGRAM-ID. DemoERRPROC.
3. ENVIRONMENT DIVISION.
4. DATA DIVISION.
5. WORKING-STORAGE SECTION.
6. 01 Err-Proc-Address USAGE PROGRAM-POINTER.
7. PROCEDURE DIVISION.
8. S1.
9. DISPLAY 'Program is starting'
10. SET Err-Proc-Address TO ENTRY 'ErrProc'
11. CALL 'CBL_ERROR_PROC' USING 0, Err-Proc-Address
12. CALL 'Tilt' *> THIS DOESN'T EXIST!!!!
13. DISPLAY 'Program is stopping'
14. STOP RUN
15. .
16. END PROGRAM DemoERRPROC.
17.
18. IDENTIFICATION DIVISION.
19. PROGRAM-ID. ErrProc.
20. PROCEDURE DIVISION.
21. 000-Main.
22. DISPLAY 'Error: ' FUNCTION EXCEPTION-LOCATION
23. DISPLAY ' ' FUNCTION EXCEPTION-STATEMENT
24. DISPLAY ' ' FUNCTION EXCEPTION-FILE
25. DISPLAY ' ' FUNCTION EXCEPTION-STATUS
26. DISPLAY '*** Returning to Standard Error Routine ***'
27. EXIT PROGRAM
28. .
29. END PROGRAM ErrProc.
When executed, this sample program generates the following console output.
E:\Programs\Demos>demoerrproc
Program is starting
Error: DemoERRPROC; S1; 12
CALL
00
EC-PROGRAM-NOT-FOUND
*** Returning to Standard Error Routine ***
DEMOERRPROC.cbl: 27: libcob: Cannot find module 'Tilt'
E:\Programs\Demos>
CBL_EXIT_PROC
CBL_EXIT_PROC Built-In Subroutine Syntax
=======================================================================
CALL "CBL_EXIT_PROC" USING function, program-pointer
~~~~ ~~~~~
=======================================================================
This routine registers a general exit-handling routine.
The <function> argument must be a numeric literal or a 32-bit binary data item (USAGE BINARY-LONG, for example) with a value of 0 or 1. A value of 0 means that you will be registering (“installing”) an exit procedure while a value of 1 indicates you’re deregistering (“uninstalling”) a previously-installed exit procedure.
The <program-pointer> must be a data item with a USAGE (see USAGE) of PROGRAM-POINTER containing the address of your exit procedure.
A success (0) or failure (non-0) result will be passed back in the RETURN-CODE special register (see Special Registers).
An exit procedure, once registered, will trigger whenever a STOP RUN statement (see STOP) or a GOBACK statement (see GOBACK) is executed anywhere in the program. The exit procedure may execute whatever code is desired to undertake an orderly shut down of the program. Once the exit procedure terminates by executing an EXIT PROGRAM statement (see EXIT) or a GOBACK statement, the system-standard program termination routine will be executed.
Only one user-defined exit procedure may be in effect at any time.
The following is a sample GnuCOBOL program that registers an exit procedure. The output of that program is shown as well.
IDENTIFICATION DIVISION.
PROGRAM-ID. demoexitproc.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Exit-Proc-Address USAGE PROGRAM-POINTER.
PROCEDURE DIVISION.
000-Register-Exit-Proc.
SET Exit-Proc-Address TO ENTRY "ExitProc"
CALL "CBL_EXIT_PROC" USING 0, Exit-Proc-Address
IF RETURN-CODE NOT = 0
DISPLAY 'Error: Could not register Exit Procedure'
END-IF.
099-Now-Test-Exit-Proc.
DISPLAY 'Executing a STOP RUN...' END-DISPLAY
GOBACK.
END PROGRAM demoexitproc.
IDENTIFICATION DIVISION.
PROGRAM-ID. ExitProc.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Display-Date PIC XXXX/XX/XX.
01 Display-Time PIC XX/XX/XX.
01 Now PIC X(8).
01 Today PIC X(8).
PROCEDURE DIVISION.
000-Main.
DISPLAY '*** STOP RUN has been executed ***'
ACCEPT Today FROM DATE YYYYMMDD
ACCEPT Now FROM TIME
MOVE Today TO Display-Date
MOVE Now TO Display-Time
INSPECT Display-Time REPLACING ALL '/' BY ':'
DISPLAY '*** ' Display-Date ' ' Display-Time ' ***'
GOBACK.
END PROGRAM ExitProc.
CBL_FLUSH_FILE
CBL_FLUSH_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_FLUSH_FILE" USING file-handle
~~~~ ~~~~~
=======================================================================
In Micro Focus COBOL, calling this subroutine flushes any as-yet unwritten buffers for the (output) file whose file-handle is specified as the argument to disk.
This routine is non-functional in GnuCOBOL. It exists only to provide compatibility for applications that may have been developed for Micro Focus COBOL.
CBL_GC_FORK
CBL_GC_FORK Built-In Subroute Syntax
=======================================================================
CALL "CBL_GC_FORK" USING Child-PID
~~~~ ~~~~~
=======================================================================
CBL_GC_FORK allows you to fork the current COBOL process to a new one.
The current content of the process’s storage (including LOCAL-STORAGE) will be identical, any file handles get invalid in the new process, positions and file and record locks are only available to the original process. This system routine is not available on Windows (exception: GCC on Cygwin).
Parameters: none. Returns: pid (the child process gets ‘0’ returned, the calling process gets the pid of the created child). Negative values are returned for system dependant error codes and -1 if the function is not available on the current system.
IDENTIFICATION DIVISION.
PROGRAM-ID. prog.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 CHILD-PID PIC S9(9) BINARY.
01 WAIT-STS PIC S9(9) BINARY.
PROCEDURE DIVISION.
CALL "CBL_GC_FORK" RETURNING CHILD-PID END-CALL
EVALUATE TRUE
WHEN CHILD-PID = ZERO
PERFORM CHILD-CODE
WHEN CHILD-PID > ZERO
PERFORM PARENT-CODE
WHEN CHILD-PID = -1
DISPLAY 'CBL_GC_FORK is not available on the current'
' system!'
PERFORM CHILD-CODE
MOVE 0 TO CHILD-PID
PERFORM PARENT-CODE
WHEN OTHER
MULTIPLY -1 BY CHILD-PID END-MULTIPLY
DISPLAY 'CBL_GC_FORK returned system error: ' CHILD-PID
END-EVALUATE
STOP RUN.
CHILD-CODE.
CALL "C$SLEEP" USING 1 END-CALL
DISPLAY "Hello, I am the child"
MOVE 2 TO RETURN-CODE.
PARENT-CODE.
DISPLAY "Hello, I am the parent"
CALL "CBL_GC_WAITPID" USING CHILD-PID RETURNING WAIT-STS
MOVE 0 TO RETURN-CODE
EVALUATE TRUE
WHEN WAIT-STS >= 0
DISPLAY 'Child ended with status: ' WAIT-STS
WHEN WAIT-STS = -1
DISPLAY 'CBL_GC_WAITPID is not available on the '
'current system!'
WHEN WAIT-STS < -1
MULTIPLY -1 BY WAIT-STS END-MULTIPLY
DISPLAY 'CBL_GC_WAITPID returned system error: ' WAIT-STS
END-EVALUATE.
CBL_GC_GETOPT
CBL_GC_GETOPT Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_GETOPT" USING BY REFERENCE SHORTOPTIONS LONGOPTIONS LONGIND
~~~~ ~~~~~ BY VALUE LONG-ONLY
BY REFERENCE RETURN-CHAR OPT-VAL
=======================================================================
CBL_GC_GETOPT adapts the well-known option parser, getopt, to GnuCOBOL.
The usage of this system routine is described by the following example.
IDENTIFICATION DIVISION.
PROGRAM-ID. PROG.
DATA DIVISION.
WORKING-STORAGE SECTION.
78 SHORTOPTIONS VALUE "jkl".
01 LONGOPTIONS.
05 OPTIONRECORD OCCURS 2 TIMES.
10 OPTIONNAME PIC X(25).
10 HAS-VALUE PIC 9.
10 VALPOINT POINTER VALUE NULL.
10 RETURN-VALUE PIC X(4).
01 LONGIND PIC 99.
01 LONG-ONLY PIC 9 VALUE 1.
01 RETURN-CHAR PIC X(4).
01 OPT-VAL PIC X(10).
01 COUNTER PIC 9 VALUE 0.
We first need to define the necessary fields for getopt’s shortoptions, longoptions, longoption index (longind), long-only-option (long-only) and also the fields for return values return-char and opt-val (arbitrary size with trimming, see return codes).
The shortoptions are written down as an alphanumeric field (i.e., a string with arbitrary size) as follows:
"ab:c::d"
This means we want getopt to look for short options named ‘a’, ‘b’, ‘c’ or ‘d’, require an option value for ‘b’, and accept an optional one for ‘c’.
The longoptions are defined as a table of records with oname, has-value, valpoint and val.1
oname defines the name of a longoption. has-value defines if an option value is demanded (has-val = 1), optional (has-val = 2) or not required (has-val = 0).
valpoint is a pointer used to specify an address to save getopt's return value to. The pointer is optional. If it is NULL, getopt returns a value as usual. If you use the pointer it has to point to a PIC X(4) field. The field val is a PIC X(4) character which is returned if the longoption was recognized.
The longoption structure is immutable! You can only vary the number of records.
Now we have the tools to run CBL_GC_GETOPT within the procedure division.
PROCEDURE DIVISION.
MOVE "version" to OPTIONNAME (1).
MOVE 0 TO HAS-VALUE (1).
MOVE ‘V’ TO RETURN-VALUE (1).
MOVE "verbose" TO OPTIONNAME (2).
MOVE 0 TO HAS-VALUE (2).
MOVE ‘V’ TO RETURN-VALUE (2).
PERFORM WITH TEST AFTER UNTIL RETURN-CODE = -1
CALL 'CBL_GC_GETOPT' USING
BY REFERENCE SHORTOPTIONS LONGOPTIONS LONGIND
BY VALUE LONG-ONLY
BY REFERENCE RETURN-CHAR OPT-VAL
END-CALL
DISPLAY RETURN-CHAR END-DISPLAY
DISPLAY OPT-VAL END-DISPLAY
END-PERFORM
STOP RUN.
The example shows how we initialize all parameters and call the routine until CBL_GC_GETOPT runs out of options and returns -1.
return-char might contain the following regular character if an option was recognized:
?-
undefined or ambiguous option
1-
non-option (only if first byte of so is ‘
-’) 0-
valpoint != NULLand we are writing the return value to the specified address -1-
no more options (or reach the first non-option if first byte of
shortoptionsis ‘+’)
The return-codes of CBL_GC_GETOPT are:
1-
a non-option (only if first byte of so is ‘
-’) 0-
valpoint != NULLand we are writing the return value to the specified address -1-
no more options (or reach the first non-option if first byte of
shortoptionsis ‘+’) 2-
truncated option value in
opt-val(becauseopt-valwas too small) 3-
a regular answer from
getopt
This routine replaces CBL_OC_GETOPT which is kept as a legacy item.
Note that the legacy name of this routine that starts with CBL_OC is deprecated, as is GETOPT but will still work. It is recommended that all library routines names starting with CBL_OC are replaced with CBL_GC to minimise issues.
CBL_GC_HOSTED
CBL_GC_HOSTED Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_HOSTED" USING ARG-1 ARG-2
~~~~ ~~~~~
=======================================================================
CBL_GC_HOSTED provides access to the following C hosted variables:
argc-
binary-long by value argv-
pointer to char ** stdin, stdout, stderr-
pointer errno-
giving address of
errnoin pointer tobinary-long, usebasedfor more
Direct access and conditional access to the following variables:
tzname-
pointer to pointer to array of two char pointers timezone-
C
long, will be seconds west of UTC daylight-
C
int, will be 1 during daylight savings
The system will need HAVE TIMEZONE defined for these to return anything meaningful. Attempts made when they are not available will return 1 from CBL GC HOSTED.
It returns 0 when match, 1 on failure, case matters as does length, "arg" won’t match.
The usage of this system routine is described by the following example.
IDENTIFICATION DIVISION.
PROGRAM-ID. HOSTED.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Argc BINARY-LONG.
01 Argv POINTER.
01 Stdin POINTER.
01 Stdout POINTER.
01 Stderr POINTER.
01 Errno POINTER.
01 Err BINARY-LONG BASED.
01 Domain FLOAT-LONG VALUE 3.0.
01 Tzname POINTER.
01 Tznames POINTER BASED.
05 Tzs POINTER OCCURS 2.
01 Timezone BINARY-LONG.
01 Daylight BINARY-SHORT.
*>
PROCEDURE DIVISION.
call "CBL_GC_HOSTED" using stdin "stdin"
display "stdin : " stdin
call "feof" using by value stdin
display "feof stdin : " return-code
call "CBL_GC_HOSTED" using stdout "stdout"
display "stdout : " stdout
call "fprintf" using by value stdout by content "Hello" & x"0a"
call "CBL_GC_HOSTED" using stderr "stderr"
display "stderr : " stderr
call "fprintf" using by value stderr by content "on err" & x"0a"
call "CBL_GC_HOSTED" using argc "argc"
display "argc : " argc
call "CBL_GC_HOSTED" using argv "argv"
display "argv : " argv
call "args" using by value argc argv
call "CBL_GC_HOSTED" using errno "errno"
display "&errno : " errno
set address of err to errno
display "errno : " err
call "acos" using by value domain
display "errno after acos(3.0): " err ", EDOM is 33"
call "CBL_GC_HOSTED" using argc "arg"
display "'arg' lookup : " return-code
call "CBL_GC_HOSTED" using null "argc"
display "null with argc : " return-code
display "argc is still : " argc
*> the following only returns zero if the system has HAVE_TIMEZONE set
call "CBL_GC_HOSTED" using daylight "daylight "
display "'timezone' lookup : " return-code
if return-code not = 0
display "system doesn't has timezone"
else
display "timezone is : " timezone
call "CBL_GC_HOSTED" using daylight "daylight "
display "'daylight' lookup : " return-code
display "daylight is : " daylight
set environment "TZ" to "PST8PDT"
call static "tzset" returning omitted on exception
continue end-call
call "CBL_GC_HOSTED" using tzname "tzname"
display "'tzname' lookup : " return-code
*> tzs(1) will point to z"PST" and tzs(2) to z"PDT"
if return-code equal 0 and tzname not equal null then
set address of tznames to tzname
if tzs(1) not equal null then
display "tzs #1 : " tzs(1)
end-if
if tzs(2) not equal null then
display "tzs #2 : " tzs(2)
end-if
end-if
end-if
goback.
end program HOSTED.
This routine replaces CBL_OC_HOSTED which is kept as a legacy item.
Note that the legacy name of this routine that starts with CBL_OC is deprecated, as is HOSTED but will still work. It is recommended that all library routines names starting with CBL_OC are replaced with CBL_GC to minimise issues.
CBL_GC_NANOSLEEP
CBL_GC_NANOSLEEP Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_NANOSLEEP" USING nanoseconds-to-sleep
~~~~ ~~~~~
=======================================================================
This subroutine puts the program to sleep for the specified number of nanoseconds.
The effective granularity of <nanoseconds-to-sleep> values will depend upon the granularity of the system clock your computer is using and the timing granularity of the operating system that computer is running.
For example, you will not expect to see any difference between values of 1, 100, 500 or 1000, but you should see a difference between values such as 250000000 and 500000000.
The <nanoseconds-to-sleep> argument is a numeric literal or data item.
There are one billion nanoseconds in a second, so if you wanted to put the program to sleep for 1/4 second you’d use a <nanoseconds-to-sleep> value of 250000000.
This routine replaces CBL_OC_NANOSLEEP which is kept as a legacy item.
Note that the legacy name of this routine starts with “CBL_OC” is deprecated, as is NANOSLEEP, but will still work. It is recommended that all library routines names starting with “CBL_OC” are replaced with “CBL_GC” to minimise issues.
CBL_GC_PRINTABLE
CBL_GC_PRINTABLE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_PRINTABLE" USING data-item [ , char ]
~~~~ ~~~~~
Note replaces C$PRINTABLE which is kept as a legacy item.
=======================================================================
The CBL_GC_PRINTABLE subroutine converts the contents of the data-item specified as the first argument to printable characters.
Those characters that are deemed printable (as defined by the character set used by <data-item>) will remain unchanged, while those that are not printable will be converted to the character specified as the second argument.
If no <char> argument is provided, a period (‘.’) will be used.
CBL_GC_SCR_DUMP
CBL_GC_SCR_DUMP Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_SCR_DUMP" USING file-name, return-code
~~~~ ~~~~~
=======================================================================
Use this subroutine to writes the current contents of the screen to the file named by file-name. This function prepares the file that will be used with the CBL_GC_SCR_RESTORE function.
The following is a sample GnuCOBOL program that shows how to use the DUMP and RESTORE routines.
>>SOURCE FORMAT IS FREE
REPLACE ==:BCOL:== BY ==with BACKGROUND-COLOR==
==:FCOL:== BY ==FOREGROUND-COLOR==.
IDENTIFICATION DIVISION.
program-id. SCRDUMPRESTORE.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Black constant as 00.
01 Green constant as 02.
01 wBco pic 9(02) value Green.
01 wFco pic 9(02) value Black.
01 wLin pic 99 value 05.
01 wCol pic 99 value 10.
01 wScreenName PIC X(256) value space.
01 wScrOk BINARY-LONG value zero.
01 wScrOk9 pic 99.
01 .
03 Bmess pic x(30) occurs 20 value space.
PROCEDURE DIVISION.
*> D I S P L A Y 1st S C R E E N
move Green to wBco move Black to wFco
move '111111111111111111111111111111' to Bmess(1)
move '>>>>>>>>>> MESSAGE 1 <<<<<<<<<' to Bmess(2)
move '111111111111111111111111111111' to Bmess(3)
move '111111111111111111111111111111' to Bmess(4)
move '111111111111111111111111111111' to Bmess(5)
move '111111111111111111111111111111' to Bmess(6)
move '------------------------------' to Bmess(7)
perform DisplayMessage thru DisplayMessageEx
display 'PRESS ENTER TO DUMP 1st SCREEN ' at line 01 col 01 :BCOL: 07 :FCOL: black
accept omitted
*> save 1st screen
move 'DUMPSCREEN.TMP' & x'00' to wScreenName
call 'CBL_GC_SCR_DUMP' using by reference wScreenName returning wScrOk end-call
display '1st SCREEN DUMPED - RETURN CODE IS: ' at line 01 col 01 :BCOL: 07 :FCOL: black
move wScrOk to wScrOk9
display wScrOk9 at line 01 col 41 :BCOL: 07 :FCOL: black
accept omitted
display 'PRESS ENTER TO DISPLAY 2nd SCREEN ' at line 01 col 01 :BCOL: 07 :FCOL: black
accept omitted
*> D I S P L A Y 2nd S C R E E N
DISPLAY ' ' AT 0101 WITH ERASE EOS
move 12 to wLin move 20 to wCol
move 04 to wBco move Black to wFco
move '+----------------------------+' to Bmess(1)
move '|2222222222222222222222222222|' to Bmess(2)
move '|2222222222222222222222222222|' to Bmess(3)
move '| MESSAGE 2 |' to Bmess(4)
move '|2222222222222222222222222222|' to Bmess(5)
move '|2222222222222222222222222222|' to Bmess(6)
move '+----------------------------+' to Bmess(7)
perform DisplayMessage thru DisplayMessageEx
display 'PRESS ENTER TO RESTORE 1st SCREEN ' at line 01 col 01 :BCOL: 07 :FCOL: black
accept omitted
*> restore 1st screen
call 'CBL_GC_SCR_RESTORE' using by reference wScreenName returning wScrOk end-call
CALL 'CBL_DELETE_FILE' USING wScreenName
display '1st SCREEN RESTORED - RETURN CODE IS: ' at line 01 col 01 :BCOL: 07 :FCOL: black
move wScrOk to wScrOk9
display wScrOk9 at line 01 col 41 :BCOL: 07 :FCOL: black
accept omitted
STOP RUN.
DisplayMessage.
display Bmess(1) at line wLin + 1 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(2) at line wLin + 2 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(3) at line wLin + 3 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(4) at line wLin + 4 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(5) at line wLin + 5 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(6) at line wLin + 6 col wCol :BCOL: wBco :FCOL: wFco
display Bmess(7) at line wLin + 7 col wCol :BCOL: wBco :FCOL: wFco
continue.
DisplayMessageEx. exit.
CBL_GC_SCR_RESTORE
CBL_GC_SCR_RESTORE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_SCR_RESTORE" USING file-name, return-code
~~~~ ~~~~~
=======================================================================
Use this subroutine to restore the screen to the way it looked in the dump file which must have been created using the CBL_GC_SCR_DUMP function.
CBL_GC_SET_SCR_SIZE
CBL_GC_SET_SCR_SIZE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_SET_SCR_SIZE" USING no-of-lines, no-of-cols
~~~~ ~~~~~
=======================================================================
Use this subroutine to set the current console screen size.
When the system is running in a windowed environment, this will be the sizing of the console window in which the program is executing. When the system is not running a windowing environment, the physical console screen attributes will be set. In environments such as a Windows console window, where the logical size of the window may far exceed that of the physical console window, the size set will be that for the physical console window.
The size data must be in binary form or any other numeric forms to be accepted.
The following are possibly typical <no-of-lines> and <no-of-columns> definitions:
01 NO-OF-LINES USAGE BINARY-CHAR UNSIGNED.
01 NO-OF-COLUMNS USAGE BINARY-CHAR UNSIGNED.
This system call will only work if the terminal program used is compatible for such operations and not all are.
CBL_GC_WAITPID
CBL_GC_WAITPID Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_WAITPID" USING ARG-1
~~~~ ~~~~~
RETURNING RET-STATUS
~~~~~~~~~
=======================================================================
CBL_GC_WAITPID allows you to wait until another system process ended.
Additionally you can check the process’s return code.
Parameters: none
Returns: function-status / child-status
Negative values are returned for system dependant error codes and -1 if the function is not available on the current system.
CALL "CBL_GC_WAITPID" USING CHILD-PID RETURNING WAIT-STS
MOVE 0 TO RETURN-CODE
DISPLAY 'CBL_GC_WAITPID ended with status: ' WAIT-STS
CBL_GC_WINDOW
CBL_GC_WINDOW Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_WINDOW" USING command parameters return-code
~~~~ ~~~~~
=======================================================================
CBL_GC_WINDOW is a new callable function which implement multiple TUI (Text User Interface) window support. It is available starting from GnuCOBOL 3.3. Also there is a new copy member used to call them, GCWINDOW.CPY.
The functionality to support multiple TUI windows on the terminal screen has been implemented by making use of the panel libraries which are part of both PDCURSES and NCURSES variants. Note that panels are NOT supported in X/OPEN CURSES. If panels are not supported then the functions implemented below will return a non-zero value in the COBOL RETURN-CODE. Also note that if called with a parameter of the wrong length it will return a non-zero value in the GnuCOBOL RETURN-CODE.
Panels are TUI windows with the added feature of depth, so they can be stacked on top of each other, and only the visible portions of each window will be displayed. Panels can be added, moved on the physical screen, moved to the top or bottom of the stack, made visible or not visible, and removed.
For the implementation of this in GnuCOBOL, none of the curses functions / data structures are directly exposed to COBOL programs.
If called with "L" (List) command, this will return an array containing informations about all of the windows created by the function. The order of the entries is their depth in the deck of windows. Note that the hidden windows will be present after all of the non hidden windows.
Note restriction about hidden windows, the only allowable functions on a hidden window are "V" (Show) or "D" (Delete). See error codes 40 and 42 below.
All of the functions require the WP-NUMBER to contain the number returned by the WP-NEW function. Note that the HIDDEN variable below is now bit switch in the WP-FLAGS field. It is required for the SHOW / HIDE functions. An example on how commands and parameters are settled follows.
*> CBL_GC_WINDOW ROUTINE
*>
*> for all commands excluding L use:
*> call "CBL_GC_WINDOW" using WP-COMMAND WP-PARMS WP-RETCODE
*> only for command L use:
*> call "CBL_GC_WINDOW" using WP-COMMAND WL-LIST WP-RETCODE
*>
*> COMMAND NUM START-L START-C LINS COLS FG BG FLAGS RETCODE
*> ---------- --- ------- ------- ---- ---- --- --- ------ -------
*> N NEW ret req req req req req req - ret
*> T TOP req - - - - - - - ret
*> B BOTTOM req - - - - - - - ret
*> D DELETE req - - - - - - - ret
*> M MOVE req req req - - - - - ret
*> I HIDE req - - - - - - - ret
*> V SHOW req - - - - - - - ret
*> G GET req ret ret ret ret ret ret ret ret
*> S SET req - - - - req req - ret
*> L LIST - ret ret ret ret ret ret ret ret
*> ---------- --- ------- ------- ---- ---- --- --- ------ --------
*> req= required, ret= returned
*> the window on TOP of the deck always has the focus
01 WP-COMMAND PIC X. *> command
88 WP-NEW VALUE 'N'.*> create new window on top of the deck
88 WP-TOP VALUE 'T'.*> put the window on top of the deck
88 WP-BOTTOM VALUE 'B'.*> put the window at bottom of the deck
88 WP-DELETE VALUE 'D'.*> delete window from the deck
88 WP-MOVE VALUE 'M'.*> move the window on screen
88 WP-HIDE VALUE 'I'.*> make the window invisible (hide it)
88 WP-SHOW VALUE 'V'.*> make visible a hidden window
88 WP-GET VALUE 'G'.*> get settings & attributes of a window
88 WP-SET VALUE 'S'.*> set video attributes of a window
88 WP-LIST VALUE 'L'.*> get window's list with settings/attributes
*> communication area to manage information about a single window
01 WP-PARMS.
03 WP-NUMBER BINARY-SHORT.
66 WP-HANDLE renames WP-NUMBER.
03 WP-SETTINGS.
05 WP-START-LINE BINARY-SHORT.
05 WP-START-COL BINARY-SHORT.
05 WP-LINES BINARY-SHORT.
05 WP-COLUMNS BINARY-SHORT.
03 WP-VIDEO-ATTRIBUTES.
05 WP-FG-COLOR BINARY-SHORT.
05 WP-BG-COLOR BINARY-SHORT.
05 WP-FLAGS BINARY-SHORT.
*> Optional flags for the windows
78 WP-FLAG-HIDDEN VALUE h'01'.
78 WP-FLAG-NOSCROLL VALUE h'02'.
78 WP-FLAG-NOWRAP VALUE h'04'.
*> communication area for information about list of windows
*> low value = end of window list
01 WL-LIST.
05 WL-WINDOW OCCURS 20 TIMES INDEXED BY WL-INDEX.
10 WL-DEPTH BINARY-SHORT.
10 WL-NUMBER BINARY-SHORT
66 WL-HANDLE renames WL-NUMBER.
10 WL-START-LINE BINARY-SHORT.
10 WL-START-COL BINARY-SHORT.
10 WL-LINES BINARY-SHORT.
10 WL-COLUMNS BINARY-SHORT.
10 WL-FG-COLOR BINARY-SHORT.
10 WL-BG-COLOR BINARY-SHORT.
10 WL-FLAGS BINARY-SHORT.
01 WP-RETCODE BINARY-INT.
88 WP-UNSUPPORTED VALUE -1.
88 WP-DISABLED VALUE -2.
88 WP-BAD-PARAMETER-LEN VALUE -8.
88 WP-OK VALUE 0.
88 WP-LINE-EXCEEDS-MAX VALUE 2.
88 WP-COL-EXCEEDS-MAX VALUE 4.
88 WP-WIN-LINES-EXCEEDS-MAX VALUE 6.
88 WP-WIN-COLS-EXCEEDS-MAX VALUE 7.
88 WP-INVALID-BG-COLOR VALUE 8.
88 WP-INVALID-FG-COLOR VALUE 9.
88 WP-WIN-NUMBER-INVALID VALUE 10.
88 WP-FG-BG-COLORS-ARE-SAME VALUE 11.
88 WP-NO-MORE-WINDOWS-LEFT VALUE 20.
88 WP-NEWWIN-FAILED VALUE 22.
88 WP-NEW-PANEL-FAILED VALUE 24.
88 WP-PAN-USRPTR-FAILED VALUE 26.
88 WP-WINDOW-NOT-FOUND VALUE 28.
88 WP-MOVE-WINDOW-FAILED VALUE 29.
88 WP-SHOW-WINDOW-FAILED VALUE 30.
88 WP-HIDE-WINDOW-FAILED VALUE 32.
88 WP-TOP-WINDOW-FAILED VALUE 34.
88 WP-BOTTOM-WINDOW-FAILED VALUE 35.
88 WP-DELETE-WINDOW-FAILED VALUE 36.
88 WP-DELETE-PANEL-FAILED VALUE 38.
88 WP-WINDOW-IS-HIDDEN VALUE 40.
88 WP-WINDOW-IS-NOT-HIDDEN VALUE 42.
88 WP-WINDOW-MODE-IS-INVALID VALUE 44.
Note that the following are bit masks for the WP-FLAGS field. To modify the values you will need to use the B-OR to turn a bit on. The B-XOR can be used to turn a bit off.
COMPUTE WP-FLAGS = WP-FLAGS B-OR WP-FLAG-HIDDEN turn bit on
COMPUTE WP-FLAGS = WP-FLAGS B-XOR WP-FLAG-HIDDEN turn bit off
CBL_GET_CSR_POS
CBL_GET_CSR_POS Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GET_CSR_POS" USING cursor-locn-buffer
~~~~ ~~~~~
=======================================================================
This subroutine will retrieve the current cursor location on the screen, returning a 2-byte value into the supplied <cursor-locn-buffer>. The first byte of <cursor-locn-buffer> will receive the current line (row) location while the second receives the current column location.
The returned location data will be in binary form, and will be based upon starting values of 0, meaning that if the cursor is located at line 15, column 12 at the time this routine is called, a value of (14,11) will be returned.
The following is a typical <cursor-locn-buffer> definition:
01 CURSOR-LOCN-BUFFER.
05 CURSOR-LINE USAGE BINARY-CHAR UNSIGNED.
05 CURSOR-COLUMN USAGE BINARY-CHAR UNSIGNED.
Values of 1 (Line) and 1 (column) will be returned if GnuCOBOL was not generated to include screen I/O.
CBL_GET_CURRENT_DIR
CBL_GET_CURRENT_DIR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GET_CURRENT_DIR" USING BY VALUE 0,
~~~~ ~~~~~ ~~~~~
BY VALUE length,
~~~~~
BY REFERENCE buffer
~~~~~~~~~
=======================================================================
This retrieves the fully-qualified pathname of the current directory, saving up to <length> characters of that name into <buffer>.
The first argument is unused, but must be specified. It must be specified BY VALUE (see CALL).
The <length> argument must be specified BY VALUE. The <buffer> argument must be specified BY REFERENCE.
The value specified for the <length> argument (a numeric literal or data item) should not exceed the actual length of <buffer> argument.
If the value specified for the <length> argument is LESS THAN the actual length of <buffer> argument, the current directory path will be left-justified and space filled within the first <length> bytes of <buffer> — any bytes in <buffer> after that point will be unchanged.
If the routine is successful, a value of 0 will be returned to the RETURN-CODE special register (see Special Registers). If the routine failed because of a problem with an argument (such as a negative or 0 length), a value of 128 will result. Finally, if the 1st argument value is anything but zero, the routine will fail with a 129 value.
CBL_GET_SCR_SIZE
CBL_GET_SCR_SIZE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GET_SCR_SIZE" USING no-of-lines, no-of-cols
~~~~ ~~~~~
=======================================================================
Use this subroutine to retrieve the current console screen size.
When the system is running in a windowed environment, this will be the sizing of the console window in which the program is executing. When the system is not running a windowing environment, the physical console screen attributes will be returned. In environments such as a Windows console window, where the logical size of the window may far exceed that of the physical console window, the size returned will be that of the physical console window. Two one-byte values will be returned — the first will be the current number of lines (rows) while the second will be the number of columns.
The returned size data will be in binary form.
The following are typical <no-of-lines> and <no-of-columns> definitions:
01 NO-OF-LINES USAGE BINARY-CHAR UNSIGNED.
01 NO-OF-COLUMNS USAGE BINARY-CHAR UNSIGNED.
GnuCOBOL run-time screen management must have been initialized prior to CALLing this routine in order to receive meaningful values. This means that a DISPLAY data-item statement (see DISPLAY data-item) or a ACCEPT data-item statement (see ACCEPT data-item) must have been executed prior to executing the CALL statement.
Zero values will be returned if the screen has not been initialized and values of 24 (lines) and 80 (columns) will be returned if GnuCOBOL was not generated to include screen I/O.
Maximum values for BINARY-CHAR is 255 and any excess to this will be wrong so if lines or columns exceed 255, results will not be valid.
CBL_IMP
CBL_IMP Built-In Subroutine Syntax
=======================================================================
CALL "CBL_IMP" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs a bit-by-bit logical implies process between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the IMP process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_NIMP
CBL_NIMP Built-In Subroutine Syntax
=======================================================================
CALL "CBL_NIMP" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs the negation of a bit-by-bit logical implies process between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the NIMP process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_NOR
CBL_NOR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_NOR" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs the negation of a bit-by-bit logical or’ process between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the NOR process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_NOT
CBL_NOT Built-In Subroutine Syntax
=======================================================================
CALL "CBL_NOT" USING item-1, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
This subroutine “flips” the left-most 8*<byte-length> bits of <item-1>, changing 0 bits to 1, and 1 bits to 0. The changes are made directly in <item-1>.
The <item-1> argument must be a data item. The length of <item-1> must be at least 8*<byte-length>.
The <byte-length> argument may be a numeric literal or data item, and must be passed using BY VALUE (see CALL).
Any bits in <item-1> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_OC_GETOPT
CBL_GC_GETOPT Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_GETOPT" USING BY REFERENCE SHORTOPTIONS LONGOPTIONS LONGIND
~~~~ ~~~~~ BY VALUE LONG-ONLY
BY REFERENCE RETURN-CHAR OPT-VAL
=======================================================================
Use function CBL_GC_GETOPT instead as redundant and will be removed.
CBL_OC_HOSTED
CBL_GC_HOSTED Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_HOSTED" USING ARG-1 ARG-2
~~~~ ~~~~~
=======================================================================
Use function CBL_GC_HOSTED instead as redundant and will be removed.
CBL_OC_NANOSLEEP
CBL_GC_NANOSLEEP Built-In Subroutine Syntax
=======================================================================
CALL "CBL_GC_NANOSLEEP" USING nanoseconds-to-sleep
~~~~ ~~~~~
=======================================================================
Use function CBL_GC_NANOSLEEP instead as redundant and will be removed.
CBL_OPEN_FILE
CBL_OPEN_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_OPEN_FILE" USING file-path, access-mode, 0, 0, handle
~~~~ ~~~~~
=======================================================================
This routine opens an existing file for use as a byte-stream file usable by CBL_WRITE_FILE or CBL_READ_FILE.
The <file-path> argument is an alphanumeric literal or data-item.
The <access-mode> argument is a numeric literal or data item with a PIC X USAGE COMP-X (or USAGE BINARY-CHAR) definition; it specifies how you wish to use the file, as follows:
1-
input (read-only)
2-
output (write-only)
3-
input and/or output
The third and fourth arguments would specify a locking mode and device specification, respectively, but they’re not implemented in GnuCOBOL (currently, at least) — just specify each as 0.
The final argument (<handle>) is a PIC X(4) USAGE COMP-X item that will receive the handle to the file. That handle is used on all other byte-stream functions to reference this specific file.
A RETURN-CODE special register (see Special Registers) value of -1 indicates an invalid argument, while a value of 0 indicates success. A value of 35 means the file does not exist.
An example of the use of OPEN, CLOSE, READ etc., can be found in Contribs program printcbl.cbl which is basically also in cobxref.cbl as program 3.
NOTE.
A byte-stream file opened in input-output mode (access-mode = 3) can be used with true dynamic access.
After creating a file with CBL_CREATE_FILE and closing it with CBL_CLOSE_FILE the file can be opened in input-output mode (access-mode = 3) for writing with CBL_WRITE_FILE and reading with CBL_READ_FILE in any kind of sequence with any offset and buffer length. The same definitions for offset, length, flags and buffer can be shared by these routines. For retrieving the file size a CBL_READ_FILE can be used with the read-flag set to 128. In this case the buffer is not filled, instead the file size is returned in the offset variable. This procedure can be used to append additional records to the file, addressing the space immediately after the last record.
To read from the file and fill the buffer with the content of the file from the given offset with the given length the read-flag has to be set to zero. Records can be written even outside the file boundary. In this case a CBL_WRITE_FILE will fill gaps in the file with the necessary number of hex 00 bytes. If the file is 100 byte long and the CBL_WRITE_FILE is executed with an offset of 120 the 20 bytes between offset 100 and 120 are filled with hex 00, after this the contents of the buffer are written in the given length. The gaps filled with hex 00 can be addressed like any other space in the file. Updates can be executed with CBL_READ_FILE and CBL_WRITE_FILE in input-output open-mode (access-mode = 3). The buffer can be altered and rewritten at the same position, as long as offset and length are not changed. The special register RETURN-CODE usually returns the known codes for error-evaluation in the COBOL file system, i.e. 35 for the attempt to open a non-existent file, zero for a successful operation, 30 for permanent i-o error, etc. Only exception is -1 which means one of the parameters is wrong.
Warning. The only problem encountered during read tests is the file system return code for EOF, code 10. Repeated CBL_READ_FILE in input-output mode (access-mode = 3) never returned any file error. Even if the offset of the read went far beyond the file boundary the RETURN-CODE was always zero. In input mode (access-mode = 1) the EOF condition was only returned on an empty file (length 0 bytes). It is good advice to use a counter or intercept the offset to work around this problem. Conclusion: with the exception of the EOF problem the byte-stream file routines can be used like the ones introduced once by Micro Focus.
CBL_OR
CBL_OR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_OR" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs a bit-by-bit logical or process between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the OR process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
CBL_READ_FILE
CBL_READ_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_READ_FILE" USING handle, offset, nbytes, flag, buffer
~~~~ ~~~~~
=======================================================================
This routine reads <nbytes> of data starting at byte number <offset> from the byte-stream file defined by <handle> into <buffer>.
The <handle> argument (PIC X(4) USAGE COMP-X) must have been populated by a prior call to CBL_OPEN_FILE built-in system subroutine (see CBL_OPEN_FILE).
The <offset> argument (PIC X(8) USAGE COMP-X) defines the location in the file of the first byte to be read. The first byte of a file is byte offset 0 and MUST be preset to zero for first use.
The <nbytes> argument (PIC X(4) USAGE COMP-X) specifies how many bytes (maximum) will be read. If the <flag> argument is specified as 128, the size of the file (in bytes) will be returned into the file offset argument (argument 2) upon completion. Not all operating system/GnuCOBOL environments may be able to retrieve file sizes in such cases, a value of zero will be returned. The only other valid value for flags is 0. This argument may be specified either as a numeric literal or as a PIC X USAGE COMP-X data item.
Upon completion, the RETURN-CODE special register (see Special Registers) will be set to 0 if the read was successful or to 10 if an "end-of-file" condition occurred. If a value of -1 is returned, a problem was identified with the subroutine arguments.
CBL_READ_KBD_CHAR
CBL_READ_KBD_CHAR Build-In Subroutine Syntax
=======================================================================
CALL "CBL_READ_KBD_CHAR" USING char RETURNING status-code.
~~~~ ~~~~~ ~~~~~~~~~
=======================================================================
Waits until a character is typed from the terminal and then read it with no echo.
Parameters: char PIC X. Receives the character that was typed, in ASCII.
status-code PIC XX COMP-5.
If RETURNING is not used the RETURN-CODE special register receives the status-code where zero is success and non-zero it is not.
[Above information taken from MF WB manual].
CBL_RENAME_FILE
CBL_RENAME_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_RENAME_FILE" USING old-file-path, new-file-path
~~~~ ~~~~~
=======================================================================
You may use this subroutine to rename a file.
The file specified by <old-file-path> will be “renamed” to the name specified as <new-file-path>. Each argument may be an alphanumeric literal or data item.
Despite what the name of this routine might make you believe, this routine is more than just a simple “rename” — it will actually move the file supplied as the 1st argument to the file specified as the 2nd argument. Think of it as a two-step sequence, first copying the <old-file-path> file to the <new-file-path> file and then a second step where the <old-file-path> is deleted.
If the attempt to move the file fails (for example, it doesn’t exist), the RETURN-CODE special register (see Special Registers) will be set to 128; on successful completion it will be set to 0.
CBL_RUNTIME_ERROR
CBL_RUNTIME_ERROR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_RUNTIME_ERROR" USING item-1 { error-message-string }
~~~~ ~~~~~ { literal-1 }
{ OMITTED }
~~~~~~~
=======================================================================
Support for exiting the runtime from COBOL as a hard error (including possible [core-]dump and stacktrace).
Used in hard, non-recoverable error cases, for example when you pre-catch runtime exceptions "that should never happen" yourself, or for example if an API/socket/whatever endpoint does not exist/is not reachable.
First parameter item-1 is a pic x(4) comp-5 data item which must be zero. It is ignored in GnuCOBOL (we may add abcode and reasoncode as well as cleanup into the current first parameter at some later date). In any case for now it is "reserved for future use".
Second parameter: an optional alphanumeric null-terminated error message to be outputted after a run-time message. The output leading to stderr, will be: libcob: prog.cob:12: error: Program abandoned at user request: Your error message here To produce no additional message, pass the reserved word OMITTED instead.
Depending on compile-time flags and runtime options you get the "common" abort handling (possibly creation of dump file, creation of core-dump, stop within GDB, stack-trace output, ...) and also error procedures registered with CBL_ERROR_PROC.
See also the "STOP ERROR" statement.
CBL_SET_CSR_POS
CBL_SET_CSR_POS Build-In Subroutine Syntax
=======================================================================
CALL "CBL_SET_CSR_POS" USING cursor-locn-buffer
~~~~ ~~~~~
=======================================================================
Set current cursor position on terminal.
This subroutine will set the cursor location on the screen, using a 2-byte value into the supplied <cursor-locn-buffer>. The first byte of <cursor-locn-buffer> is for the line (row) location while the second sets the column location.
The two byte data block must be in binary form, and will be based upon starting values of 0, meaning that if the routine is called with a value of (14,11) cursor will be located at line 15, column 12. The following is a typical <cursor-locn-buffer> definition:
01 CURSOR-LOCN-BUFFER.
05 CURSOR-LINE USAGE BINARY-CHAR UNSIGNED.
05 CURSOR-COLUMN USAGE BINARY-CHAR UNSIGNED.
CBL_TOLOWER
CBL_TOLOWER Built-In Subroutine Syntax
=======================================================================
CALL "CBL_TOLOWER" USING data-item, BY VALUE convert-length
~~~~ ~~~~~ ~~~~~
=======================================================================
This routine will convert the first <convert-length> (a numeric literal or data item) characters of <data-item> (an alpha-numeric identifier) to lower-case.
The <convert-length> argument must be specified BY VALUE (see CALL). It specifies how many (leading) characters in data-item will be converted — any characters after that will remain unchanged.
If <convert-length> is negative or zero, no conversion will be performed.
CBL_TOUPPER
CBL_TOUPPER Built-In Subroutine Syntax
=======================================================================
CALL "CBL_TOUPPER" USING data-item, BY VALUE convert-length
~~~~ ~~~~~ ~~~~~
=======================================================================
This routine will convert the first <convert-length> (a numeric literal or data item) characters of <data-item> (an alpha-numeric identifier) to upper-case.
The <convert-length> argument must be specified BY VALUE (see CALL). It specifies how many (leading) characters in data-item will be converted — any characters after that will remain unchanged.
If <convert-length> is negative or zero, no conversion will be performed.
CBL_virtual_heap_routines
CBL_VIRTUAL_HEAP_ROUTINES Built-In Subroutines Syntax
=======================================================================
CALL "CBL_OPEN_VFILE" USING heap-ID heap-status RETURNING status-code.
~~~~ ~~~~~ ~~~~~~~~~
CALL "CBL_CLOSE_VFILE" USING BY VALUE heap-ID RETURNING status-code.
~~~~ ~~~~~ ~~~~~ ~~~~~~~~~
CALL "CBL_WRITE_VFILE" USING BY VALUE heap-ID relative-addr data-len
~~~~ ~~~~~ ~~~~~
BY REFERENCE strings RETURNING stat-code.
~~~~~~~~~ ~~~~~~~~~
CALL "CBL_READ_VFILE" USING BY VALUE heap-ID relative-addr data-len
~~~~ ~~~~~ ~~~~~
BY REFERENCE strings RETURNING stat-code.
~~~~~~~~~ ~~~~~~~~~
=======================================================================
The VFILE functions provide functionality consistent with Microfocus / Fujitsu, but the heap is never paged to disk. The VFILE64 functions are a GnuCOBOL extension to allow for access beyond the 4 GB offset when using a 64 bit environment. They are available starting from GnuCOBOL 3.3.
CBL_OPEN_VFILE opens a "virtual file" (heap)
CBL_WRITE_VFILE writes bytes to heap; offset 4 byte binary
CBL_READ_VFILE reads bytes from heap; offset 4 byte binary
CBL_CLOSE_VFILE closes the heap handle
CBL_GC_OPEN_VFILE64 opens a "virtual file" (heap)
CBL_GC_WRITE_VFILE64 writes bytes to heap; offset 8 byte binary
CBL_GC_READ_VFILE64 reads bytes from heap; offset 8 byte binary
CBL_GC_CLOSE_VFILE64 closes the heap handle
01 heap-ID PIC 9(4) COMP-5.
01 heap-status PIC X(2). *> The area to store heap-status
01 relative-addr PIC 9(4) COMP-5. *> The relative address in a heap
01 data-len PIC 9(4) COMP-5. *> The length of data to be read or written.
01 strings PIC X(n). *> Area to store the read string or the string to be written
01 stat-code PIC S(4) COMP-5. *> 0: Successful, other than 0: Failure
CBL_WRITE_FILE
CBL_WRITE_FILE Built-In Subroutine Syntax
=======================================================================
CALL "CBL_WRITE_FILE" USING handle, offset, nbytes, 0, buffer
~~~~ ~~~~~
=======================================================================
This routine writes <nbytes> of data from <buffer> to the byte-stream file defined by <handle> starting at byte number <offset> within the file.
The <handle> argument (PIC X(4) USAGE COMP-X) must have been populated by a prior call to CBL_OPEN_FILE. The offset argument (PIC X(8) USAGE COMP-X) defines the location in the file of the first byte to be written to. The first byte of a file is byte offset 0.
The <nbytes> argument (PIC X(4) USAGE COMP-X) specifies how many bytes (maximum) will be written.
Currently, the only allowable value for the flags argument is 0. This argument may be specified either as a numeric literal or as a PIC X(1) USAGE COMP-X data item.
Upon completion, the RETURN-CODE special register (see Special Registers) will be set to 0 if the write was successful or to 30 if an I/O error condition occurred. If a value of -1 is returned, a problem was identified with the subroutine arguments.
CBL_XOR
CBL_XOR Built-In Subroutine Syntax
=======================================================================
CALL "CBL_XOR" USING item-1, item-2, BY VALUE byte-length
~~~~ ~~~~~ ~~~~~
=======================================================================
|
This subroutine performs a bit-by-bit logical exclusive or process between the left-most 8*<byte-length> corresponding bits of <item-1> and <item-2>, storing the resulting bit string into <item-2>. The truth table shown to the left documents the XOR process. The <item-1> argument may be an alphanumeric literal or a data item and <item-2> must be a data item. The length of both <item-1> and <item-2> must be at least 8*<byte-length>. |
The <byte-length> argument may be a numeric literal or data item, and must be specified using BY VALUE (see CALL).
Any bits in <item-2> after the 8*<byte-length> point will be unaffected.
A result of zero will be passed back in the RETURN-CODE special register (see Special Registers).
EXTFH
EXTFH Built-In Subroutine Syntax
=======================================================================
CALL "EXTFH" USING opcode fcd
~~~~ ~~~~~
=======================================================================
The Callable File Handler (EXTFH), is primarily an API for file I-O and a kind of an industry standard.
It can be used to access to GnuCOBOL files by some other programming languages (like C, Visual Basic, Python ...) on several platforms.
It also allows to use GnuCOBOL LIBCOB’s fileio routines from other compilers (AcuCobol, MicroFocus, IBM Cobol ...) and vice versa (which of course needs a license). This can also help during migration phases.
The EXTFH API also provides features such as: Record locking, Data compression, New Index creation, Relative Byte Address, ...
You can also write your own file handler and run it in place of EXTFH, when it conforms to the call interface defined in this chapter.
The Callable File Handler handles all file organizations: sequential, line sequential, relative and indexed. The file operations performed by EXTFH fit into the following categories: Open files, Read and Write records, Move through records, Delete records, File and records locking, Unlocking records, Close files.
GnuCOBOL EXTFH file handling include support a callable EXTFH interface also provided by several compilers including Micro Focus The GnuCOBOL external file handler can be directly invoked from COBOL too, using CALL "EXTFH"
To have the compiled program call yourfh() for file I/O use: cobc -fcallfh=yourfh
In turn yourfh() may call EXTFH() to use I/O functions from GnuCOBOL.
Support for the EXTFH includes support for FH--FCD and FH--KEYDEF.
Some sample use of EXTFH.
a. Write a GnuCOBOL program that accepts as parameters: file type (sequential, relative indexed etc ...), number and length of keys, both the primary and any alternative keys.
This GnuCOBOL program, always the same, will be able to create various types of files (sequential, relative, indexed ) with a primary key that can be 5 bytes or 20 or 30 bytes long, with a record length of 100 bytes or 1000 bytes etc, etc, .. simply by accepting parameters with one or many ACCEPT statements ... with as an example an open output and a close.
b. Allow a Microfocus COBOL (or AcuCOBOL or RM Cobol or Realia COBOL ...) program to read an indexed file that was created with a GnuCOBOL program that used BDB or VB-ISAM.
Conversely, read from a GnuCOBOL program an indexed file created by a Microfocus COBOL program with its proprietary system for example IDX4. This would require that EXTFH be available in the non GnuCOBOL environment.
c. Generate file io statistics. Each I-O operation can record the number of times a read, write, delete, open - any file I-O statement.
You could record the start of the call to EXTFH, the return from EXTFH - even the before and after image of the record processed.
You can implement recording stats from the file activity in your EXTFH services. The intent to provide operation reporting performance / consumption.
Each I-O operation can record the number of times a read, write, delete, open - any file I-O statement. You could record the start of the call to EXTFH, the return from EXTFH - even the before and after image of the record processed.
If you use EXTFH you can gather the statistics and only need to recompile the program - no change in them needed at all.
You can create a new EXTFH module named "myiostats.cbl" that uses the "xfhfcd3.cpy" for its LINKAGE and to get the 78 values, which only counts the statistics and possibly write them out when a CLOSE was requested; filter in that program as you like (for example for the filename, filetype, ...) before adding to the statistics; end with CALL "EXTFH" USING fcd-record to let libcob do the actual file io; compile with with cobc -c myiostats.cbl .
Compile your programs with an additional -fcallfh=myiostats myiostats.o to route all io through them. Consequently it does not affect the GnuCOBOL’s EXTFH.
To use EXTFH in any COBOL environment that needs to provide an option like GnuCOBOL has with -fcallfh or MF with its CALLFH directive (GnuCOBOL supports that when included in source files as well).
To be able to call another COBOL’s EXTFH entry point from a GnuCOBOL module to allow the io be routed to that, this environment also needs this entry point and a way to call it directly or via a "to GnuCOBOL foreign" COBOL module that calls into that. So this part means that you can only use it from a GnuCOBOL module if there’s some way to access it.
d. You could read from a Python or Visual Basic program etc etc ... an indexed file written with the GnuCOBOL program using BDB or VB-ISAM as along as you use the applicable structure to call into EXTFH (the C structure is part of libcob / common.h).
The COBOL syntax defining a file (the SELECT and the FD statement) cause the compiler to create the data areas needed to define the file and to hold the file records.
EXTFH uses 4 data areas during file operations: File Control Description (FCD), Record Area, Filename Area, Key Definition Block.
To use the EXTFH you must follow these steps:
a. Allocate data areas for the File Control Description (FCD), Record Area, Filename Area and Key Definition Block(for indexed files only).
b. Initialize all the data areas to binary zeros to ensure that EXTFH does not receive invalid values.
c. Fill in the fields in the Record Area, Filename Area, and Key Definition Block that are needed for the selected Operation Code.
d. Set the pointers in the File Control Description (FCD) to point at Record Area, Filename Area and Key Definition Block (for indexed files only)
e. Select an Operation Code to decide which file operation to be performed
f. Fill in the fields in the FCD that are needed for the selected Operation Code.
g. Call the File Handler.
h. Determine the success of the file I/O operation by checking the returned File Status
i. Process any data in the the Record Area and the FCD output fields
Use the following syntax to call the File Handler from COBOL: CALL "EXTFH" USING opcode fcd where opcode is a PIC X(2) COMP-X field specifying the operation code.
FILE CONTROL DESCRIPTION (FCD)
The FCD area contains information about the file in use, set the appropriate fields in the FCD before calling EXTFH.
After performing the specified operation, EXTFH completes the appropriate fields in the FCD before passing control back to the calling program.
All unused or reserved areas of the FCD must be set to binary zeros.
The FCD used on the call to open a file must be the one used on all subsequent calls to that file. The supplied GnuCOBOL copyfile XFHFCD3.CPY contains a COBOL definition of the FCD.
01 FCD-AREA.
COPY 'xfhfcd3.cpy'.
The structure of the FCD is defined below, bit 7 is always the leftmost bit.
When using COBOL, this and the following pointers are USAGE POINTER items, set using a statement of the form: SET POINTER TO ADDRESS OF data item
where:
pointer is one of these fields,
data item is the relevant data area.
Offset and size are in bytes.
OFFSET SIZE DESCRIPTION
------ ---- --------------------------------------------------------------
0 2 File Status Code. See also offsets 6 and 33.
After every operation except a COMMIT or ROLLBACK operation,
this field is updated with a standard file status value telling
you the status of the operation.
2 3 Reserved. Must be set to binary zeros.
5 1 File organization: 0 Line sequential, 1 Sequential, 2 Indexed,
3 Relative
6 1 User Status and Access Mode indicators.
User Status is indicated by bit 7. The bit is set if you have
defined a file status.
Defining a file status can affect how some operations (such as
RETRYLOCK) are performed.
When calling EXTFH directly, this bit should be set.
however, file status is obtained directly from offset 0.
Access mode is indicated by bits 6-0:
0 - Sequential access mode, 4 - Random access mode,8 - Dynamic
access mode.
7 1 Open mode: you must set this field to 128 before opening a file.
This field is written to by the Callable File Handler so that,
on return, it indicates the open mode of the file: 0 INPUT,
1 OUTPUT, 2 I/O, 3 EXTEND, 128 File is closed.
8 3 Reserved. Must be set to binary zeros.
11 2 Length of filename.
13 8 Relative byte address.
This field is used instead of the 4 byte field at offset 72 if
bit 4 of byte 93 is set.
21 3 Reserved. Must be set to binary zeros.
24 1 Lock mode flags for shareable files:
Bit 7 - Lock on multiple records
Bit 6 - WRITELOCK directive enabled
Bit 5 - RETRYOPEN
Bit 4 - SKIPLOCK directive enabled
Bit 3 - RETRYLOCK directive enabled
Bit 2 - Lock mode MANUAL
Bit 1 - Lock mode AUTOMATIC
Bit 0 - Lock mode EXCLUSIVE
25 1 Other flags:
Bit 7 - OPTIONAL file (OPEN INPUT)
Bit 6 - Reserved
Bit 5 - Not OPTIONAL (OPEN I/O and EXTEND)
Bit 4 - Filename is EXTERNAL
Bit 3 - Reserved
Bit 2 - NODETECTLOCK directive enabled
Bit 1 - Multiple Reel file (Record Sequential)
Bit 0 - Line Advancing file (Record Sequential).
26 2 Reserved. Must be set to binary zeros.
28 4 File handle
32 1 Reserved. Must be set to binary zeros.
33 1 File status type. See also offsets 0 and 6:
Bit 7 Set for ANSI'85 COBOL file status by default, otherwise
ANSI'74 COBOL file status
Bits 6-3 Reserved
Bit 2 Enables tab insertion for line sequential files
Bit 1 Enables null insertion for line sequential files
Bit 0 Reserved.
Bits 1 and 2 are set/unset by EXTFH at open time,
depending on the settings of the N and T RTS switches. These
bits can be set/unset after an OPEN operation to override the
N and T RTS switches.
34 1 File format:
0 - Operating system default. C-ISAM on UNIX,
same as specifying a value of 3 on DOS, Windows and OS/2.
1 - C-ISAM format
2 - LEVEL II COBOL format
3 - Micro Focus COBOL format
4 - IDXFORMAT"4" format
All platforms except UNIX:
5 - Btrieve format with ANSI emulation
6 - Btrieve format without ANSI emulation
All platforms:
8 - IDXFORMAT"8" format
11 - Sequential files only. Mainframe print file.
14 - Heap file
35 3 Reserved. Must be set to binary zeros.
38 2 Maximum record length (in bytes).
40 3 Reserved. Must be set to binary zeros.
32-bit:
42 1 File descriptor. Returned for line sequential fixed length
sequential and relative files and C-ISAM files on UNIX.
43 4 Relative record number.
47 1 Recording mode: Bits 7-1 Reserved,Bit 0: 0 - Fixed, 1 - Variable
48 2 Current record length (in bytes).
50 2 Minimum record length (in bytes).
52 2 Key-of-Reference (indexed files).
This field identifies the Key-of-Reference, used for random READ
operations.
To specify the prime key, set this field to zero.
For example, to specify the first alternate key defined, use a
value 1; the second alternate key defined use value 2.
Or:
Line count (Line Sequential files).
This field specifies the number of lines to skip when writing a
file. For example:
WRITE AFTER ADVANCING line-count LINES
54 2 Effective key length.
When using a START operation on indexed files, you can specify
only the leading part of a key instead of the whole key. You
should set this field to the number of bytes to be used in the
comparison.It must be > than zero and no bigger than the key
being used.
56 4 Pointer to the record area.
60 4 Pointer to the filename area.
64 4 Pointer to key definition block.
68 4 Reserved. Must be set to binary zeros.
72 4 Relative byte address. Unless bit 4 of byte 93 is set,
in which case the relative byte address is held at offset 13
76 2 Reserved. Must be set to binary zeros.
78 1 Data compression routine indicator:
0 = No compression
1-127 = Micro Focus data compression routine number (1=CBLDC001)
128-255 = User-defined data compression routine number
(128=USRDC128)
79 4 Fileshare V2 session-id.
83 2 Fileshare V2 file-id.
85 6 Reserved. Must be set to binary zeros.
91 1 Bit 7- Interlanguage locking (LOCKTYPE 1), Bits 6-0- Reserved.
92 1 Fileshare V2 flags: Bit 7 - Transaction logging; Bits 6-0 -
Reserved.
93 1 Configuration flags:
Bit 7 - WRITETHRU
Bit 6 - Use Relative Byte Address
Bit 5 - Update current record pointer
Bit 4 - Use offset 13 for relative byte address, instead of
offset 72
Bits 3-2 - Reserved
Bit 1 - Check COBFSTATCONV
Bit 0 - Set if IGNORELOCK required.
94 1 Reserved. Must be set to binary zeros.
95 1 Bit 7- Use EBCDIC collating sequence
Bit 6- Set if file is to have WRITE AFTER ADVANCING
Bit 5- Set if file is to have WRITE BEFORE ADVANCING
Bit 4- ADV byte
Bit 3- Ignore minimum length checking on variable-length files
Bits 2-0- Reserved.
96 1 Index cache size.
97 1 Index cache area.
98 2 Reserved.
RECORD AREA
The record area is an area into which records are read, and from which records are (re)written.
The size of the record area must be four bytes larger than the largest record in the file. The record length fields in the FCD always contain true record lengths, not the length of the record area. (See offsets 38, 48 and 50 in the FCD.)
The following GnuCOBOL sample code shows how the FCD is set up to point to the record area:
01 wRECORD-AREA PIC X(90).
...
SET FCD-RECORD-ADDRESS TO ADDRESS OF wRECORD-AREA
...
FILENAME AREA
The filename area contains the name of the file in use. It can contain drive and/or path information as well as the actual name of the file. If the actual name is shorter than the length of the buffer specified in the FCD, it must be terminated by a space.
This data area must be filled before the first operation on the file.
The following GnuCOBOL sample code shows how the FCD is set up to point to the filename area:
01 wFILENAME-AREA PIC X(60) VALUE "file001.dat".
...
MOVE LENGTH OF wFILENAME-AREA TO FCD-NAME-LENGTH
SET FCD-FILENAME-ADDRESS TO ADDRESS OF wFILENAME-AREA
...
KEY DEFINITION BLOCK
The Key Definition BLOCK is used to hold index key information during operations on indexed files. It consists of three data areas: Global Information area, Key Definition area, Component Definition area.
Global Information Area.
It tells the size of the Key Definition Area and how many keys are in the file. All unused or reserved areas must be initialized to binary zeros. The structure is shown below.
OFFSET SIZE DESCRIPTION
------ ---- -------------------------------------
0 2 Length of the Key Definition Block
2 4 Reserved. Must be set to binary zeros
6 2 Number of keys
8 6 Reserved. Must be set to binary zeros.
Key Definition Area Parameter Block
It describes the keys used in the indexed file and consists of one Key Definition for each key in the file. You must define all keys before their components. The order of defining the keys is important. The ordinal position of the key is used to identify it.
For example, if you have an indexed file with a prime key and two alternate keys, the Key Definition area would contain three key definitions. The prime key is key 0, the first alternate is key 1, and the second alternate is key 2. All unused or reserved areas must be initialized to binary zeros.
The structure is shown below.
OFFSET SIZE DESCRIPTION
------ ---- --------------------------------------------------------------
0 2 Component count. For ordinary keys, the component count is 1.
For split keys, the component count is the number of components
making up the split key.
2 2 Offset to first Component Definition area for this key.
This offset is relative to the start of the Global Information
area, starting at 0.
4 1 Key flags:
Bit 7 - Reserved. Must be set to binary zeros
Bit 6 - Duplicates allowed
Bit 5 - Reserved. Must be set to binary zeros
Bit 4 - Set to indicate that this is the prime key. If this is
not set for any key, the file handler assumes that the first
key is the prime key.
Bit 3 - Reserved. Must be set to binary zeros
Bit 2 - Reserved. Must be set to binary zeros
Bit 1 - Sparse key. See offset 6
Bit 0 - Reserved. Must be set to binary zeros.
5 1 Compression flags:
Bits 7-3 - Reserved. Must be set to binary zeros
Bit 2 - Compression of trailing spaces
Bit 1 - Compression of leading characters
Bit 0 - Compression of duplicates
6 2 Sparse character. If bit 1 of the key flags (offset 4) is set,
the key is suppressed if it is entirely made up of this character.
7 8 Reserved. Must be set to binary zeros.
Component Definition Area
It follows the Key Definition Area and contains one component definition for each key component. Each key consists of one component, unless defined as a split key, when each component of the key requires its own Component Definition.
The Component Definitions define the location in the record and length of the key component. All unused or reserved areas must be initialized to binary zeros.
The structure of a Component Definition is shown below.
OFFSET SIZE DESCRIPTION
------ ---- --------------------------------------------------------------
0 2 Reserved. Must be set to binary zeros.
2 4 Offset of component in the record (starting at 0).
6 4 Length of the component (in bytes).
OPERATION CODES
There are two types of operation codes:
Standard: The code contain x"FA" in the leftmost byte; the least significant byte indicates the specific operation
Special: The codes contain x"00" in the leftmost significant byte; the least significant byte indicates the specific operation
Opcode A 2-character operation code specifying an exact operation PIC X(2) COMP-X .
Operation The operation performed by the chosen opcode.
File Type L Line Sequential, S Record Sequential(including vS), R Relative(including vR), I Indexed, vS Variable format Sequential only, vR Variable format Relative only
Input fields The offset values of fields in the FCD to be set before calling.
Output fields The offset values of fields set by EXTFH during the call.
STANDARD OPERATION CODES
They are identified by x"FA" in the leftmost significant byte of the operation code.
The least significant byte indicates the specific operation, as shown in the following sections.
OPEN
Initiates the processing of files.
OP FILE
CODE OPERATION TYPE
---- ------------------------------- -------
00 OPEN INPUT L S R I
01 OPEN OUTPUT L S R I
02 OPEN I-O L S R I
03 OPEN EXTEND L S R I
04 OPEN INPUT WITH NO REWIND L S
05 OPEN OUTPUT WITH NO REWIND L S
08 OPEN INPUT REVERSED L S
Input Fields:
Offset 5 File organization
Offset 6 Access mode
Offset 7 Open mode. Must be set to 128 before opening a file.
Offset 11 Length of filename
Offset 24 Lock mode flags
Offset 25 Other flags
Offset 34 File format
Offset 38 Maximum record length
Offset 47 Recording mode
Offset 50 Minimum record length
Offset 60 Pointer to the filename area
Offset 64 Pointer to the key definition block (I)
Offset 78 Data compression
Offset 91 Interlanguage locking
Filename area
Key Definition Area (only for Indexed Files)
Output Fields:
Offset 0 User file status
Offset 7 Open mode
FCD Use for all subsequent accesses to this file
Opening a File More Than Once.
With EXTFH you can assign several FCDs to the same physical file and have them all open at the same time. The operating system counts it as just one open file. The physical file is not closed until every logical file assigned to it has been closed.
CLOSE
Terminates the processing of files.
OP FILE
CODE OPERATION TYPE
---- ------------------------------- -------
80 CLOSE L S R I
81 CLOSE WITH LOCK L S R I
82 CLOSE WITH NO REWIND L S
84 CLOSE REEL/UNIT L S
85 CLOSE REEL/UNIT FOR REMOVAL L S
86 CLOSE REEL/UNIT WITH NO REWIND L S
Input Fields: None
Output Fields: Offset 0 - User file status
READ
Makes available a specified record (random access) or the next or previous logical record (sequential access).
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
8D READ (sequential) WITH NO LOCK L S R I
D8 READ (sequential) WITH LOCK L S R I
D9 READ (sequential) WITH KEPT LOCK L S R I
F5 READ (sequential) L S R I
8C READ PREVIOUS WITH NO LOCK R I
DE READ PREVIOUS WITH LOCK R I
DF READ PREVIOUS WITH KEPT LOCK R I
F9 READ PREVIOUS R I
8E READ (random) WITH NO LOCK R I
DA READ (random) WITH LOCK R I
DB READ (random) WITH KEPT LOCK R I
F6 READ (random) R I
8F READ (direct) WITH NO LOCK L S R I
D6 READ (direct) WITH LOCK L S R I
D7 READ (direct) WITH KEPT LOCK L S R I
C9 READ (direct) L S R I
F1 READ (position) L S R I
Input Fields:
Offset 43 Relative record number (R) if READ random or direct
Offset 52 Key identifier (I)
Offset 56 Pointer to the record area
Output Fields:
Offset 0 User file status
Offset 48 Current record length
Offset 72 Relative byte address
Record Area
WRITE/REWRITE
Releases a logical record for an output or input-output file. For sequential files, it can also be used for vertical positioning of lines in a logical page.
The REWRITE operation logically replaces a record existing in a disk file. The WRITE operation releases record locks and writes records.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
E1 WRITE BEFORE L S
E2 WRITE AFTER L S
E3 WRITE BEFORE TAB L S
E4 WRITE AFTER TAB L S
E5 WRITE BEFORE PAGE L S
E6 WRITE AFTER PAGE L S
EC WRITE BEFORE mnemonic name S
ED WRITE AFTER mnemonic name S
F3 WRITE L S R I
F4 REWRITE L S R I
Input Fields:
Offset 43 Relative record number (R)
Offset 48 Current record length
Offset 52 Line count (WRITE only)
Offset 56 Pointer to the record area
Output Fields:
Offset 0 User file status
Offset 72 Relative byte address
START
Provides a basis for logical positioning in a relative or indexed file, for subsequent retrieval of records.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
E8 START equal to full length prime key R I
E9 START equal to (any key/record number) R I
EA START greater than (>) R I
EB START not less than (>=) R I
FE START less than (<) R I
FF START less than or equal to (<=) R I
Input Fields:
Offset 43 Relative record number (R)
Offset 52 Key identifier (I)
Offset 54 Effective key length (I)
Offset 56 Pointer to the record area
Output Fields:
Offset 0 User file status
STEP
Steps to the next physical record, this operation enables very fast access to a record.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
90 STEP NEXT WITH NO LOCK L S R I
D4 STEP NEXT WITH LOCK L S R I
D5 STEP NEXT WITH KEPT LOCK L S R I
CA STEP NEXT L S R I
92 STEP FIRST WITH NO LOCK L S R I
D0 STEP FIRST WITH LOCK L S R I
D1 STEP FIRST WITH KEPT LOCK L S R I
CC STEP FIRST L S R I
Input Fields: Offset 56 Pointer to the record area
Output Fields: Offset 0 User file status
STEP
operations are a method of sequentially retrieving records in a relative or indexed file without having to read via a key or relative record number. Generally, this is a faster method of accessing data in the file.
A STEP NEXT operation returns the record that is physically stored immediately after the one that was last retrieved in the file (either by a STEP or READ operation).
If you are using relative byte addressing and you have specified that the current record pointer should be updated to the record you have just accessed, STEP operations are relative to this new position.
The relative byte address is returned on every STEP operation, so if you need to update the current record pointer to the record just retrieved, you can use the READ (direct) operation using the address returned. The current record pointer is not affected by STEP operations.
DELETE
Logically removes a record from a disk file.
OP FILE
CODE OPERATION TYPE
---- ------------------------------- -------
F7 DELETE vS R I
Input Fields
Offset 43 Non-sequential access to relative record number (R)
Offset 56 Non-sequential access to record pointer (I)
Output Fields:
Offset 0 User file status
DELETE FILE
Physically removes the specified file from the physical devices on which it resides.
OP FILE
CODE OPERATION TYPE
---- ------------------------------- -------
F8 DELETE FILE L S R I
Input Fields:
Offset 5 File organization
Offset 11 Filename length
Offset 34 File format
Offset 60 Pointer to the filename area
Filename Area
Output Fields:
Offset 0 User file status
COMMIT
Releases all record locks in all files held by this run unit. This operation code always requires use of the FCD.
OP FILE
CODE OPERATION TYPE
---- ------------------------------- -------
DC COMMIT (UNLOCK all files) L S R I
Input Fields: Always requires FCD used by the file
Output Fields: None
ROLLBACK
Releases all record locks in all files held by this run unit.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
DD ROLLBACK (UNLOCKs all files) L S R I
Input Fields: None
Output Fields: None
UNLOCK
Releases all record locks held by the run unit on a named file.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
0E UNLOCK L S R I
Input Fields: None
Output Fields: Offset 0 User file status
SPECIAL OPERATION CODES
They must be identified by the hexadecimal code x"00" in the most significant byte of the operation code.
The least significant byte indicates the operation, as shown in the following sections.
GET FILE INFO
Returns information on keys for the specified file in the format of the Key Definition Block for index files and general file information for all file types supported.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
06 Return file information vS vR I
Input Fields:
Offset 5 File organization (can be x"FF")
Offset 11 Length of filename
Offset 60 Pointer to the filename area
Offset 64 Pointer to the key definition area (I)
Output Fields:
Offset 0 User file status
Offset 5 File organization
Key definition Area (I)
Offset 34 File format
Offset 38 Maximum record length
Offset 47 Recording mode
Offset 50 Minimum record length
Offset 72 File size
Offset 78 Data compression routine
It is your responsibility to ensure that you have enough space allocated for the key definition block to hold all the information returned.
Failure to allocate enough space causes corruption of some data areas. For variable-length sequential files and variable-length relative files, no key definition information exists.
If the organization byte of the FCD is set to x"FF", this tries to determine the file type and return with the relevant information set. This mode of operation is not recommended if fixed-length sequential files are involved as it might be impossible to determine the difference between the first record of a fixed-length sequential file and the header of a variable-length sequential file. When the file type is determined as incompatible, the error code 9/161 is returned.
CREATE NEW INDEX
Creates a new .idx file, containing only header information for the file to allow new indexes to be added.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
07 Open new index I
Input fields: same as open
Output fields: same as open
GET NEXT RECORD
Gets the next physical record from the index data file.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
08 Get next record I
Input fields: offset 56 pointer to record area
Output fields:
offset 0 user file status
offset 48 current record length
offset 72 relative byte offset
ADD KEY VALUE
Adds key value to the index for the key specified
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
09 Add key value I
Input fields:
offset 52 key identifier
offset 56 pointer to record area
Output fields: offset 0 user file status
FLUSH FILE
Ensure all data for a specific file is flushed to disk.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
0C Flush File L S R I
Input Fields: None
Output Fields: None
UNLOCK RECORD
Unlocks a specific record in a file.
OP FILE
CODE OPERATION TYPE
---- -------------------------------- -------
0F Unlock record I
Input Fields: Offset 56 Pointer to the record area
Output Fields: None
SAMPLE PROGRAM
EXTFH is very powerful, it requires many parameters to work and provides many return data.An example is very useful to better clarify all these aspects.
The following example also shows the COBOL structure of the FCD area and the Key Definition Area
The following is a single source EXTFH02.COB to be compiled with a single command but which includes two programs EXTFH02A and EXTFH02B.
The first program creates an indexed file with 10 records with the normal I-O statements and calls the second program.
The second program instead uses EXTFH for OPEN, READ REWRITE START READ PREVIOUS and CLOSE operations.
>>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. EXTFH02A.
*>***********************************************************
*> CREATE AN INDEXED FILE WITH 10 RECORDS FOR NEXT PROGRAM
*>***********************************************************
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OUTFILE
ASSIGN TO "FILE01EXTFH"
ORGANIZATION IS INDEXED
RECORD KEY IS PRIME-KEY
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS FS-OUT.
DATA DIVISION.
FILE SECTION.
FD OUTFILE.
01 OUT-REC.
05 PRIME-KEY PIC X(25) VALUE ALL 'K'.
05 IN-DATA PIC X(10) VALUE ALL 'x'.
WORKING-STORAGE SECTION.
01 FS-OUT PIC XX VALUE space.
01 OUT-RECNUM PIC 999 VALUE 0.
PROCEDURE DIVISION.
OPEN OUTPUT OUTFILE.
INITIALIZE OUT-REC ALL TO VALUE.
perform 10 times
MOVE "RECORD-" TO PRIME-KEY (1:7)
ADD 1 TO OUT-RECNUM MOVE OUT-RECNUM TO PRIME-KEY (8:3)
DISPLAY 'WRITE: ' OUT-REC WRITE OUT-REC
end-perform
DISPLAY OUT-RECNUM ' records written'.
CLOSE OUTFILE
display 'Enter to continue...' accept omitted
CALL 'EXTFH02B'
STOP RUN.
END PROGRAM EXTFH02A.
*>***********************************************************
*> USE CALL 'EXTFH' TO OPEN READ REWRITE START READPREV CLOSE
*>***********************************************************
IDENTIFICATION DIVISION.
PROGRAM-ID. EXTFH02B.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 OperationCode.
05 wOperationType pic x(01).
78 Standard-Type value x'FA'.
78 Special-Type value x'00'.
05 wOperationCode pic x(01).
*> Standard Codes (Type is x'FA')
78 Open-Input value x'00'.
78 Open-Output value x'01'.
78 Open-I-O value x'02'.
78 Open-Extend value x'03'.
78 Open-Input-No-Rewind value x'04'.
78 Open-Output-No-Rewind value x'05'.
78 Open-Input-Reversed value x'08'.
78 Close-File value x'80'.
78 Close-Lock value x'81'.
78 Close-No-Rewind value x'82'.
78 Close-Reel-Unit value x'84'.
78 Close-Reel-Unit-For-Removal value x'85'.
78 Close-Reel-Unit-No-Rewind value x'86'.
78 Read-Seq-No-Lock value x'8D'.
78 Read-Seq-Lock value x'D8'.
78 Read-Seq-Kept-Lock value x'D9'.
78 Read-Seq value x'F5'.
78 Read-Previous-No-Lock value x'8C'.
78 Read-Previous-Lock value x'DE'.
78 Read-Previous-Kept-Lock value x'DF'.
78 Read-Previous value x'F9'.
78 Read-Random-No-Lock value x'8E'.
78 Read-Random-Lock value x'DA'.
78 Read-Random-Kept-Lock value x'DB'.
78 Read-Random value x'F6'.
78 Read-Direct-No-Lock value x'8F'.
78 Read-Direct-Lock value x'D6'.
78 Read-Direct-Kept-Lock value x'D7'.
78 Read-Direct value x'C9'.
78 Read-Position value x'F1'.
78 Write-Before value x'E1'.
78 Write-After value x'E2'.
78 Write-Before-Tab value x'E3'.
78 Write-After-Tab value x'E4'.
78 Write-Before-Page value x'E5'.
78 Write-After-Page value x'E6'.
78 Write-Record value x'F3'.
78 Rewrite-Record value x'F4'.
78 Start-Equal-Prime-Key value x'E8'.
78 Start-Equal-Key value x'E9'.
78 Start-Greater value x'EA'.
78 Start-Not-Less value x'EB'.
78 Start-Less value x'FE'.
78 Start-Less-Or-Equal value x'FF'.
78 Step-Next-No-Lock value x'90'.
78 Step-Next-Lock value x'D4'.
78 Step-Next-Kept-Lock value x'D5'.
78 Step-Next value x'CA'.
78 Step-First-No-Lock value x'92'.
78 Step-First-Lock value x'D0'.
78 Step-First-Kept-Lock value x'D1'.
78 Step-First value x'CC'.
78 Delete-Record value x'F7'.
78 Delete-File value x'F8'.
78 Unlock-Current value x'0E'.
78 Commit-All value x'DC'.
78 Rollback-All value x'DD'.
*> Special codes (Type is x'00')
78 Get-File-Info value x'06'. *> not avail. for BDB files
78 Open-New-Index value x'07'.
78 Get-Next-Record value x'08'.
78 Add-Key-Value value x'09'.
78 Unlock-Record value x'0F'.
01 FCD-AREA. *> or use: COPY 'XFHFCD3.CPY'.
10 FCD-FILE-STATUS.
15 FCD-STATUS-KEY-1 pic x.
15 FCD-STATUS-KEY-2 pic x.
15 FCD-BINARY redefines FCD-STATUS-KEY-2 pic x comp-x.
10 FCD-LENGTH pic xx comp-x.
10 FCD-VERSION pic x comp-x.
78 fcd--version-number value 1.
10 FCD-ORGANIZATION pic x comp-x.
78 fcd--line-sequential-org value 0.
78 fcd--sequential-org value 1.
78 fcd--indexed-org value 2.
78 fcd--relative-org value 3.
78 fcd--determine-org value 255. *> see wOperationCode 0006:
10 FCD-ACCESS-MODE pic x comp-x.
78 fcd--sequential-access value 0.
78 fcd--dup-prime-access value 1.
78 fcd--random-access value 4.
78 fcd--dynamic-access value 8.
78 fcd--status-defined value h"80".
10 FCD-OPEN-MODE pic x comp-x. *> open mode
78 fcd--open-input value 0.
78 fcd--open-output value 1.
78 fcd--open-i-o value 2.
78 fcd--open-extend value 3.
78 fcd--open-max value 3.
78 fcd--open-closed value 128.
10 FCD-RECORDING-MODE pic x comp-x. *> recording mode
78 fcd--recmode-fixed value 0.
78 fcd--recmode-variable value 1.
10 FCD-FILE-FORMAT pic x comp-x.
78 fcd--format-liiv1 value 0.
78 fcd--format-cisam value 1.
78 fcd--format-liiv2 value 2.
78 fcd--format-cobol2 value 3.
78 fcd--format-idx4 value 4.
78 fcd--format-btrieve-ansi value 5.
78 fcd--format-btrieve-non-ansi value 6.
*> 78 fcd--format-rlio value 7.
78 fcd--format-big value 8.
78 fcd--format-leafrec value 9.
78 fcd--format-cst value 10.
78 fcd--format-mvs-print value 11.
*> 78 value 13.
78 fcd--format-heap value 14.
78 fcd--format-esds value 15.
78 fcd--format-qsamv value 255.
78 fcd--max-file-format value 16. *> 1 > max permissible format:
10 FCD-DEVICE-FLAG Pic x comp-x.
78 fcd--dev-normal value 0.
78 fcd--dev-device value 1.
78 fcd--dev-stdin value 2.
78 fcd--dev-stdout value 3.
78 fcd--dev-stderr value 4.
78 fcd--dev-badname value 5.
78 fcd--dev-input-pipe value 6.
78 fcd--dev-output-pipe value 7.
78 fcd--dev-i-o-pipe value 8.
78 fcd--dev-library value 9.
78 fcd--dev-disk-file value 10.
78 fcd--dev-null value 11.
78 fcd--dev-disk-redir value 12.
78 fcd--dev-no-map value 13.
10 FCD-LOCK-ACTION pic x comp-x. *> Used only in c-isam type calls
78 fcd--getlock value 1.
78 fcd--nolock value 2.
78 fcd--ignorelock value 3.
10 FCD-DATA-COMPRESS pic x comp-x.
10 FCD-BLOCKING pic x comp-x.
10 FCD-additional-status redefines FCD-blocking pic x comp-x.
10 FCD-IDXCACHE-SIZE pic x comp-x.
10 FCD-PERCENT pic x comp-x.
10 FCD-REC-COUNT-SET redefines FCD-PERCENT pic x comp-x.
10 FCD-BLOCK-SIZE pic x comp-x.
10 FCD-FLAGS-1 pic x comp-x.
78 fcd--mainframe-compat value h"80".
78 fcd--ansi-line-adv value h"40".
78 fcd--return-key-only value h"20".
78 fcd--bypass-esds value h"10".
78 fcd--no-xfhname-mapping value h"08".
78 fcd--dont-call-xfhtrace value h"04".
78 fcd--call-xfhtrace value h"02".
78 fcd--fcd-decl value h"01". *> declaratives exist:
10 FCD-FLAGS-2 pic x comp-x.
78 fcd--convert-dbspace value h"01".
10 fcd-mvs-flags pic x comp-x. *> MVS flag bits
78 fcd--file-is-syspunch value h"10".
78 fcd--file-is-indd value h"08".
78 fcd--file-is-outdd value h"04".
78 fcd--amode-31bit value h"02".
78 fcd--amode-24bit value h"01".
78 fcd--amode-bits value fcd--amode-31bit + fcd--amode-24bit.
10 FCD-STATUS-TYPE pic x comp-x.
78 fcd--ans85-status value h"80".
78 fcd--no-space-fill value h"40".
78 fcd--no-strip-spaces value h"20".
78 fcd--no-expand-tabs value h"10".
78 fcd--rec-term-bit value h"08".
78 fcd--insert-tabs value h"04".
78 fcd--insert-nulls value h"02".
78 fcd--cr-delimiter value h"01".
78 fcd--modify-writes value fcd--insert-tabs + fcd--insert-nulls.
10 FCD-OTHER-FLAGS pic x comp-x.
78 fcd--optional-file value h"80".
78 fcd--nodetectlock-input value h"40".
78 fcd--not-optional value h"20".
78 fcd--external-name value h"10".
78 fcd--get-info value h"08".
78 fcd--nodetectlock value h"04".
78 fcd--multiple-reel value h"02".
78 fcd--line-advancing value h"01".
78 fcd--special-sequential
value fcd--optional-file + fcd--multiple-reel + fcd--line-advancing.
10 FCD-TRANS-LOG pic x comp-x.
78 fcd--open-input-shared value h"80".
78 fcd--allow-input-locks value h"40".
78 fcd--no-read-sema value h"20".
78 fcd--expand-positioning-bit value h"10".
78 fcd--no-seq-check value h"08".
78 fcd--dat-term-bit value h"04".
78 fcd--slow-read value h"02".
78 fcd--suppress-adv value h"01".
10 FCD-LOCKTYPES pic x comp-x.
78 fcd--interlang-locking value h"80".
78 fcd--allow-readers value h"40".
78 fcd--separate-lock-file value h"20".
78 fcd--single-open value h"10".
78 fcd--nfs-file-lock value h"08".
78 fcd--nfs-file-lock-hp value h"04".
78 fcd--nfs-file-locks value fcd--nfs-file-lock + fcd--nfs-file-lock-hp.
10 FCD-FS-FLAGS pic x comp-x.
78 fcd--transaction-processing-bit value h"80".
78 fcd--recovery-run-b value h"04".
78 fcd--fs-server-bit value h"02".
10 FCD-CONFIG-FLAGS pic x comp-x.
78 fcd--writethru-bit value h"80".
78 fcd--relative-bit value h"40".
78 fcd--set-crp-bit value h"20".
78 fcd--bigfile-bit value h"10".
*> 78 fcd--return-percent value h"08".
*> 78 fcd--dont-call-xfhconv value h"04".
78 fcd--call-cobfstatconv value h"02".
78 fcd--ignorelock-bit value h"01".
10 FCD-MISC-FLAGS pic x comp-x.
78 fcd--mainframe-hostfd value h"80".
78 fcd--set-idxdatbuf value h"40".
78 fcd--load-onto-heap value h"20".
78 fcd--usage-unknown value h"10".
78 fcd--recmode-s value h"08".
78 fcd--recmode-u value h"04".
78 fcd--external-fcd value h"02".
78 fcd--closed-with-lock value h"01".
10 FCD-CONFIG-FLAGS2 pic x comp-x.
78 fcd--file-is-ebcdic value h"80".
78 fcd--file-has-write-after value h"40".
78 fcd--file-has-write-before value h"20".
78 fcd--file-has-adv-specified value h"10".
78 fcd--no-min-len-check value h"08".
78 fcd--no-key-check value h"04".
78 fcd--convert-to-ascii value h"02".
78 fcd--rm-behaviour value h"01".
78 fcd--file-has-before-or-after
value fcd--file-has-write-before + fcd--file-has-write-after.
10 FCD-LOCK-MODE pic x comp-x.
78 fcd--multilock-bit value h"80".
78 fcd--writelock-bit value h"40".
78 fcd--retry-open-bit value h"20".
78 fcd--skip-lock-bit value h"10".
78 fcd--retry-lock-bit value h"08".
78 fcd--manual-lock-bit value h"04".
78 fcd--auto-lock-bit value h"02".
78 fcd--exclusive-bit value h"01".
78 fcd--sharing-bits value fcd--manual-lock-bit + fcd--auto-lock-bit.
10 FCD-SHR2 pic x comp-x.
78 fcd--file-max-bit value h"08".
78 fcd--file-pointer-bit value h"04".
78 fcd--retry-time-bit value h"02".
78 fcd--start-unlock value h"01".
10 FCD-IDXCACHE-BUFFS pic x comp-x.
10 FCD-INTERNAL-FLAGS-1 pic x comp-x.
10 FCD-INTERNAL-FLAGS-2 pic x comp-x.
10 pic x comp-x occurs 15.
10 FCD-NLS-ID pic xx comp-x. *> NLS id (else 0)
10 FCD-FS-FILE-ID pic xx comp-x.
10 fcd-retry-open-count pic xx comp-x.
10 FCD-NAME-LENGTH pic xx comp-x.
10 fcd-idxname-length pic xx comp-x.
10 fcd-retry-count pic xx comp-x.
*> Indexed key identifier for random READ
10 FCD-KEY-ID pic xx comp-x.
10 FCD-LINE-COUNT pic xx comp-x. *> Line count (seq files)
10 FCD-USE-FILES pic x comp-x.
10 FCD-GIVE-FILES pic x comp-x.
10 FCD-KEY-LENGTH pic xx comp-x. *> Effective key length
*> (START KEY LENGTH IS n)
10 pic x comp-x occurs 20.
10 FCD-CURRENT-REC-LEN pic x(4) comp-x. *> Current record length
10 FCD-MIN-REC-LENGTH pic x(4) comp-x. *> Minimum record length
10 FCD-MAX-REC-LENGTH pic x(4) comp-x. *> Max record length
10 FCD-SESSION-ID pic x(4) comp-x.
10 pic x comp-x occurs 24.
10 FCD-RELADDR-OFFSET pic x(8) comp-x.
10 FCD-RELADDR redefines FCD-RELADDR-OFFSET pic x(8) comp-x.
10 FCD-RELADDR-BIG redefines FCD-RELADDR-OFFSET pic x(8) comp-x.
10 FCD-MAX-REL-KEY pic x(8) comp-x.
10 FCD-RELATIVE-KEY pic x(8) comp-x.
10 FCD-PTR-FILLER1 pic x(8) comp-x.
10 FCD-HANDLE redefines FCD-PTR-FILLER1 usage pointer.
10 FCD-HANDLE-NUM redefines FCD-PTR-FILLER1 pic x(4) comp-x.
10 FCD-PTR-FILLER2 pic x(8) comp-x. *> Pointer to record area
10 FCD-RECORD-ADDRESS redefines FCD-PTR-FILLER2 usage pointer.
10 FCD-PTR-FILLER3 pic x(8) comp-x. *> Pointer to file name
10 FCD-FILENAME-ADDRESS redefines FCD-PTR-FILLER3 usage pointer.
*> Pointer to index name (applies only if separate index file exists)
10 FCD-PTR-FILLER4 pic x(8) comp-x.
10 FCD-IDXNAME-ADDRESS redefines FCD-PTR-FILLER4 usage pointer.
10 FCD-INDEX-NAME redefines FCD-PTR-FILLER4 usage pointer.
10 FCD-PTR-FILLER5 pic x(8) comp-x. *> Pointer to key def block
10 FCD-KEY-DEF-ADDRESS redefines FCD-PTR-FILLER5 usage pointer.
10 FCD-PTR-FILLER6 pic x(8) comp-x. *> Pointer to collating seq
10 FCD-COL-SEQ-ADDRESS redefines FCD-PTR-FILLER6 usage pointer.
10 FCD-PTR-FILLER7 pic x(8) comp-x. *> Pointer to using list
10 FCD-FILDEF-ADDRESS redefines FCD-PTR-FILLER7 usage pointer.
10 FCD-PTR-FILLER8 pic x(8) comp-x.
10 FCD-DFSORT-ADDRESS redefines FCD-PTR-FILLER8 usage pointer.
01 FILE-NAME PIC X(64).
01 RECORD-AREA.
05 PRIME-KEY PIC X(25).
05 DATA-AREA PIC X(10).
01 RECORD-AREA2.
05 PRIME-KEY2 PIC X(25).
05 DATA-AREA2 PIC X(10).
01 KEY-DEF-BLOCK.
47 GLOBAL-INFORMATION-AREA.
49 LENGTH-OF-KEY-DEF-AREA pic 9(04) comp-x.
49 key-version pic 9(02) comp-x value 2.
49 filler pic 9(06) comp-x. *> reserved
49 NUMBER-OF-KEYS pic 9(04) comp-x.
49 filler pic 9(13) comp-x. *> reserved
*> key-def-area is repeated for the n.of keys defined by NUMBER-OF-KEYS
47 KEY-DEF-AREA.
49 component-count pic 9(4) comp-x.
*> The offset for the component-specification for this key
49 component-defs pic 9(4) comp-x.
49 key-flags pic 9(2) comp-x.
78 KEY2KEYFLAG-DUPS-IN-ORDER value h"40".
78 KEY2KEYFLAG-PRIME value h"10".
78 KEY2KEYFLAG-SPARSE-KEY value h"02".
49 key-compression pic 9(2) comp-x.
78 KEY2COMPRESS-TRAILING-NULLS value h"08".
78 KEY2COMPRESS-TRAILING-SPACES value h"04".
78 KEY2COMPRESS-IDENTICAL-CHARS value h"02".
78 KEY2COMPRESS-FOLLOWING-DUP value h"01".
78 KEY2COMPRESS-NO-COMPRESSION value h"00".
78 KEY2COMPRESS-DEFAULT value KEY2COMPRESS-NO-COMPRESSION.
49 sparse-characters pic x(2).
49 filler pic x(8). *> reserved
*> component-specifications for all keys follows after the key definition area
*> for all the keys.
47 COMPONENT-DEF-AREA.
49 component-flags pic 9(2) comp-x.
49 component-type pic 9(2) comp-x.
78 KEY2PARTTYP-NUMERIC value h"80".
78 KEY2PARTTYP-SIGNED value h"40".
78 KEY2PARTTYP-COMP value h"20".
78 KEY2PARTTYP-COMP-3 value h"21".
78 KEY2PARTTYP-COMP-X value h"22".
78 KEY2PARTTYP-COMP-5 value h"23".
78 KEY2PARTTYP-FLOAT value h"24".
78 KEY2PARTTYP-COMP-6 value h"25".
78 KEY2PARTTYP-DISPLAY value h"00".
78 KEY2PARTTYP-SIGN-TRAIL-INCL value h"00".
78 KEY2PARTTYP-SIGN-TRAIL-SEP value h"01".
78 KEY2PARTTYP-SIGN-LEAD-INCL value h"02".
78 KEY2PARTTYP-SIGN-LEAD-SEP value h"03".
78 KEY2PARTTYP-SIGN-LEAD-FLOAT value h"04".
49 component-offset pic 9(9) comp-x.
49 component-length pic 9(9) comp-x.
01 OP-N PIC X COMP-X.
01 OP-X REDEFINES OP-N PIC X.
PROCEDURE DIVISION.
PERFORM 1000-OPEN-FILE.
INITIALIZE RECORD-AREA.
MOVE 'RECORD-003KKKKKKKKKKKKKKK' TO PRIME-KEY.
PERFORM 2000-READ-RECORD.
DISPLAY 'AFTER RANDOM READ ------> ' RECORD-AREA '<' DISPLAY SPACE
PERFORM 3000-REWRITE-RECORD.
PERFORM 2000-READ-RECORD.
DISPLAY 'READ AFTER REWRITE -----> ' RECORD-AREA '<' DISPLAY SPACE
PERFORM 5000-CLOSE-FILE.
PERFORM 1000-OPEN-FILE.
PERFORM 6000-START.
PERFORM 7000-READ-PREVIOUS.
DISPLAY 'AFTER 1ST READ PREVIOUS -> ' RECORD-AREA2 '<' DISPLAY SPACE
PERFORM 7000-READ-PREVIOUS.
DISPLAY 'AFTER 2ND READ PREVIOUS -> ' RECORD-AREA2 '<' DISPLAY SPACE
PERFORM 5000-CLOSE-FILE.
STOP RUN.
1000-Open-File.
MOVE 'FILE01EXTFH' TO FILE-NAME
MOVE STANDARD-TYPE TO wOperationType
MOVE OPEN-I-O TO wOperationCode
MOVE LOW-VALUES TO FCD-AREA
MOVE LENGTH OF FCD-AREA TO FCD-LENGTH
MOVE LENGTH OF FILE-NAME TO FCD-NAME-LENGTH
MOVE fcd--version-number TO FCD-VERSION
SET FCD-FILENAME-ADDRESS TO ADDRESS OF FILE-NAME
SET FCD-RECORD-ADDRESS TO ADDRESS OF RECORD-AREA
SET FCD-KEY-DEF-ADDRESS TO ADDRESS OF KEY-DEF-AREA
MOVE fcd--exclusive-bit TO FCD-LOCK-MODE
MOVE fcd--format-cobol2 TO FCD-FILE-FORMAT
MOVE fcd--indexed-org TO FCD-ORGANIZATION
MOVE fcd--dynamic-access TO FCD-ACCESS-MODE
MOVE fcd--recmode-fixed TO FCD-RECORDING-MODE
MOVE LENGTH OF RECORD-AREA TO FCD-MIN-REC-LENGTH
MOVE LENGTH OF RECORD-AREA TO FCD-MAX-REC-LENGTH
MOVE LENGTH OF RECORD-AREA TO FCD-CURRENT-REC-LEN
move fcd--open-closed TO FCD-OPEN-MODE
MOVE 16 TO FCD-FS-FLAGS
MOVE 1 TO NUMBER-OF-KEYS
MOVE LENGTH OF PRIME-KEY TO COMPONENT-LENGTH
display "01--- OPEN I-O"
PERFORM 9000-CALL-EXTFH.
2000-Read-Record.
INITIALIZE RECORD-AREA.
MOVE 'RECORD-003KKKKKKKKKKKKKKK' TO PRIME-KEY.
MOVE READ-RANDOM-LOCK TO wOperationCode.
SET FCD-RECORD-ADDRESS TO ADDRESS OF RECORD-AREA.
display "02--- READ"
PERFORM 9000-CALL-EXTFH.
3000-Rewrite-Record.
MOVE REWRITE-RECORD TO wOperationCode.
MOVE '1234567890' TO DATA-AREA.
display "03--- REWRITE"
PERFORM 9000-CALL-EXTFH.
5000-Close-File.
MOVE CLOSE-FILE TO wOperationCode.
display "04--- CLOSE"
PERFORM 9000-CALL-EXTFH.
6000-Start.
SET FCD-RECORD-ADDRESS TO ADDRESS OF RECORD-AREA.
MOVE 25 TO FCD-KEY-LENGTH.
MOVE HIGH-VALUES TO PRIME-KEY.
MOVE START-LESS TO wOperationCode.
display "05--- START"
PERFORM 9000-CALL-EXTFH.
7000-Read-Previous.
MOVE READ-PREVIOUS TO wOperationCode.
INITIALIZE RECORD-AREA2.
SET FCD-RECORD-ADDRESS TO ADDRESS OF RECORD-AREA2.
display "06--- READ PREVIOUS"
PERFORM 9000-CALL-EXTFH.
9000-CALL-EXTFH.
move '99' to FCD-FILE-STATUS
display 'BEFORE OpCode: ' FUNCTION HEX-OF(OperationCode)
perform 9900-Display
CALL 'EXTFH' USING OperationCode FCD-AREA
display 'AFTER OpCode : ' FUNCTION HEX-OF(OperationCode)
perform 9900-Display
accept omitted
IF FCD-FILE-STATUS NOT = '00'
MOVE wOperationCode TO OP-X
IF FCD-STATUS-KEY-1 = '9'
DISPLAY 'FILE ERROR, STATUS: 9/' FCD-BINARY '
wOperationCode: ' OP-N
ELSE
DISPLAY 'FILE ERROR, STATUS: ' FCD-FILE-STATUS '
wOperationCode: ' OP-N
END-IF
STOP RUN
END-IF.
9900-Display.
display 'FILE-STATUS : ' FCD-FILE-STATUS
if wOperationCode NOT = READ-PREVIOUS
display 'RECORD-AREA : ' RECORD-AREA
else display 'RECORD-AREA2 : ' RECORD-AREA2
end-if
display 'KEY-DEF-AREA :' display FUNCTION HEX-OF(KEY-DEF-AREA)
continue.
END PROGRAM EXTFH02B.
RELATIVE BYTE ADDRESSING
When you read or write a record, you obtain its relative byte address. Using this address, you can re-read, re-write or delete the record without using keys and indexes.
This is a fast method of accessing records, but has limitations :
- A normal relative byte address operation does not affect the current record pointer. Therefore, a READ (sequential) after a relative byte addressing operation returns the record after the last one accessed using normal access methods. It does not return the record after the one you accessed using relative byte addressing.
- It is possible, however, to update the file position indicator so it points to the record you accessed using relative byte addressing. A subsequent READ returns you to the record after the one you accessed using the relative byte address operation.
- To update the file position indicator, you should set Bit 5 of the configuration flags (offset 93) in the FCD before calling the Callable File Handler to perform the relative byte address operation.
- Relative byte operations update the index when a record is re-written or deleted.
- If the record has been deleted since the relative byte address for it was obtained, a read or write using its relative byte address usually fails.
- However, you should be aware that it is possible for the record to have been replaced by a different record.
Record locking is supported by relative byte addressing.
The relative byte address of a record is returned in offset 72 of the FCD (or offset 13, if bit 4 of offset 93 is set) on all operations that involve specific records.
To use this address, simply save the contents of this field after a READ operation. Note that if the operation is unsuccessful, the value in the relative byte address is undefined.
Once you have obtained the relative byte address of a record, you can perform a number of operations. These are outlined in the following sections.
You can read a specific record from a file in two ways using the relative address:
Put the relative address in the relative byte address field of the FCD and set bit 6 of the configuration flags in the FCD (offset 93).
If you want to update the file position indicator to this record, set bit 5 of the configuration flags (offset 93).
Perform a READ (random) WITH NO LOCK, READ (random) WITH LOCK, READ (random) WITH KEPT LOCK or READ (random) operation on the file.
The READ (direct) operations work the same as described above, but do not require certain bits in the FCD to be set.
The READ (direct) operations always return the record at the address given in the relative byte address field of the FCD and update the file position indicator.
Both of the above methods provide a way of switching the current key-of-reference to a different key. For example, if READ (sequential) operations are performed via the primary key, you can start reading via the first alternate key from the current record using the following steps:
a. Read the next record in the file (the address of this record is in the FCD relative byte address field).
b. Put the new key-of-reference in the key-of-reference field in the FCD (offset 52).
c. Perform a READ (direct) operation to return the record at this address. The key-of-reference is changed to the new one.
d. Read the next record in the file. This is the next record in the new key-of-reference index.
You can re-write a record to a specific address by specifying that address in the relative byte address field of the FCD and setting bit 6 of the configuration flags in the FCD (offset 93). If you want to update the file position indicator, set bit 5 of the configuration flags in the FCD (offset 93). You can delete a record at a specific address by specifying that address in the relative byte address field of the FCD and setting bit 6 of the configuration flags in the FCD (offset 93).
CREATING A NEW INDEX
That enables you to recreate an index file using only the information in the data file. To recreate an index file, your program must:
a. Open the file using the open-new-index operation code.
b. Read records from the file using the get-next-rec operation code.
c. Create an index from each separate record, using the add-index operation code.
GnuCOBOL Example:
78 open-new-index value x"0007".
78 get-next-rec value x"0008".
78 add-key-value value x"0009".
78 close-file value x"fa80".
...
move open-new-index to opcode
perform EXTFH-op
move get-next-rec to opcode
perform EXTFH-op
perform until fcd-status(1:1) not = "0"
perform varying fcd-key-id from 0 by 1 until fcd-key-id = key-count
or fcd-status(1:1) not = "0"
move add-key-value to opcode
perform EXTFH-op
end-perform
move get-next-rec to opcode
perform EXTFH-op
end-perform
move close-file to opcode
perform EXTFH-op
...
EXTFH-op.
call "EXTFH" using opcode, fcd
if fcd-status of fcd (1:1) "1"
move 1 to return-code
end-if.
ACCESSING A COMPILER GENERATED FCD
When normal I/O operations (OPEN, READ ...) in a GnuCOBOL program, an FCD is created for each file.
To access this FCD, set up a FCD definition in the Linkage Section of your program. An example FCD COBOL definition is supplied in a file called xfhfcd3.cpy.
This definition (that takes up no physical memory) can then be mapped onto the FCD you want to read or alter using the following SET statement in your program:
SET ADDRESS OF fcd TO ADDRESS OF fh--fcd OF namefile
where the parameters are:
fcd The name of the FCD definition in the Linkage Section of your program;
fh–fcd OF namefile (note the double hyphen). The pointer special register automatically allocated to the file with FD-name: namefile.
Following this SET operation, the data items defined in the Linkage Section group item fcd become the fields of the FCD of the file referenced in the SET statement.
Similarly, you can access the Key Definition Block by:
SET ADDRESS OF kda TO ADDRESS OF fh--keydef OF namefile
where the parameters are:
kda the name of the key definition Block in the Linkage Section of your program;
fh–keydef of indexedfile the pointer special register automatically allocated to the file with FD-name indexfile to point to its Key Definition Block.
TURN ON KEY COMPRESSION IN A FILE
Following sample program turns on key compression in a file by setting bits in the file’s Key Definition Block.
select MASTERFILE
assign to ...
organization is indexed
record key is M-RecKey
alternate key is M-AltKey1 with duplicates
alternate key is M-AltKey2
alternate key is M-AltKey3 with duplicates.
select INDEXEDFILE
assign to ...
organization is indexed
record key is I-RecKey
alternate key is I-AltKey1 with duplicates.
...
...
LINKAGE SECTION.
01 KeyDefinitionBlock.
03 filler pic x(6).
03 KeyCount pic 9(4) comp-x.
03 filler pic x(6).
03 KeyDefinition occurs 1 to 4 times depending on KeyCount.
05 filler pic x(5).
05 KeyCompression pic 9(2) comp-x.
05 filler pic x(10).
...
PROCEDURE DIVISION.
*>
*> set appropriate key compressions:
*> +-- trailing space compression
*> |+-- leading character compression
*> ||+-- duplicate key compression
*> |||
*> 7 = 00000111 - all compressions
*> 6 = 00000110 - leading character & trailing space
*> 2 = 00000010 - leading character compression
*> 1 = 00000001 - duplicate key compression
set address of KeyDefinitionBlock to address of fh--keydef of MASTERFILE
move 4 to KeyCount
move 6 to KeyCompression(1)
move 7 to KeyCompression(2)
move 6 to KeyCompression(3)
move 7 to KeyCompression(4)
open I-O MASTERFILE
. . .
set address of KeyDefinitionBlock to address of fh--keydef of INDEXEDFILE
move 2 to KeyCount
move 4 to KeyCompression(1)
move 1 to KeyCompression(2)
open input INDEXEDFILE
See the file NEWS for other details as implementation may varies between compiler versions.
SYSTEM
SYSTEM Built-In Subroutine Syntax
=======================================================================
CALL "SYSTEM" USING command
~~~~ ~~~~~
=======================================================================
This subroutine submits <command> (an alphanumeric literal or data item) to a command shell for execution as if it were typed into a console/terminal window.
A shell will be opened subordinate to the GnuCOBOL program issuing the call to SYSTEM.
Output from the command (if any) will appear in the command window in which the GnuCOBOL program was executed.
On a Unix system, the shell environment will be established using the default shell program. This is also true when using a GnuCOBOL build created with and for OSX or the Cygwin Unix emulator.
With native Windows Windows/MinGW builds, the shell environment will be the Windows console window command processor (usually cmd.exe) appropriate for the version of Windows you’re using.
To trap output from the executed command and process it within the GnuCOBOL program, use a redirection (‘>’) to send the command output to a temporary file which you read from within the program once control returns.
The exit status of the executed command will be available in the RETURN-CODE special-register.
X"91"
X"91" Built-In Subroutine Syntax
=======================================================================
CALL X"91" USING return-code, function-code, binary-variable-arg
~~~~ ~~~~~
=======================================================================
The original Micro Focus version of this routine is capable of providing a wide variety of functions. GnuCOBOL supports just three of them namely 11, 12 and 16, but maybe more on the way subject to version of compiler (see file NEWS):
11 Sets and/or clears all eight of the COBOL switches (
SWITCH-1throughSWITCH-8). See SPECIAL-NAMES, for an explanation of those switches. Also referred to as programmable 0 - 7.The <variable-arg> argument should be an
OCCURS 8 TIMEStable ofUSAGE BINARY-CHARorUSAGE COMP-X.Each occurrence that is set to a value of zero prior to the
CALL X"91"will cause the corresponding switch to be cleared. Each occurrence set to 1 prior to theCALL X"91"will cause the corresponding switch to be set.Values other than 0 or 1 will be ignored.
Syntax: FN-Status set to 0 if the function is successful, else 1. X91-function set to 11. Group-item group-item with - Switch-flags values ( 0 or 1 ) for each of the 8 switches. Parameters: 01 FN-Return-Code pic x comp-x. 01 x91-function pic x comp-x. 01 Group-item. 01 Switch-Flags pic x comp-x occurs 8 Code example: 77 fn-Return-Code pic x comp-x. 77 x91-function pic x comp-x value 11. 01 Group-item. 05 switch-flags pic x comp-x occurs 8. ... move 1 to switch-flags(1). call x"91" using fn-Return-Code, x91-Function, Group-item ...12 Reads all eight of the COBOL switches (
SWITCH-1throughSWITCH-8) and debug switches as prorammable 0 - 7.The <variable-arg> argument should be an
OCCURS 8 TIMEStable ofUSAGE BINARY-CHARorUSAGE COMP-X.Each of the 1st eight occurrences of the array will be set to either 0 or 1 — 1 if the corresponding switch is set, 0 otherwise.
Syntax: FN-Status set to 0 if the function is successful, else 1. X91-function set to 12. Group-item group-item to receive - Switch-flags value of each of the switches set. Parameters: 01 FN-Return-Code pic x comp-x. 01 x91-function pic x comp-x. 01 Group-item. 01 Switch-Flags pic x comp-x occurs 8 Code example: ... special-names. switch 1 is switch-1. ... 77 fn-Return-Code pic x comp-x. 77 x91-function pic x comp-x value 12. 01 group-item. 05 switch-flags pic x comp-x occurs 8. ... set switch-1 to on call x"91" using fn-Return-Code, x91-function, Group-item. ...16 Retrieves the number of arguments passed to the program executing the
CALL X"91", saving that number into the <variable-arg> argument. That should be a binary numeric data item (USAGE BINARY-CHARorUSAGE COMP-Xis recommended).Usage: call x"91" using fn-status, x91-function, num-params. Parameters: 01 Fn-status pic x comp-x 01 x91-function pic x comp-x 01 num-params pic x comp-x Syntax: Fn-status Set to 0 if the function is successful, else 1. X91-function Set to 16. num-params Receives the number of parameters on the Procedure Division USING / CHAINING statement.
The <return-code> argument must be a one-byte binary numeric data item (USAGE BINARY-CHAR is recommended). It will receive a value of 0 if the operation was successful, 1 otherwise.
The <function-code> argument must be either a numeric literal or a one-byte binary numeric data item (USAGE BINARY-CHAR is recommended).
The third argument — <variable-arg> — is defined differently depending upon the <function-code> value, but are not implemented and are as follows:
- 13 + 14
-
Allow access to runtime switches 1 - 26 as A-Z. In case of A.N.T: set related runtime setting. Option 13 read them and option 14 sets them.
- 15
-
Prepare for program lookup. Checks to see if a program exists. You pass the program name and its length in parameter. When routine exits, result is zero if found and non-zero if not. Parameter is a group item consisting of two data items: a PIC X COMP-X specifyinh length in bytes of data item containing the file name and PIC X data item of varaiable length containing the file name.
- 35
-
Prepare for DOS EXEC call.
- 46-49
-
Prepare for file specific settings LS_NULLS/LS_TABS.
- 69
-
Prepare for directory search.
X"E4"
X"E4" Built-In Subroutine Syntax
=======================================================================
CALL X"E4"
~~~~
=======================================================================
Use X"E4" to clear the screen. There are no arguments and no returned value.
X"E5"
X"E5" Built-In Subroutine Syntax
=======================================================================
CALL X"E5"
~~~~
=======================================================================
The X"E5" routine will sound the PC “bell”. There are no arguments and no returned value. Works the same as function CBL_ALARM_SOUND and CBL_BELL_SOUND.
X"F4"
X"F4" Built-In Subroutine Syntax
=======================================================================
CALL X"F4" USING byte, table
~~~~ ~~~~~
=======================================================================
This routine packs the low-order (rightmost) bit from each of the eight 1-byte items in <table> into the corresponding bit positions of the single-byte data item <byte>.
The <byte> data item need be only a single byte in size. If it is longer, the excess will be unaffected by this subroutine.
The <table> data item must be at least 8 bytes long. If it is longer, the excess will be ignored by this subroutine.
Typically, table is defined similarly to the following:
01 Table-Arg.
05 Each-Byte OCCURS 8 TIMES USAGE BINARY-CHAR.
X"F5"
X"F5" Built-In Subroutine Syntax
=======================================================================
CALL X"F5" USING byte, table
~~~~ ~~~~~
=======================================================================
This routine unpacks each bit of the single-byte data item <byte> into the low-order (rightmost) bit of each of the corresponding eight 1-byte items in <table>. The other seven bit positions of each of the first eight entries in <table> will be set to zero.
The <byte> data item need be only a single byte in size. If it is longer, the excess will be unaffected by this subroutine.
The <table> data item must be at least 8 bytes long. If it is longer, the excess will be ignored by this subroutine.
Typically, table is defined similarly to the following:
01 Table-Arg.
05 Each-Byte OCCURS 8 TIMES USAGE BINARY-CHAR.
Footnotes
Say what? the discussion and code seem to have diverged.↩︎