C H A P T E R 1 |
Fortran Library Routines |
This chapter describes the Fortran library routines.
All the routines described in this chapter have corresponding man pages in section 3F of the man library. For example, man -s 3F access will display the man page entry for the library routine access.
This chapter does not describe the standard Fortran 95 intrinsic routines. See the relevant Fortran 95 standards documents for information on intrinsics.
See also the Numerical Computation Guide for additional math routines that are callable from Fortran and C. These include the standard math library routines in libm and libsunmath (see Intro(3M)), optimized versions of these libraries, the SPARC vector math library, libmvec, and others.
See Chapter 3 for details on Fortran 77 and VMS intrinsic functions implemented by the f95 compiler.
Unless otherwise indicated, the function routines listed here are not intrinsics. That means that the type of data a function returns may conflict with the implicit typing of the function name, and require explicit type declaration by the user. For example, getpid() returns INTEGER*4 and would require an INTEGER*4 getpid declaration to ensure proper handling of the result. (Without explicit typing, a REAL result would be assumed by default because the function name starts with g.) As a reminder, explicit type statements appear in the function summaries for these routines.
Be aware that IMPLICIT statements and the -dbl and -xtypemap compiler options also alter the data typing of arguments and the treatment of return values. A mismatch between the expected and actual data types in calls to these library routines could cause unexpected behavior. Options -xtypemap and -dbl promote the data type of INTEGER functions to INTEGER*8, REAL functions to REAL*8, and DOUBLE functions to REAL*16. To protect against these problems, function names and variables appearing in library calls should be explicitly typed with their expected sizes, as in:
integer*4 seed, getuid real*4 ran ... seed = 70198 val = getuid() + ran(seed) ... |
Explicit typing in the example protects the library calls from any data type promotion when the -xtypemap and -dbl compiler options are used. Without explicit typing, these options could produce unexpected results. See the Fortran User's Guide and the f95(1) man page for details on these options.
The Fortran 95 compiler, f95, provides an include file, system.inc, that defines the interfaces for most non-intrinsic library routines. Include this file to insure that functions you call and their arguments are properly typed, especially when default data types are changed with -xtypemap.
include 'system.inc' integer(4) mypid mypid = getpid() print *, mypid |
You can catch many issues related to type mismatches over library calls by using the Fortran compilers' global program checking option, -Xlist. Global program checking by the f95 compiler is described in the Fortran User's Guide, the Fortran Programming Guide, and the f95(1) man page.
Compiling a program to run in a 64-bit operating environment (that is, compiling with -xarch=v9, v9a, or v9b and running the executable on a SPARC platform running the 64-bit enabled Solaris operating environment) changes the return values of certain functions. These are usually functions that interface standard system-level routines, such as malloc(3F) (see malloc, malloc64, realloc, free: Allocate/Reallocate/Deallocate Memory), and may take or return 32-bit or 64-bit values depending on the environment. To provide portability of code between 32-bit and 64-bit environments, 64-bit versions of these routines have been provided that always take and/or return 64-bit values. The following table identifies library routine provided for use in 64-bit environments:
The following functions and subroutines are part of the Fortran math libraries. They are available to all programs compiled with f95. These routines are non-intrinsics that take a specific data type as an argument and return the same. Non-intrinsics do have to be declared in the routine referencing them.
Many of these routines are "wrappers", Fortran interfaces to routines in the C language library, and as such are non-standard Fortran. They include IEEE recommended support functions, and specialized random number generators. See the Numerical Computation Guide and the man pages libm_single(3F), libm_double(3F), libm_quadruple(3F), for more information about these libraries.
These subprograms are single-precision math functions and subroutines.
In general, the functions below provide access to single-precision math functions that do not correspond to standard Fortran generic intrinsic functions--data types are determined by the usual data typing rules.
These functions need not be explicitly typed with a REAL statement as long as default typing holds. (Names beginning with "r" are REAL, with "i" are INTEGER.)
For details on these routines, see the C math library man pages (3M). For example, for r_acos(x) see the acos(3M) man page.
See also: intro(3M) and the Numerical Computation Guide.
The following subprograms are double-precision math functions and subroutines.
In general, these functions do not correspond to standard Fortran generic intrinsic functions--data types are determined by the usual data typing rules.
These DOUBLE PRECISION functions need to appear in a DOUBLE PRECISION statement.
Refer to the C library man pages for details: the man page for d_acos(x) is acos(3M)
See also: intro(3M) and the Numerical Computation Guide.
These subprograms are quadruple-precision (REAL*16) math functions and subroutines.
In general, these do not correspond to standard generic intrinsic functions; data types are determined by the usual data typing rules.
The quadruple precision functions must appear in a REAL*16 statement
If you need to use any other quadruple-precision libm function, you can call it using $PRAGMA C(fcn) before the call. For details, see the chapter on the C-Fortran interface in the Fortran Programming Guide.
call abort |
abort flushes the I/O buffers and then aborts the process, possibly producing a core file memory dump in the current directory. See limit(1) about limiting or suppressing core dumps.
access determines if you can access the file name with the permissions specified by mode. access returns zero if the access specified by mode would be successful. See also gerror(3F) to interpret error codes.
Set mode to one or more of r, w, x, in any order or combination, or blank, where r, w, x have the following meanings:
Example 1: Test for read/write permission:
INTEGER*4 access, status status = access ( 'taccess.data', 'rw' ) if ( status .eq. 0 ) write(*,*) "ok" if ( status .ne. 0 ) write(*,*) 'cannot read/write', status |
Example 2: Test for existence:
INTEGER*4 access, status status = access ( 'taccess.data', ' ' ) ! blank mode if ( status .eq. 0 ) write(*,*) "file exists" if ( status .ne. 0 ) write(*,*) 'no such file', status |
Subprogram to execute must be listed in an external statement. |
|||
Example: alarm--wait 9 seconds then call sbrtn:
See also: alarm(3C), sleep(3F), and signal(3F). Note the following restrictions:
Tests bit bitnum in word and returns .true. if the bit is 1, .false. if it is 0. |
|
Sets bit bitnum in word to 1 if state is nonzero, and clears it otherwise. |
The alternate external versions for MIL-STD-1753 are:
See also mvbits: Move a Bit Field, and Chapters 2 and 3 for other functions that manipulate bit fields.
word, word1, word2, nbits are integer input arguments. These are intrinsic functions expanded inline by the compiler. The data type returned is that of the first argument.
No test is made for a reasonable value of nbits.
For the subroutines and functions
bitnum, state, and word are INTEGER*4 input arguments. Function bit() returns a logical value.
Bits are numbered so that bit 0 is the least significant bit, and bit 31 is the most significant.
bic, bis, and setbit are external subroutines. bit is an external function.
Example 3: bic, bis, setbit, bit:
Example: chdir--change cwd to MyDir:
INTEGER*4 chdir, n n = chdir ( 'MyDir' ) if ( n .ne. 0 ) stop 'chdir: error' end |
See also: chdir(2), cd(1), and gerror(3F) to interpret error codes.
Path names can be no longer than MAXPATHLEN as defined in <sys/param.h>. They can be relative or absolute paths.
Use of this function can cause inquire by unit to fail.
Certain Fortran file operations reopen files by name. Using chdir while doing I/O can cause the runtime system to lose track of files created with relative path names. including the files that are created by open statements without file names.
Example: chmod--add write permissions to MyFile:
character*18 name, mode INTEGER*4 chmod, n name = 'MyFile' mode = '+w' n = chmod( name, mode ) if ( n .ne. 0 ) stop 'chmod: error' end |
See also: chmod(1), and gerror(3F) to interpret error codes.
Path names cannot be longer than MAXPATHLEN as defined in <sys/param.h>. They can be relative or absolute paths.
The form of the returned string c is dd-mmm-yy, where dd is the day of the month as a 2-digit number, mmm is the month as a 3-letter abbreviation, and yy is the year as a 2-digit number (and is not year 2000 safe!).
See also idate() and date_and_time().
This is a Fortran 95 intrinsic routine, and is Year 2000 safe.
The date_and_time subroutine returns data from the real-time clock and the date. Local time is returned, as well as the difference between local time and Universal Coordinated Time (UTC) (also known as Greenwich Mean Time, GMT).
The date_and_time() subroutine is called by:
The eight values returned in the INTEGER*4 values array are
An example using date_and_time:
When run on a computer in California, USA on February 16, 2000, it generated the following output:
Both functions have return values of elapsed time (or -1.0 as error indicator).
The time returned is in seconds.
Versions of dtime and etime used by Fortran 95 use the system's low resolution clock by default. The resolution is one hundreth of a second. However, if the program is run under the Sun OS operating system utility ptime(1), (/usr/proc/bin/ptime), the high resolution clock is used.
For dtime, the elapsed time is:
Note - Calling dtime from within a parallelized loop gives non-deterministic results, since the elapsed time counter is global to all threads participating in the loop |
e= -1.0: Error: tarray values are undefined e -1.0: User time in tarray(1) if no error. System time in tarray(2) if no error |
|||
Example: dtime(), single processor:
For etime, the elapsed time is:
The runtime library determines that a program is executing in a multiprocessor mode if either the PARALLEL or OMP_NUM_THREADS environment variables are defined to some integer value greater than 1.
e= -1.0: Error: tarray values are undefined. e -1.0: Single Processor: User time in tarray(1). System time in tarray(2) Multiple Processor: Wall clock time in tarray(1), 0.0 in tarray(2) |
|||
Take note that the initial call to etime will be inaccurate. It merely enables the system clock. Do not use the value returned by the initial call to etime.
Example: etime(), single processor:
See also times(2), and the Fortran Programming Guide.
... if(dx .lt. 0.) call exit( 0 ) ... end |
exit flushes and closes all the files in the process, and notifies the parent process if it is executing a wait.
The low-order 8 bits of status are available to the parent process. These 8 bits are shifted left 8 bits, and all other bits are zero. (Therefore, status should be in the range of 256 - 65280). This call will never return.
The C function exit can cause cleanup actions before the final system 'exit'.
Calling exit without an argument causes a compile-time warning message, and a zero will be automatically provided as an argument. See also: exit(2), fork(2), fork(3F), wait(2), wait(3F).
The subroutine or function is called by:
If used as a function, the calling routine must define the type and size of fdate. |
|||
Example 1: fdate as a subroutine:
character*24 string call fdate( string ) write(*,*) string end |
Wed Aug 3 15:30:23 1994 |
Example 2: fdate as a function, same output:
character*24 fdate write(*,*) fdate() end |
See also: ctime(3), time(3F), and idate(3F).
The flush function flushes the contents of the buffer for the logical unit, lunit, to the associated file. This is most useful for logical units 0 and 6 when they are both associated with the console terminal. The function returns a positive error number if an error was encountered; zero otherwise.
The fork function creates a copy of the calling process. The only distinction between the two processes is that the value returned to one of them, referred to as the parent process, will be the process ID of the copy. The copy is usually referred to as the child process. The value returned to the child process will be zero.
All logical units open for writing are flushed before the fork to avoid duplication of the contents of I/O buffers in the external files.
INTEGER*4 fork, pid pid = fork() if(pid.lt.0) stop 'fork error' if(pid.gt.0) then print *, 'I am the parent' else print *, 'I am the child' endif |
A corresponding exec routine has not been provided because there is no satisfactory way to retain open logical units across the exec routine. However, the usual function of fork/exec can be performed using system(3F). See also: fork(2), wait(3F), kill(3F), system(3F), and perror(3F).
fseek and ftell are routines that permit repositioning of a file. ftell returns a file's current position as an offset of so many bytes from the beginning of the file. At some later point in the program, fseek can use this saved offset value to reposition the file to that same place for reading.
Example: fseek()--Reposition MyFile to two bytes from the beginning:
INTEGER*4 fseek, lunit/1/, offset/2/, from/0/, n open( UNIT=lunit, FILE='MyFile' ) n = fseek( lunit, offset, from ) if ( n .gt. 0 ) stop 'fseek error' end |
Example: Same example in a 64-bit environment and compiled with -xarch=v9:
INTEGER*4 fseek, lunit/1/, from/0/, n INTEGER*8 offset/2/ open( UNIT=lunit, FILE='MyFile' ) n = fseek( lunit, offset, from ) if ( n .gt. 0 ) stop 'fseek error' end |
INTEGER*4 ftell, lunit/1/, n open( UNIT=lunit, FILE='MyFile' ) ... n = ftell( lunit ) if ( n .lt. 0 ) stop 'ftell error' ... |
Example: Same example in a 64-bit environment and compiled with -xarch=v9:
INTEGER*4 lunit/1/ INTEGER*8 ftell, n open( UNIT=lunit, FILE='MyFile' ) ... n = ftell( lunit ) if ( n .lt. 0 ) stop 'ftell error' ... |
See also fseek(3S) and perror(3F); also fseeko64(3F) ftello64(3F).
fseeko64 and ftello64 are "large file" versions of fseek and ftell. They take and return INTEGER*8 file position offsets. (A "large file" is larger than 2 Gigabytes and therefore a byte-position must be represented by a 64-bit integer.) Use these versions to determine and/or reposition large files.
64-bit offset in bytes relative to position specified by from |
|||
Example: fseeko64()--Reposition MyFile to two bytes from the beginning:
INTEGER fseeko64, lunit/1/, from/0/, n INTEGER*8 offset/200/ open( UNIT=lunit, FILE='MyFile' ) n = fseeko64( lunit, offset, from ) if ( n .gt. 0 ) stop 'fseek error' end |
INTEGER*8 ftello64, lunit/1/, n open( UNIT=lunit, FILE='MyFile' ) ... n = ftello64( lunit ) if ( n .lt. 0 ) stop 'ftell error' ... |
getarg and iargc access arguments on the command line (after expansion by the command-line preprocessor.
Example: iargc and getarg, get argument count and each argument:
demo% cat yarg.f character argv*10 INTEGER*4 i, iargc, n n = iargc() do 1 i = 1, n call getarg( i, argv ) 1 write( *, '( i2, 1x, a )' ) i, argv end demo% f95 yarg.f demo% a.out *.f 1 first.f 2 yarg.f |
See also execve(2) and getenv(3F).
getc and fgetc get the next character from the input stream. Do not mix calls to these routines with normal Fortran I/O on the same logical unit.
Example: getc gets each character from the keyboard; note the Control-D (^D):
character char INTEGER*4 getc, status status = 0 do while ( status .eq. 0 ) status = getc( char ) write(*, '(i3, o4.3)') status, char end do end |
After compiling, a sample run of the above source is:
For any logical unit, do not mix normal Fortran input with getc().
Example: fgetc gets each character from tfgetc.data; note the linefeeds (Octal 012):
character char INTEGER*4 fgetc, status open( unit=1, file='tfgetc.data' ) status = 0 do while ( status .eq. 0 ) status = fgetc( 1, char ) write(*, '(i3, o4.3)') status, char end do end |
After compiling, a sample run of the above source is:
demo% cat tfgetc.data ab yz demo% a.out 0 141 `a' read 0 142 `b' read 0 012 linefeed read 0 171 `y' read 0 172 `z' read 0 012 linefeed read -1 012 CONTROL-D read demo% |
For any logical unit, do not mix normal Fortran input with fgetc().
See also: getc(3S), intro(2), and perror(3F).
Path name of the current working directory. n must be large enough for longest path name |
|||
INTEGER*4 getcwd, status character*64 dirname status = getcwd( dirname ) if ( status .ne. 0 ) stop 'getcwd: error' write(*,*) dirname end |
See also: chdir(3F), perror(3F), and getwd(3).
Note: the path names cannot be longer than MAXPATHLEN as defined in <sys/param.h>.
Value of the environment variable found; blanks if not successful |
The size of ename and evalue must be large enough to hold their respective character strings.
If evalue is too short to hold the complete string value, the string is truncated to fit in evalue.
The getenv subroutine searches the environment list for a string of the form ename=evalue and returns the value in evalue if such a string is present; otherwise, it fills evalue with blanks.
Example: Use getenv() to print the value of $SHELL:
character*18 evalue call getenv( 'SHELL', evalue ) write(*,*) "'", evalue, "'" end |
See also: execve(2) and environ(5).
File descriptor if file is connected;
|
INTEGER*4 fildes, getfd, unitn/1/ open( unitn, file='tgetfd.data' ) fildes = getfd( unitn ) if ( fildes .eq. -1 ) stop 'getfd: file not connected' write(*,*) 'file descriptor = ', fildes end |
File pointer if the file is connected; -1 if the file is not connected.
|
This function is used for mixing standard Fortran I/O with C I/O. Such a mix is nonportable, and is not guaranteed for subsequent releases of the operating system or Fortran. Use of this function is not recommended, and no direct interface is provided. You must create your own C routine to use the value returned by getfilep. A sample C routine is shown below.
Example: Fortran uses getfilep by passing it to a C function:
Sample C function actually using getfilep:
demo% cat tgetfilepC.c #include <stdio.h> int c_read_ ( fd, buf, nbytes, buf_len ) FILE **fd ; char *buf ; int *nbytes, buf_len ; { return fread( buf, 1, *nbytes, *fd ) ; } |
A sample compile-build-run is:
demo% cc -c tgetfilepC.c demo% f95 tgetfilepC.o tgetfilepF.f demo% a.out What is the digit? 3 The digit read by C is 3 demo% |
For more information, read the chapter on the C-Fortran interface in the Fortran Programming Guide. See also open(2).
User's login name, or all blanks if the process is running detached from a terminal. n should be large enough to hold the longest name. |
character*18 name call getlog( name ) write(*,*) "'", name, "'" end |
INTEGER*4 getpid, pid pid = getpid() write(*,*) 'process id = ', pid end |
getuid and getgid get the user or group ID of the process, respectively.
Example: getuid() and getpid():
INTEGER*4 getuid, getgid, gid, uid uid = getuid() gid = getgid() write(*,*) uid, gid end |
Name of current host system. n must be large enough to hold the host name. |
|||
INTEGER*4 hostnm, status character*8 name status = hostnm( name ) write(*,*) 'host name = "', name, '"' end |
idate puts the current system date into one integer array: day, month, and year.
Example: idate (standard version):
demo% cat tidate.f INTEGER*4 iarray(3) call idate( iarray ) write(*, "(' The date is: ',3i5)" ) iarray end demo% f95 tidate.f demo% a.out The date is: 10 8 1998 demo% |
These subprograms provide modes and status required to fully exploit ANSI/IEEE Standard 754-1985 arithmetic in a Fortran program. They correspond closely to the functions ieee_flags(3M), ieee_handler(3M), and sigfpe(3).
See the Sun Numerical Computation Guide for details on how these functions can be used strategically.
If you use sigfpe, you must do your own setting of the corresponding trap-enable-mask bits in the floating-point status register. The details are in the SPARC architecture manual. The libm function ieee_handler sets these trap-enable-mask bits for you.
The character keywords accepted for mode and exception depend on the value of action.
set user exception handing of in; out is address of handler routine, or SIGFPE_DEFAULT, or SIGFPE_ABORT, or SIGFPE_IGNORE defined in |
Example 1: Set rounding direction to round toward zero, unless the hardware does not support directed rounding modes:
INTEGER*4 ieeer character*1 mode, out, in ieeer = ieee_flags( 'set', 'direction', 'tozero', out ) |
Example 2: Clear rounding direction to default (round toward nearest):
character*1 out, in ieeer = ieee_flags('clear','direction', in, out ) |
Example 3: Clear all accrued exception-occurred bits:
character*18 out ieeer = ieee_flags( 'clear', 'exception', 'all', out ) |
Example 4: Detect overflow exception as follows:
character*18 out ieeer = ieee_flags( 'get', 'exception', 'overflow', out ) if (out .eq. 'overflow' ) stop 'overflow' |
The above code sets out to overflow and ieeer to 25 (this value is platform dependent). Similar coding detects exceptions, such as invalid or inexact.
Example 5: hand1.f, write and use a signal handler:
Change the declarations for address and function hand to INTEGER*8 to enable Example 5 in a 64-bit, SPARC V9 environment (-xarch=v9)
See the Numerical Computation Guide. See also: floatingpoint(3), signal(3), sigfpe(3), floatingpoint(3F), ieee_flags(3M), and ieee_handler(3M).
The header file floatingpoint.h defines constants and types used to implement standard floating-point according to ANSI/IEEE Std 754-1985.
Include the file in a Fortran 95 source program as follows:
#include "floatingpoint.h" |
Use of this include file requires preprocessing prior to Fortran compilation. The source file referencing this include file will automatically be preprocessed if the name has a .F, .F90 or .F95 extension.
The type of the IEEE rounding direction mode. The order of enumeration varies according to hardware. |
A list of the classes of IEEE floating-point values and symbols. |
Refer to the Numerical Computation Guide. See also ieee_environment(3F).
These functions search through a character string:
index has the following forms:
The index is an intrinsic function called by:
If declared INTEGER*8, index() will return an INTEGER*8 value when compiled for a 64-bit environment and character variable a1 is a very large character string (greater than 2 Gigabytes).
n>0: Index of last occurrence of a2 in a1 n=0: a2 does not occur in a1
|
n>0: Index of last nonblank in a1 n=0: a1 is all nonblank
|
Example: index(), rindex(), lnblnk():
Note - Programs compiled to run in a 64-bit environment must declare index, rindex and lnblnk (and their receiving variables) INTEGER*8 to handle very large character strings. |
demo% cat tinmax.f INTEGER*4 inmax, m m = inmax() write(*,*) m end demo% f95 tinmax.f demo% a.out 2147483647 demo% |
See also libm_single(3F) and libm_double(3F). See also the non-standard FORTRAN 77 intrinsic function ephuge() described in Chapter 3.
itime puts the current system time into an integer array: hour, minute, and second. The subroutine is called by:
demo% cat titime.f INTEGER*4 iarray(3) call itime( iarray ) write (*, "(' The time is: ',3i5)" ) iarray end demo% f95 titime.f demo% a.out The time is: 15 42 35 |
See also time(3F), ctime(3F), and fdate(3F).
Example (fragment): Send a message using kill():
INTEGER*4 kill, pid, signum * ... status = kill( pid, signum ) if ( status .ne. 0 ) stop 'kill: error' write(*,*) 'Sent signal ', signum, ' to process ', pid end |
The function sends signal signum, and integer signal number, to the process pid. Valid signal numbers are listed in the C include file /usr/include/sys/signal.h
See also: kill(2), signal(3), signal(3F), fork(3F), and perror(3F).
link creates a link to an existing file. symlink creates a symbolic link to an existing file.
Example 1: link: Create a link named data1 to the file, tlink.db.data.1:
Example 2: symlnk: Create a symbolic link named data1 to the file, tlink.db.data.1:
See also: link(2), symlink(2), perror(3F), and unlink(3F).
Note: the path names cannot be longer than MAXPATHLEN as defined in <sys/param.h>.
This intrinsic function is called by:
Returns an INTEGER*8 pointer when compiled to run in a 64-bit environment with -xarch=v9. See Note below. |
INTEGER*4 k, loc real arg / 9.0 / k = loc( arg ) write(*,*) k end |
Note - Programs compiled to run in a 64-bit environment should declare INTEGER*8 the variable receiving output from the loc() function. |
long and short handle integer object conversions between INTEGER*4 and INTEGER*2, and is especially useful in subprogram call lists.
Example (fragment): long() and short():
integer*4 int4/8/, long integer*2 int2/8/, short call ExpecLong( long(int2) ) call ExpecShort( short(int4) ) ... end |
ExpecLong is some subroutine called by the user program that expects a long (INTEGER*4) integer argument. Similarly, ExpecShort expects a short (INTEGER*2) integer argument.
long is useful if constants are used in calls to library routines and the code is compiled with the -i2 option.
short is useful in similar context when an otherwise long object must be passed as a short integer. Passing an integer to short that is too large in magnitude does not cause an error, but will result in unexpected behavior.
isetjmp sets a location for longjmp; longjmp returns to that location.
This intrinsic function is called by:
env is a 12-element integer array.
|
|||
env is the 12-word integer array initialized by isetjmp.
|
|||
The isetjmp and longjmp routines are used to deal with errors and interrupts encountered in a low-level routine of a program. They are f95 intrinsics.
These routines should be used only as a last resort. They require discipline, and are not portable. Read the man page, setjmp(3V), for bugs and other details.
isetjmp saves the stack environment in env. It also saves the register environment.
longjmp restores the environment saved by the last call to isetjmp, and returns in such a way that execution continues as if the call to isetjmp had just returned the value ival.
The integer expression ival returned from isetjmp is zero if longjmp is not called, and nonzero if longjmp is called.
Example: Code fragment using isetjmp and longjmp:
The functions malloc(), malloc64(), and realloc() allocate blocks of memory and return the starting address of the block. The return value can be used to set an INTEGER or Cray-style POINTER variable. realloc() reallocates an existing memory block with a new size. free() deallocates memory blocks allocated by malloc(), malloc64(), or realloc().
Standard-conforming Fortran 95 programs should use ALLOCATE and DEALLOCATE statements on ALLOCATABLE arrays to perform dynamic memory management, and not make direct calls to malloc/realloc/free.
Legacy Fortran 77 programs could use malloc()/malloc64() to assign values to Cray-style POINTER variables, which have the same data representation as INTEGER variables. Cray-style POINTER variables are implemented in f95 to support portability from Fortran 77.
The malloc() function is called by:
k>0: k = address of the start of the block of memory allocated |
|||
An INTEGER*8 pointer value is returned when compiled for a 64-bit environment with -xarch=v9. See Note below. |
k>0: k=address of the start of the block of memory allocated |
These functions allocate an area of memory and return the address of the start of that area. (In a 64-bit environment, this returned byte address may be outside the INTEGER*4 numerical range--the receiving variables must be declared INTEGER*8 to avoid truncation of the memory address.) The region of memory is not initialized in any way, and it should not be assumed to be preset to anything, especially zero!
Example: Code fragment using malloc():
parameter (NX=1000) integer ( p2X, X ) real*4 X(1) ... p2X = malloc( NX*4 ) if ( p2X .eq. 0 ) stop 'malloc: cannot allocate' do 11 i=1,NX 11 X(i) = 0. ... end |
In the above example, we acquire 4,000 bytes of memory, pointed to by p2X, and initialize it to zero.
The realloc() f95 intrinsic function is called by:
The realloc() function changes the size of the memory block pointed to by ptr to n bytes and returns a pointer to the (possibly moved) new block. The contents of the memory block will be unchanged up to the lesser of the new and old sizes.
If ptr is zero, realloc() behaves the same as malloc() and allocates a new memory block of size n bytes.
If n is zero and ptr is not zero, the memory block pointed to is made available for further allocation and is returned to the system only upon termination of the application.
Example: Using malloc() and realloc() and Cray-style POINTER variables:
Note that realloc() is only implemented for f95.
free deallocates a region of memory previously allocated by malloc and realloc(). The region of memory is returned to the memory manager; it is no longer available to the user's program.
real x pointer ( ptr, x ) ptr = malloc ( 10000 ) call free ( ptr ) end |
These routines perform the following functions:
Get a system error message (of the last detected system error) |
|
The message. It is written preceding the standard error message for the last detected system error. |
call perror( "file is for formatted I/O" ) |
The subroutine or function is called by:
Example 2: gerror() as a subroutine:
character string*30 ... call gerror ( string ) write(*,*) string |
Example 3: gerror() as a function; string not used:
character gerror*30, z*30 ... z = gerror( ) write(*,*) z |
This number is updated only when an error actually occurs. Most routines and I/O statements that might generate such errors return an error code after the call; that value is a more reliable indicator of what caused the error condition.
INTEGER*4 ierrno, n ... n = ierrno() write(*,*) n |
See also intro(2) and perror(3).
putc writes to logical unit 6, normally the control terminal output.
fputc writes to a logical unit.
These functions write a character to the file associated with a Fortran logical unit bypassing normal Fortran I/O.
Do not mix normal Fortran output with output by these functions on the same unit.
Note that to write any of the special \ escape characters, such as '\n' newline, requires compiling with -f77=backslash FORTRAN 77 compatibility option.
See also putc(3S), intro(2), and perror(3F).
Size of an element, typically: |
|||
Size of an element, typically: |
|||
Use qsort64 in 64-bit environments with arrays larger than 2 Gbytes. Be sure to specify the array length, len8, and the element size, isize8, as INTEGER*8 data. Use the Fortran 95 style constants to explicitly specify INTEGER*8 constants.
The compar(arg1, arg2) arguments are elements of array, returning:
Repeated calls to ran generate a sequence of random numbers with a uniform distribution. See lcrans(3m).
SEED = 6909 * SEED + 1 (MOD 2**32) |
rand returns real values in the range 0.0 through 1.0.
drand returns double precision values in the range 0.0 through 1.0.
irand returns positive integers in the range 0 through 2147483647.
These functions use random(3) to generate sequences of random numbers. The three functions share the same 256 byte state array. The only advantage of these functions is that they are widely available on UNIX systems. For better random number generators, compare lcrans, addrans, and shufrans. See also random(3), and the Numerical Computation Guide
k=0: Get next random number in the sequence k=1: Restart sequence, return first number |
|||
demo% cat trand.f integer*4 v(5), iflag/0/ do i = 1, 5 v(i) = irand( iflag ) end do write(*,*) v end demo% f95 trand.f demo% a.out 2078917053 143302914 1027100827 1953210302 755253631 demo% |
If the file specified by to exists, then both from and to must be the same type of file, and must reside on the same file system. If to exists, it is removed first.
Example: rename()--Rename file trename.old to trename.new
See also rename(2) and perror(3F).
Note: the path names cannot be longer than MAXPATHLEN as defined in <sys/param.h>.
set_io_err_handler() declares a user-defined routine to be called whenever errors are detected on a specified input logical unit.
get_io_err_handler() returns the address of the currently declared error handling routine.
These routines are module subroutines and can only be accessed when USE SUN_IO_HANDLERS appears in the calling routine.
SET_IO_ERR_HANDLER sets the user-supplied subroutine subr_name to be used as the I/O error handler for the logical unit iu when an input error occurs. iu has to be a connected Fortran logical unit for a formatted file. istat will be set to a non-zero value if there is an error, otherwise it is set to zero.
For example, if SET_IO_ERR_HANDLER is called before the logical unit iu has been opened, istat will be set to 1001 ("Illegal Unit"). If subr_name is NULL user error-handling is turned off and the program reverts to default Fortran error handling.
Use GET_IO_ERR_HANDLER to get the address of the function currently being used as the error handler for this logical unit. For example, call GET_IO_ERR_HANDLER to save the current I/O before switching to another handler routine. The error handler can be restored with the saved value later.
subr_name is the name of the user-supplied routine to handle the I/O error on logical unit iu. The runtime I/O library passes all relevant information to subr_name, enabling this routine to diagnose the problem and possibly fix the error before continuing.
The interface to the user-supplied error handler routine is as follows:
The I/O handler can only replace once character with another character. It cannot replace one character with more than one character.
The error recovery algorithm can only fix a bad character it currently reads, not a bad character which has already been interpreted as a valid character in a different context. For example,in a list-directed read, if the input is "1.234509.8765" when the correct input should be "1.2345 9.8765" then the I/O library will run into an error at the second period because it is not a valid number. But, by that time, it is not possible to go back and change the '0' into a blank.
Currently, this error-handling capability does not work for namelist-directed input. When doing namelist-directed input, the specified I/O error handler will not be invoked when an error occurs.
I/O error handlers can only be set for external files, not internal files, because there are no logical units associated with internal files.
The I/O error handler is called only for syntactic errors, not system errors or semantic errors(such as an overflowed input value).
It is possible to have an infinite loop if the user-supplied I/O error handler keeps providing a bad character to the I/O library, causing it to call the user-supplied I/O error handler over and over again. If an error keeps occuring at the same file position then the error handler should terminate itself. One way to do this is to take the default error path by setting CORR_ACTION to 0. Then the I/O library will continue with the normal error handling.
Exit status of the shell executed. See wait(2) for an explanation of this value. |
character*18 string / 'ls > MyOwnFile.names' / INTEGER*4 status, sh status = sh( string ) if ( status .ne. 0 ) stop 'sh: error' ... end |
The function sh passes string to the sh shell as input, as if the string had been typed as a command.
The current process waits until the command terminates.
The forked process flushes all open files:
The sh() function is not MT-safe. Do not call it from multithreaded or parallelized programs.
See also: execve(2), wait(2), and system(3).
Note: string cannot be longer than 1,024 characters.
If proc is called, it is passed the signal number as an integer argument.
If a process incurs a signal, the default action is usually to clean up and abort. A signal handling routine provides the capability of catching specific exceptions or interrupts for special processing.
The returned value can be used in subsequent calls to signal to restore a previous action definition.
You can get a negative return value even though there is no error. In fact, if you pass a valid signal number to signal(), and you get a return value less than -1, then it is OK.
floatingpoint.h defines proc values SIGFPE_DEFAULT, SIGFPE_IGNORE, and SIGFPE_ABORT. See floatingpoint.h: Fortran IEEE Definitions.
In 64-bit environments, signal must be declared INTEGER*8, along with the variables receiving its output, to avoid truncation of the address that may be returned.
See also kill(1), signal(3), and kill(3F), and Numerical Computation Guide.
The actual time can be up to 1 second less than itime due to granularity in system timekeeping.
INTEGER*4 time / 5 / write(*,*) 'Start' call sleep( time ) write(*,*) 'End' end |
These functions return the following information:
Both stat and lstat query by file name. fstat queries by logical unit.
The meaning of the information returned in the INTEGER*4 array statb is as described for the structure stat under stat(2).
Spare values are not included. The order is shown in the following table:
Number of hard links to the file Device type, for inode that is device |
See also stat(2), access(3F), perror(3F), and time(3F).
Note: the path names can be no longer than MAXPATHLEN as defined in <sys/param.h>.
64-bit "long file" versions of stat, lstat, fstat. These routines are identical to the non-64-bit routines, except that the 13-element array statb must be declared INTEGER*8.
Exit status of the shell executed. See wait(2) for an explanation of this value. |
character*8 string / 'ls s*' / INTEGER*4 status, system status = system( string ) if ( status .ne. 0 ) stop 'system: error' end |
The function system passes string to your shell as input, as if the string had been typed as a command. Note: string cannot be longer than 1024 characters.
If system can find the environment variable SHELL, then system uses the value of SHELL as the command interpreter (shell); otherwise, it uses sh(1).
The current process waits until the command terminates.
Historically, cc developed with different assumptions:
The system function flushes all open files:
See also: execve(2), wait(2), and system(3).
The system() function is not MT-safe. Do not call it from multithreaded or parallelized programs.
These routines have the following functions:
Standard version: Get system time as integer (seconds since 0 GMT 1/1/70) |
|
Dissect a system time into month, day, and so forth, local time. |
|
The time() function is called by:
The function time() returns an integer with the time since 00:00:00 GMT,
January 1, 1970, measured in seconds. This is the value of the operating system clock.
Example: time(), version standard with the operating system:
demo% cat ttime.f INTEGER*4 n, time n = time() write(*,*) 'Seconds since 0 1/1/70 GMT = ', n end demo% f95 ttime.f demo% a.out Seconds since 0 1/1/70 GMT = 913240205 demo% |
The function ctime converts a system time, stime, and returns it as a 24-character ASCII string.
System time as character string. Declare ctime and string as character*24. |
The format of the ctime returned value is shown in the following example. It is described in the man page ctime(3C).
demo% cat tctime.f character*24 ctime, string INTEGER*4 n, time n = time() string = ctime( n ) write(*,*) 'ctime: ', string end demo% f95 tctime.f demo% a.out ctime: Wed Dec 9 13:50:05 1998 demo% |
This routine dissects a system time into month, day, and so forth, for the local time zone.
For the meaning of the elements in tarray, see the next section.
demo% cat tltime.f integer*4 stime, tarray(9), time stime = time() call ltime( stime, tarray ) write(*,*) 'ltime: ', tarray end demo% f95 tltime.f demo% a.out ltime: 25 49 10 12 7 91 1 223 1 demo% |
This routine dissects a system time into month, day, and so on, for GMT.
Here are the tarray() values for ltime and gmtime: index, units, and range:
These values are defined by the C library routine ctime(3C), which explains why the system may return a count of seconds greater than 59. See also: idate(3F), and fdate(3F).
These are versions of the corresponding routines ctime, gmtime, and ltime, to provide portability on 64-bit environments. They are identical to these routines except that the input variable stime must be INTEGER*8.
When used in a 32-bit environment with an INTEGER*8 stime, if the value of stime is beyond the INTEGER*4 range ctime64 returns all asterisks, while gmtime and ltime fill the tarray array with -1.
ttynam and isatty handle terminal port names.
The function ttynam returns a blank padded path name of the terminal device associated with logical unit lunit.
The function isatty returns true or false depending on whether or not logical unit lunit is a terminal device or not.
Example: Determine if lunit is a tty:
character*12 name, ttynam INTEGER*4 lunit /5/ logical*4 isatty, terminal terminal = isatty( lunit ) name = ttynam( lunit ) write(*,*) 'terminal = ', terminal, ', name = "', name, '"' end |
terminal = T, name = "/dev/ttyp1 " |
The function unlink removes the file specified by path name patnam. If this is the last link to the file, the contents of the file are lost.
Example: unlink()--Remove the tunlink.data file:
demo% cat tunlink.f call unlink( 'tunlink.data' ) end demo% f95 tunlink.f demo% ls tunl* tunlink.f tunlink.data demo% a.out demo% ls tunl* tunlink.f |
See also: unlink(2), link(3F), and perror(3F). Note: the path names cannot be longer than MAXPATHLEN as defined in <sys/param.h>.
wait suspends the caller until a signal is received, or one of its child processes terminates. If any child has terminated since the last wait, return is immediate. If there are no children, return is immediate with an error code.
Copyright © 2003, Sun Microsystems, Inc. All rights reserved.