Fortran Library Reference |
Fortran Library Routines
This chapter describes the Fortran library routines alphabetically. See the FORTRAN 77 Language Reference for details on Fortran 77 and VMS intrinsic functions. 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 routineaccess
.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
andlibsunmath
(seeIntro
(3M)), optimized versions of these libraries, the SPARC vector math library,libmvec
, and others.Data Type Considerations
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()
returnsINTEGER*4
and would require anINTEGER*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 withg
.) As a reminder, explicit type statements appear in the function summaries for these routines.Be aware that
IMPLICIT
statements and the-r8
,-i2
,-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-r8
and-dbl
promote the data type ofINTEGER
functions toINTEGER*8
,REAL
functions toREAL*8
, andDOUBLE
functions toREAL*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, getuidreal*4 ran...seed = 70198val = getuid() + ran(seed)...Explicit typing in the example protects the library calls from any data type promotion when the
-r8
and-dbl
compiler options are used. Without explicit typing, these options could produce unexpected results. See the Fortran User's Guide and thef77
(1) andf95
(1) man pages for details on these options.The more flexible
-xtypemap
compiler option is recommended over the obsolete-i2,
-r8,
and-dbl
options and should be used instead.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 thef77
andf95
compilers is described in the Fortran User's Guide, the Fortran Programming Guide, and thef77
(1) andf95
(1) man pages.64-Bit Environments
Compiling a program to run in a 64-bit operating environment (that is, compiling with
-xarch=v9
orv9a
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 asmalloc
(3F) (see page 76), 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:
TABLE 1-1 Library Routines for 64-bit Environments malloc64Allocate memory and return a pointer page 76 fseeko64Reposition a large file page 40 ftello64Determine position of a large file page 40 stat64, fstat64, lstat64Determine status of a file page 95 time64,
ctime64,
gmtime64,
ltime64Get system time, convert to character or dissected page 96 qsort64Sort the elements of an array page 83
Fortran Math Functions
The following functions and subroutines are part of the Fortran math libraries. They are available to all programs compiled with
f77
andf95
. Some routines are intrinsics and return the same data type (single precision, double precision, or quad precision) as their argument. The rest are non-intrinsics that take a specific data type as an argument and return the same. These 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.Intrinsic Math Functions
Here is a list of intrinsic math functions. You need not put them in a type statement. These functions take single, double, or quad precision data as arguments and return the same.
sqrt(x) asin(x) cosd(x) log(x) acos(x) asind(x) log10(x) atan(x) acosd(x) exp(x) atan2(x,y) atand(x) x**y sinh(x) atan2d(x,y) sin(x) cosh(x) aint(x) cos(x) tanh(x) anint(x) tan(x) sind(x) nint(x)
The functions
sind(x),
cosd(x),
asind(x),
acosd(x),
atand(x), atan2d(x,y)
are not part of the Fortran standard.Single-Precision Functions
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. (Variables beginning with "r
" areREAL
, with "i
" areINTEGER
.)For details on these routines, see the C math library man pages (3M). For example, for
r_acos(x)
see theacos
(3M) man page.
- Variables
c
,l
,p
,s
,u
,x
, andy
are of typeREAL
.- Type these functions as explicitly
REAL
if anIMPLICIT
statement is in effect that types names starting with "r
" to some other date type.sind(x)
,asind(x),
... take degrees rather than radians.See also:
intro
(3M) and the Numerical Computation Guide.Double-Precision Functions
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 aDOUBLE
PRECISION
statement.Refer to the C library man pages for details: the man page for
d_acos(x)
isacos
(3M)
- Variables
c
,l
,p
,s
,u
,x
, andy
are of typeDOUBLE
PRECISION
.- Explicitly type these functions on a
DOUBLE
PRECISION
statement or with an appropriateIMPLICIT
statement).sind(x)
,asind(x),
... take degrees rather than radians.See also:
intro
(3M) and the Numerical Computation Guide.Quad-Precision Functions
These subprograms are
quadruple
-precision (REAL*16
) math functions and subroutines (SPARC only).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
- The variables
c
,l
,p
,s
,u
,x
, andy
are of type quadruple precision.- Explicitly type these functions with a
REAL*16
statement or with an appropriateIMPLICIT
statement.sind(x)
,asind(x),
... take degrees rather than radians.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.
abort
: Terminate and Write Core FileThe subroutine is called by:
call abort
abort
flushes the I/O buffers and then aborts the process, possibly producing acore
file memory dump in the current directory. Seelimit
(1) about limiting or suppressing core dumps.
access
: Check File Permissions or ExistenceThe function is called by:
INTEGER*4 access
status = access (
name, mode)
name character
Input File name mode character
Input Permissions Return value INTEGER*4
Output status=0: OK
status>0: Error code
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 alsogerror
(3F) to interpret error codes.Set mode to one or more of
r
,w
,x
,
in any order or combination, or blank, wherer
,w
,x
have the following meanings:
'r'
Test for read permission 'w'
Test for write permission 'x'
Test for execute permission ' '
Test for existence of the file
Example 1: Test for read/write permission:
INTEGER*4 access, statusstatus = access ( 'taccess.data', 'rw' )if ( status .eq. 0 ) write(*,*) "ok"if ( status .ne. 0 ) write(*,*) 'cannot read/write', statusExample 2: Test for existence:
INTEGER*4 access, statusstatus = access ( 'taccess.data', ' ' ) ! blank modeif ( status .eq. 0 ) write(*,*) "file exists"if ( status .ne. 0 ) write(*,*) 'no such file', status
alarm
: Call Subroutine After a Specified TimeThe function is called by:
Example:
alarm
--wait 9 seconds then callsbrtn
:
See also:
alarm
(3C),sleep
(3F), andsignal
(3F). Note the following restrictions:
- A subroutine cannot pass its own name to
alarm
.- The
alarm
routine generates signals that could interfere with any I/O. The called subroutine, sbrtn, must not do any I/O itself.- Calling
alarm()
from a parallelized or multi-threaded Fortran program may have unpredictable results.
bit
: Bit Functions:and
,or
, ...,bit
,setbit
, ...The definitions are:
The alternate external versions for MIL-STD-1753 are:
See also mvbits: Move a Bit Field, and the chapter on Intrinsic Functions in the FORTRAN 77 Reference Manual.
Usage:
and
,or
,xor
,not
,rshift
,lshift
For the intrinsic functions:
x= and(
word1, word2)
x= or(
word1, word2)
x= xor(
word1, word2)
x= not(
word)
x= rshift(
word, nbits)
x= lshift(
word, nbits)
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.
Example:
and, or, xor, not
:
Example:
lshift
,rshift
:
Usage:
bic
,bis
,bit
,setbit
call bic(
bitnum,
word)
call bis(
bitnum,
word)
call setbit(
bitnum,
word,
state)
LOGICAL
bit
x= bit(
bitnum,
word)
bitnum, state, and word are
INTEGER*4
input arguments. Functionbit
() 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
, andsetbit
are external subroutines.bit
is an external function.Example 3:
bic
,bis
,setbit
,bit
:
chdir
: Change Default DirectoryThe function is called by:
dirname character
Input Directory name Return value INTEGER*4
Output n=0: OK, n>0: Error code
Example:
chdir
--changecwd
toMyDir
:
INTEGER*4 chdir, nn = chdir ( 'MyDir' )if ( n .ne. 0 ) stop 'chdir: error'endSee also:
chdir
(2),cd
(1), andgerror
(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.
chmod
: Change the Mode of a FileThe function is called by:
name character
Input Path name mode character
Input Anything recognized by chmod(1), such as o-w
,444
, etc.Return value INTEGER*4
Output n = 0: OK; n>0: System error number
Example:
chmod
--add write permissions toMyFile
:
character*18 name, modeINTEGER*4 chmod, nname = 'MyFile'mode = '+w'n = chmod( name, mode )if ( n .ne. 0 ) stop 'chmod: error'endSee also:
chmod
(1), andgerror
(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.
date
: Get Current Date as a Character String
Note This routine is not "Year 2000 Safe" because it returns only a two-digit value for the year. Programs that compute differences between dates using the output of this routine may not work properly after 31 December, 1999. Programs using thisdate()
routine will see a runtime warning message the first time the routine is called to alert the user. Seedate_and_time()
as a possible alternate routine.
The subroutine is called by:
c CHARACTER*9
Output Variable, array, array element, or character substring
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!).
Example:
date
:
See also
idate()
anddate_and_time()
.
date_and_time
: Get Date and TimeThis is a FORTRAN 77 version of the 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:
dtime
,etime
: Elapsed Execution TimeBoth functions have return values of elapsed time (or -1.0 as error indicator).
The time returned is in seconds.The versions of
dtime
andetime
used by Fortran 77 return times produced by the runtime system's high resolution clock. The actual resolution depends on the system platform. The resolutions of the clocks on current platforms range between one nanosecond and one microsecond.Versions of
dtime
andetime
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 OSTM operating system utilityptime
(1), (/usr/proc/bin/ptime)
, the high resolution clock is used.
dtime
: Elapsed Time Since the Lastdtime
CallFor
dtime
, the elapsed time is:
- First call: elapsed time since start of execution
- Subsequent calls: elapsed time since the last call to
dtime
- Single processor: time used by the CPU
- Multiple Processor: the sum of times for all the CPUs, which is not useful data; use
etime
instead.
Note Callingdtime
from within a parallelized loop gives non-deterministic results, since the elapsed time counter is global to all threads participating in the loop
The function is called by:
Example:
dtime()
, single processor:
etime
: Elapsed Time Since Start of ExecutionFor
etime
, the elapsed time is:
- Single Processor--CPU time for the calling process
- Multiple Processors--wallclock time while processing your program
Here is how Fortran decides single processor or multiple processor:
For a parallelized Fortran program linked with
libF77_mt
, if the environment variablePARALLEL
is:
- Undefined, the current run is single processor.
- Defined and in the range 1, 2, 3, ..., the current run is multiple processor.
- Defined, but some value other than 1, 2, 3, ..., the results are unpredictable.
The function is called by:
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),f77
(1), and the Fortran Programming Guide.
exit
: Terminate a Process and Set the StatusThe subroutine is called by:
call exit(
status)
status INTEGER*4
Input
Example:
exit()
:
...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 await
.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).
fdate
: Return Date and Time in an ASCII StringThe subroutine or function is called by:
string character*24
Output
or:
CHARACTER fdate*24
string= fdate()
If used as a function, the calling routine must define the type and size of fdate
.Return value character*24
Output
Example 1:
fdate
as a subroutine:
character*24 stringcall fdate( string )write(*,*) stringendOutput:
Wed Aug 3 15:30:23 1994Example 2:
fdate
as a function, same output:
character*24 fdatewrite(*,*) fdate()endSee also:
ctime
(3),time
(3F), andidate
(3F).
flush
: Flush Output to a Logical UnitThe function is called by:
lunit INTEGER*4
Input Logical unit Return value INTEGER*4
Output n = 0 no error
n > 0 error number
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.
fork
: Create a Copy of the Current ProcessThe function is called by:
Return value INTEGER*4
Output n>0: n=Process ID of copy n<0, n=System error code
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.
Example:
fork()
:
INTEGER*4 fork, pidpid = fork()if(pid.lt.0) stop 'fork error'if(pid.gt.0) thenprint *, 'I am the parent'elseprint *, 'I am the child'endifA corresponding
exec
routine has not been provided because there is no satisfactory way to retain open logical units across theexec
routine. However, the usual function offork/exec
can be performed usingsystem
(3F). See also:fork
(2),wait
(3F),kill
(3F),system
(3F), andperror
(3F).
free
: Deallocate Memory Allocated by MallocThe subroutine is called by:
ptr pointer
Input
free
deallocates a region of memory previously allocated bymalloc
. The region of memory is returned to the memory manager; it is no longer available to the user's program.Example:
free()
:
real xpointer ( ptr, x )ptr = malloc ( 10000 )call free ( ptr )endSee malloc, malloc64: Allocate Memory and Get Address for details.
fseek
,ftell
: Determine Position and Reposition a File
fseek
andftell
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.
fseek
: Reposition a File on a Logical UnitThe function is called by:
Note On sequential files, following a call tofseek
by an output operation (for example,WRITE
) causes all data records following thefseek
position to be deleted and replaced by the new data record (and an end-of-file mark). Rewriting a record in place can only be done with direct access files.
Example:
:fseek()
--RepositionMyFile
to two bytes from the beginning
INTEGER*4 fseek, lunit/1/, offset/2/, from/0/, nopen( UNIT=lunit, FILE='MyFile' )n = fseek( lunit, offset, from )if ( n .gt. 0 ) stop 'fseek error'endExample: Same example in a 64-bit environment and compiled with
-xarch=v9
:
INTEGER*4 fseek, lunit/1/, from/0/, nINTEGER*8 offset/2/open( UNIT=lunit, FILE='MyFile' )n = fseek( lunit, offset, from )if ( n .gt. 0 ) stop 'fseek error'end
ftell
: Return Current Position of FileThe function is called by:
Example:
ftell()
:
INTEGER*4 ftell, lunit/1/, nopen( 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, nopen( UNIT=lunit, FILE='MyFile' )...n = ftell( lunit )if ( n .lt. 0 ) stop 'ftell error'...See also
fseek
(3S) andperror
(3F); alsofseeko64
(3F)ftello64
(3F).
fseeko64
,ftello64
: Determine Position and Reposition a Large File
fseeko64
andftello64
are "large file" versions of fseek and ftell. They take and returnINTEGER*8
file position offsets on Solaris 2.6 and Solaris 7. (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.
fseeko64
: Reposition a File on a Logical UnitThe function is called by:
Note On sequential files, following a call tofseeko64
by an output operation (for example,WRITE
) causes all data records following thefseek
position to be deleted and replaced by the new data record (and an end-of-file mark). Rewriting a record in place can only be done with direct access files.
Example:
fseeko64()
--RepositionMyFile
to two bytes from the beginning:
INTEGER fseeko64, lunit/1/, from/0/, nINTEGER*8 offset/200/open( UNIT=lunit, FILE='MyFile' )n = fseeko64( lunit, offset, from )if ( n .gt. 0 ) stop 'fseek error'end
ftello64
: Return Current Position of FileThe function is called by:
lunit INTEGER*4
Input Open logical unit Return value INTEGER*8
Output n0: n=Offset in bytes from start of file n<0: n=System error code
Example:
ftello64()
:
INTEGER*8 ftello64, lunit/1/, nopen( UNIT=lunit, FILE='MyFile' )...n = ftello64( lunit )if ( n .lt. 0 ) stop 'ftell error'...
getarg
,iargc
: Get Command-Line Arguments
getarg
andiargc
access arguments on the command line (after expansion by the command-line preprocessor.
getarg
: Get a Command-Line ArgumentThe subroutine is called by:
k INTEGER*4
Input Index of argument (0=first=command name) arg character*
nOutput kth argument n INTEGER*4
Size of arg Large enough to hold longest argument
iargc
: Get the Number of Command-Line ArgumentsThe function is called by:
Return value INTEGER*4
Output Number of arguments on the command line
Example:
iargc
andgetarg
, get argument count and each argument:
See also
execve
(2) andgetenv
(3F).
getc
,fgetc
: Get Next Character
getc
andfgetc
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.
getc
: Get Next Character fromstdin
The function is called by:
char character
Output Next character Return value INTEGER*4
Output status=0: OK status=-1: End of file status>0: System error code or
f77
I/O error code
Example:
getc
gets each character from the keyboard; note the Control-D (^D
):
character charINTEGER*4 getc, statusstatus = 0do while ( status .eq. 0 )status = getc( char )write(*, '(i3, o4.3)') status, charend doendAfter compiling, a sample run of the above source is:
For any logical unit, do not mix normal Fortran input with
getc()
.
fgetc
: Get Next Character from Specified Logical UnitThe function is called by:
lunit INTEGER*4
Input Logical unit char character
Output Next character Return value INTEGER*4
Output status=-1: End of File status>0: System error code or f77
I/O error code
Example:
fgetc
gets each character fromtfgetc.data
; note the linefeeds (Octal 012):
character charINTEGER*4 fgetc, statusopen( unit=1, file='tfgetc.data' )status = 0do while ( status .eq. 0 )status = fgetc( 1, char )write(*, '(i3, o4.3)') status, charend doendAfter compiling, a sample run of the above source is:
demo%cat tfgetc.data
abyzdemo%a.out
0 141 `a' read0 142 `b' read0 012 linefeed read0 171 `y' read0 172 `z' read0 012 linefeed read-1 012 CONTROL-D readdemo%For any logical unit, do not mix normal Fortran input with
fgetc()
.See also:
getc
(3S),intro
(2), andperror
(3F).
getcwd
: Get Path of Current Working DirectoryThe function is called by:
Example:
getcwd
:
INTEGER*4 getcwd, statuscharacter*64 dirnamestatus = getcwd( dirname )if ( status .ne. 0 ) stop 'getcwd: error'write(*,*) dirnameendSee also:
chdir
(3F),perror
(3F), andgetwd
(3).Note: the path names cannot be longer than
MAXPATHLEN
as defined in<sys/param.h>
.
getenv
: Get Value of Environment VariablesThe subroutine is called by:
ename character*
nInput Name of the environment variable sought evalue character*
nOutput 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.
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 evaluecall getenv( 'SHELL', evalue )write(*,*) "'", evalue, "'"endSee also: execve(2) and environ(5).
getfd
: Get File Descriptor for External Unit NumberThe function is called by:
Example:
getfd()
:
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 = ', fildesend
getfilep
: Get File Pointer for External Unit NumberThe function is:
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
:
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 11%cc -c tgetfilepC.c
demo 12%f77 tgetfilepC.o tgetfilepF.f
tgetfileF.f:MAIN:demo 13%a.out
What is the digit?3
The digit read by C is 3demo 14%For more information, read the chapter on the C-Fortran interface in the Fortran Programming Guide. See also
open
(2).
getlog
: Get User's Login NameThe subroutine is called by:
name character*
nOutput 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.
Example:
getlog
:
character*18 namecall getlog( name )write(*,*) "'", name, "'"end
getpid
: Get Process IDThe function is called by:
Return value INTEGER*4
Output Process ID of the current process
Example:
getpid
:
INTEGER*4 getpid, pidpid = getpid()write(*,*) 'process id = ', pidend
getuid
,getgid
: Get User or Group ID of Process
getuid
andgetgid
get the user or group ID of the process, respectively.
getuid
: Get User ID of the ProcessThe function is called by:
Return value INTEGER*4
Output User ID of the process
getgid
: Get Group ID of the ProcessThe function is called by:
Return value INTEGER*4
Output Group ID of the process
Example:
getuid()
andgetpid()
:
INTEGER*4 getuid, getgid, gid, uiduid = getuid()gid = getgid()write(*,*) uid, gidend
hostnm
: Get Name of Current HostThe function is called by:
name character*
nOutput Name of current host system. n must be large enough to hold the host name. Return value INTEGER*4
Output status=0: OK status>0: Error
Example:
hostnm()
:
INTEGER*4 hostnm, statuscharacter*8 namestatus = hostnm( name )write(*,*) 'host name = "', name, '"'end
idate
: Return Current Date
- Standard--Put the current system date into an integer array: day, month, and year.
- VMS--Put the current system date into three integer variables: month, day, and year. This version is not "Year 2000 Safe".
The
-lV77
compiler option request the VMS library and links the VMS versions of bothtime()
andidate()
; otherwise, the linker accesses the standard versions. (VMS versions of library routines are only available withf77
through the-lV77
library option, and not withf95
).The standard version puts the current system date into one integer array: day, month, and year.
The subroutine is called by:
iarray INTEGER*4
Output Three-element array: day, month, year.
Example:
idate
(standard version):
demo%cat tidate.f
INTEGER*4 iarray(3)call idate( iarray )write(*, "(' The date is: ',3i5)" ) iarrayenddemo%f77 -silent tidate.f
demo%a.out
The date is: 10 8 1998demo%The VMS
idate()
subroutine is called by:
m INTEGER*4
Output Month (1 - 12) d INTEGER*4
Output Day (1 - 7) y INTEGER*4
Output Year (1 - 99) Not year 2000 safe!
Using the VMS
idate()
routine will cause a warning message at link time and the first time the routine is called in execution.
Note The VMS version of theidate()
routine is not "Year 2000 Safe" because it returns only a two-digit value for the year. Programs that compute differences between dates using the output of this routine may not work properly after 31 December, 1999. Programs using thisidate()
routine will see a runtime warning message the first time the routine is called to alert the user. Seedate_and_time()
as a possible alternate.
Example:
idate
(VMS version):
ieee_flags,ieee_handler,
: IEEE Arithmetic
sigfpeThese 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), andsigfpe
(3).Here is a summary:
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. Thelibm
functionieee_handler
sets these trap-enable-mask bits for you.The character keywords accepted for mode and exception depend on the value of action.
Example 1: Set rounding direction to round toward zero, unless the hardware does not support directed rounding modes:
INTEGER*4 ieeercharacter*1 mode, out, inieeer = ieee_flags( 'set', 'direction', 'tozero', out )Example 2: Clear rounding direction to default (round toward nearest):
character*1 out, inieeer = ieee_flags('clear','direction', in, out )Example 3: Clear all accrued exception-occurred bits:
character*18 outieeer = ieee_flags( 'clear', 'exception', 'all', out )Example 4: Detect overflow exception as follows:
character*18 outieeer = ieee_flags( 'get', 'exception', 'overflow', out )if (out .eq. 'overflow' ) stop 'overflow'The above code sets
out
tooverflow
andieeer
to 25 (this value is platform dependent). Similar coding detects exceptions, such asinvalid
orinexact
.Example 5:
hand1.f
, write and use a signal handler (f77
):
Change the declarations for
address
andfunction
hand
toINTEGER*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),f77_floatingpoint
(3F),ieee_flags
(3M), andieee_handler
(3M).
f77
_floatingpoint.h
: Fortran IEEE DefinitionsThe header file
f77
_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 77 source program as follows:
#include "f77_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.Fortran 95 programs should include the file
floatingpoint.h
instead.IEEE Rounding Mode:
fp_direction_type
The type of the IEEE rounding direction mode. The order of enumeration varies according to hardware.
SIGFPE Handling:
IEEE Exception Handling:
IEEE Classification:
fp_class_type
A list of the classes of IEEE floating-point values and symbols.
Refer to the Numerical Computation Guide. See also
ieee_environment
(3M) andf77_ieee_environment
(3F).
index,rindex,lnblnk
: Index or Length of SubstringThese functions search through a character string:
index(
a1,
a2)
Index of first occurrence of string a2 in string a1 rindex(
a1,
a2)
Index of last occurrence of string a2 in string a1 lnblnk(
a1)
Index of last nonblank in string a1
index
has the following forms:
index
: First Occurrence of a Substring in a StringThe index is an intrinsic function called by:
a1 character
Input Main string a2 character
Input Substring Return value INTEGER
Output n>0: Index of first occurrence of a2 in a1 n=0: a2 does not occur in a1.
If declared
INTEGER*8
,index()
will return anINTEGER*8
value when compiled for a 64-bit environment and character variable a1 is a very large character string (greater than 2 Gigabytes).
rindex
: Last Occurrence of a Substring in a StringThe function is called by:
lnblnk
: Last Nonblank in a StringThe function is called by:
a1 character
Input String Return value INTEGER*4
or
INTEGER*8
Output n>0: Index of last nonblank in a1 n=0: a1 is all nonblank INTEGER*8
returned in 64-bit environments
Example:
index()
,rindex()
,lnblnk()
:
Note Programs compiled to run in a 64-bit environment must declareindex, rindex
andlnblnk
(and their receiving variables)INTEGER*8
to handle very large character strings.
inmax
: Return Maximum Positive IntegerThe function is called by:
Return value INTEGER*4
Output The maximum positive integer
Example:
inmax
:
INTEGER*4 inmax, mm = inmax()write(*,*) menddemo%f77 -silent tinmax.f
demo%a.out
2147483647demo%See also
libm_single
(3F) andlibm_double
(3F). See also the intrinsic functionephuge(
) described in the FORTRAN 77 Language Reference Manual.
ioinit
: Initialize I/O PropertiesThe
IOINIT
routine (FORTRAN 77 only) establishes properties of file I/O for files opened after the call toIOINIT
. The file I/O properties thatIOINIT
controls are as follows:
- Carriage control: Recognize carriage control on any logical unit.
- Blanks/zeroes: Treat blanks in input data fields as blanks or zeroes.
- File position: Open files at beginning or at end-of-file.
- Prefix: Find and open files named prefixNN, 0 NN 19.
- Initializes global parameters specifying
f77
file I/O properties- Opens logical units 0 through 19 with the specified file I/O properties--attaches externally defined files to logical units at runtime
Persistence of File I/O Properties
The file I/O properties apply as long as the connection exists. If you close the unit, the properties no longer apply. The exception is the preassigned units 5 and 6, to which carriage control and blanks/zeroes apply at any time.
Internal Flags
IOINIT
uses labeled common to communicate with the runtime I/O system. It stores internal flags in the equivalent of the following labeled common block:
INTEGER*2 IEOF, ICTL, IBZRCOMMON /__IOIFLG/ IEOF, ICTL, IBZR ! Not in user name spaceIn earlier releases (prior to 3.0.1) the labeled common block was named
IOIFLG
. The name changed subsequently to__IOIFLG
to prevent conflicts with any user-defined common blocks.Source Code
Some user needs are not satisfied with a generic version of
IOINIT
, so we provide the source code. It is written in Fortran 77. The location is:<install>
/SUNWspro/
<release>/src/ioinit.f
where <install> is usually
/opt
for a standard installation of the Sun WorkShop software packages, and <release> path changes with every release of the compilers.Usage:
ioinit
The
ioinit
subroutine is called by:
See also
getarg
(3F) andgetenv
(3F).Restrictions
Note the following restrictions:
- prefix can be no longer than 30 characters.
- A path name associated with an environment name can be no longer than 255 characters.
Description of Arguments
These are the arguments for
ioinit
.cctl (Carriage Control)
By default, carriage control is not recognized on any logical unit. If cctl is
.TRUE.
, then carriage control is recognized on formatted output to all logical units, except unit 0, the diagnostic channel. Otherwise, the default is restored.bzro (Blanks)
By default, trailing and embedded blanks in input data fields are ignored. If bzro is
.TRUE.
, then such blanks are treated as zeros. Otherwise, the default is restored.apnd (Append)
By default, all files opened for sequential access are positioned at their beginning. It is sometimes necessary or convenient to open at the end-of-file, so that a write will append to the existing data. If apnd is
.TRUE.
, then files opened subsequently on any logical unit are positioned at their end upon opening. A value of.FALSE.
restores the default behavior.prefix (Automatic File Connection)
If the argument prefix is a nonblank string, then names of the form prefixNN are sought in the program environment. The value associated with each such name found is used to open the logical unit NN for formatted sequential access.
This search and connection is provided only for NN between 0 and 19, inclusive. For NN > 19, nothing is done; see Source Code.
vrbose (
IOINIT
Activity)If the argument vrbose is
.TRUE.
, thenIOINIT
reports on its own activity.Example: The program
myprogram
has the followingioinit
call:
call ioinit( .true., .false., .false., 'FORT', .false.)You can assign file name in at least two ways.
In
sh
:
demo$FORT01=mydata
demo$FORT12=myresults
demo$export FORT01 FORT12
demo$myprogram
In
csh
:
demo%setenv FORT01 mydata
demo%setenv FORT12 myresults
demo%myprogram
With either shell, the
ioinit
call in the above example gives these results:
- Open logical unit 1 to the file,
mydata
.- Open logical unit 12 to the file,
myresults
.- Both files are positioned at their beginning.
- Any formatted output has column 1 removed and interpreted as carriage control.
- Embedded and trailing blanks are to be ignored on input.
Example:
ioinit()
--list and compile:
You can set environment variables as follows, using either
sh
orcsh
:
ioinit()
--sh
:
demo$FORT01=tioinit.data
demo$FORT12=tioinit.au
demo$export FORT01 FORT12
demo$
ioinit()
--csh
:
demo%setenv FORT01 tioinit.data
demo%setenv FORT12 tioinit.au
ioinit()
--Run and test:
demo%a.out
demo%cat tioinit.au
abc 123PDQ 789
itime
: Current Time
itime
puts the current system time into an integer array: hour, minute, and second. The subroutine is called by:
iarray INTEGER*4
Output 3-element array: iarray(1) = hour iarray(2) = minute iarray(3) = second
Example:
itime
:
demo%cat titime.f
INTEGER*4 iarray(3)call itime( iarray )write (*, "(' The time is: ',3i5)" ) iarrayenddemo%f77 -silent titime.f
demo%a.out
The time is: 15 42 35See also
time
(3F),ctime
(3F), andfdate
(3F).
kill
: Send a Signal to a ProcessThe function is called by:
pid INTEGER*4
Input Process ID of one of the user's processes signum INTEGER*4
Input Valid signal number. See signal(3). Return value INTEGER*4
Output status=0: OK status>0: Error code
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 ', pidendThe 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), andperror
(3F).
link
,symlnk
: Make a Link to an Existing File
link
creates a link to an existing file.symlink
creates a symbolic link to an existing file.The functions are called by:
link:
Create a Link to an Existing FileExample 1:
link
: Create a link nameddata1
to the file,tlink.db.data.1
:
symlnk:
Create a Symbolic Link to an Existing FileExample 2:
symlnk
: Create a symbolic link nameddata1
to the file,tlink.db.data.1
:
See also:
link
(2),symlink
(2),perror
(3F), andunlink
(3F).Note: the path names cannot be longer than
MAXPATHLEN
as defined in<sys/param.h>
.
loc
: Return the Address of an ObjectThis intrinsic function is called by:
Example:
loc
:
INTEGER*4 k, locreal arg / 9.0 /k = loc( arg )write(*,*) kend
Note Programs compiled to run in a 64-bit environment should declareINTEGER*8
the variable receiving output from theloc()
function.
long
,short
: Integer Object Conversion
long
andshort
handle integer object conversions betweenINTEGER*4
andINTEGER*2
, and is especially useful in subprogram call lists.
long
: Convert a Short Integer to a Long IntegerThe function is called by:
int2 INTEGER*2
Input Return value INTEGER*4
Output
short
: Convert a Long Integer to a Short IntegerThe function is:
int4 INTEGER*4
Input Return value INTEGER*2
Output
Example (fragment):
long()
andshort()
:
integer*4 int4/8/, longinteger*2 int2/8/, shortcall ExpecLong( long(int2) )call ExpecShort( short(int4) )...endExpecLong
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.
longjmp
,isetjmp
: Return to Location Set byisetjmp
isetjmp
sets a location forlongjmp
;longjmp
returns to that location.
isetjmp
: Set the Location forlongjmp
This intrinsic function is called by:
longjmp
: Return to the Location Set byisetjmp
The subroutine is called by:
Description
The
isetjmp
andlongjmp
routines are used to deal with errors and interrupts encountered in a low-level routine of a program. They aref77
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 toisetjmp
, and returns in such a way that execution continues as if the call toisetjmp
had just returned the value ival.The integer expression ival returned from
isetjmp
is zero iflongjmp
is not called, and nonzero iflongjmp
is called.Example: Code fragment using
isetjmp
andlongjmp
:
Restrictions
- You must invoke
isetjmp
before callinglongjmp
.- The env integer array argument to
isetjmp
and longjmp must be at least 12 elements long.- You must pass the env variable from the routine that calls
isetjmp
to the routine that callslongjmp
, either by common or as an argument.longjmp
attempts to clean up the stack.longjmp
must be called from a lower call-level thanisetjmp
.- Passing
isetjmp
as an argument that is a procedure name does not work.
malloc,
malloc64
: Allocate Memory and Get AddressThe
malloc()
function is called by:
Note Programs compiled to run on 64-bit environments such as Solaris 7 must declare themalloc()
function and the variables receiving its output asINTEGER*8
. Portability issues can be solved by usingmalloc64()
instead ofmalloc()
in programs that must run in both 32-bit or 64-bit environments.
The function
malloc64
(3F) is provided to make programs portable between 32-bit and 64-bit environments:
n INTEGER*8
Input Number of bytes of memory Return value INTEGER*8
Output k>0: k=address of the start of the block of memory allocated k=0: Error
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 declaredINTEGER*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)pointer ( p1, X )real*4 X(NX)...p1 = malloc( NX*4 )if ( p1 .eq. 0 ) stop 'malloc: cannot allocate'do 11 i=1,NX11 X(i) = 0....endIn the above example, we acquire 4,000 bytes of memory, pointed to by p1, and initialize it to zero.
See also free: Deallocate Memory Allocated by Malloc.
mvbits
: Move a Bit FieldThe subroutine is called by:
Example:
mvbits
:
- Bits are numbered 0 to 31, from least significant to most significant.
mvbits
changes only bits ini2 through ini2+
nbits-1
of the des location, and no bits of the src location.- The restrictions are:
perror
,gerror
,ierrno
: Get System Error MessagesThese routines perform the following functions:
perror
Print a message to Fortran logical unit 0, stderr
.gerror
Get a system error message (of the last detected system error) ierrno
Get the error number of the last detected system error.
perror
: Print Message to Logical Unit 0,stderr
The subroutine is called by:
string character*
nInput The message. It is written preceding the standard error message for the last detected system error.
Example 1:
call perror( "file is for formatted I/O" )
gerror
: Get Message for Last Detected System ErrorThe subroutine or function is called by:
string character*
nOutput Message for the last detected system error
Example 2:
gerror()
as a subroutine:
character string*30...call gerror ( string )write(*,*) stringExample 3:
gerror
() as a function; string not used:
character gerror*30, z*30...z = gerror( )write(*,*) z
ierrno
:Get Number for Last Detected System Error
The function is called by:
Return value INTEGER*4
Output Number of last detected system error
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.
Example 4:
ierrno()
:
INTEGER*4 ierrno, n...n = ierrno()write(*,*) nSee also
intro
(2) andperror
(3).
- string in the call to
perror
cannot be longer than 127 characters.- The length of the string returned by
gerror
is determined by the calling program.- Runtime I/O error codes for
f77
andf95
are listed in the Fortran User's Guide.
putc
,fputc
: Write a Character to a Logical Unit
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.
putc
: Write to Logical Unit 6The function is called by:
char character
Input The character to write to the unit Return value INTEGER*4
Output status=0: OK status>0: System error code
Example:
putc()
:
character char, s*10 / 'OK by putc' /INTEGER*4 putc, statusdo i = 1, 10char = s(i:i)status = putc( char )end dostatus = putc( '\n' )enddemo%f77 -silent tputc.f
demo%a.out
OK by putcdemo%
fputc
: Write to Specified Logical UnitThe function is called by:
lunit INTEGER*4
Input The unit to write to char character
Input The character to write to the unit Return value INTEGER*4
Output status=0: OK status>0: System error code
Example:
fputc()
:
See also
putc
(3S),intro
(2), andperror
(3F).
qsort,qsort64
: Sort the Elements of a One-Dimensional ArrayThe subroutine is called by:
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, asINTEGER*8
data. Use the Fortran 95 style constants to explicitly specifyINTEGER*8
constants.The
compar(
arg1,
arg2)
arguments are elements of array, returning:
Negative If arg1 is considered to precede arg2 Zero If arg1 is equivalent to arg2 Positive If arg1 is considered to follow arg2
For example:
ran
: Generate a Random Number Between 0 and 1Repeated calls to
ran
generate a sequence of random numbers with a uniform distribution.
i INTEGER*4
Input Variable or array element r REAL
Output Variable or array element
Example:
ran
:
- The range includes 0.0 and excludes 1.0.
- The algorithm is a multiplicative, congruential type, general random number generator.
- In general, the value of
i
is set once during execution of the calling program.- The initial value of
i
should be a large odd integer.- Each call to
RAN
gets the next random number in the sequence.- To get a different sequence of random numbers each time you run the program, you must set the argument to a different initial value for each run.
- The argument is used by
RAN
to store a value for the calculation of the next random number according to the following algorithm:
SEED = 6909 * SEED + 1 (MOD 2**32)SEED
contains a 32-bit number, and the high-order 24 bits are converted to floating point, and that value is returned.
rand
,drand
,irand
: Return Random Values
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, comparelcrans
,addrans
, andshufrans
. See alsorandom
(3), and the Numerical Computation Guide
Example:
irand()
:
integer*4 v(5), iflag/0/do i = 1, 5v(i) = irand( iflag )end dowrite(*,*) venddemo%f77 -silent trand.f
demo%a.out
2078917053 143302914 1027100827 1953210302 755253631demo%
rename
: Rename a FileThe function is called by:
from character*
nInput Path name of an existing file to character*
nInput New path name for the file Return value INTEGER*4
Output status=0: OK status>0: System error code
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 filetrename.old
totrename.new
See also
rename
(2) andperror
(3F).Note: the path names cannot be longer than
MAXPATHLEN
as defined in<sys/param.h>
.
secnds
: Get System Time in Seconds, Minus Argument
t0 REAL
Input Constant, variable, or array element Return Value REAL
Output Number of seconds since midnight, minus t0
Example:
secnds
:
- The returned value from
SECNDS
is accurate to 0.01 second.- The value is the system time, as the number of seconds from midnight, and it correctly spans midnight.
- Some precision may be lost for small time intervals near the end of the day.
sh
: Fast Execution of ansh
CommandThe function is called by:
string character*
nInput String containing command to do Return value INTEGER*4
Output Exit status of the shell executed. See wait(2) for an explanation of this value.
Example:
sh()
:
character*18 string / 'ls > MyOwnFile.names' /INTEGER*4 status, shstatus = sh( string )if ( status .ne. 0 ) stop 'sh: error'...endThe function
sh
passes string to thesh
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:
- For output files, the buffer is flushed to the actual file.
- For input files, the position of the pointer is unpredictable.
The
sh()
function is not MT-safe. Do not call it from multithreaded or parallelized programs.See also:
execve
(2),wait
(2), andsystem
(3).Note: string cannot be longer than 1,024 characters.
signal
: Change the Action for a SignalThe function is called by:
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.
f77
arranges to trap certain signals when a process is started. The only way to restore the defaultf77
action is to save the returned value from the first call tosignal
.
f77_floatingpoint.h
defines proc valuesSIGFPE_DEFAULT
,SIGFPE_IGNORE
, andSIGFPE_ABORT
. See page 59. (Usefloatingpoint.h
withf95
).In 64-bit environments,
signal
must be declaredINTEGER*8
, along with the variables receiving its output, to avoid truncation of the address that may be returned.See also
kill
(1),signal
(3), andkill
(3F), and Numerical Computation Guide.
sleep
: Suspend Execution for an IntervalThe subroutine is called by:
itime INTEGER*4
Input Number of seconds to sleep
The actual time can be up to 1 second less than itime due to granularity in system timekeeping.
Example:
sleep()
:
INTEGER*4 time / 5 /write(*,*) 'Start'call sleep( time )write(*,*) 'End'end
stat
,lstat
,fstat
: Get File StatusThese functions return the following information:
- device,
- inode number,
- protection,
- number of hard links,
- user ID,
- group ID,
- device type,
- size,
- access time,
- modify time,
- status change time,
- optimal blocksize,
- blocks allocated
Both
stat
andlstat
query by file name.fstat
queries by logical unit.
stat
: Get Status for File, by File NameThe function is called by:
Example 1:
stat()
:
fstat
: Get Status for File, by Logical UnitThe function
Example 2:
fstat()
:
lstat
: Get Status for File, by File NameThe function is called by:
ierr= lstat (
name,
statb)
name character*
nInput File name statb INTEGER*4
Output Status array of file, 13 elements Return value INTEGER*4
Output ierr=0: OK ierr>0: Error code
Example 3:
lstat()
:
Detail of Status Array for Files
The meaning of the information returned in the
INTEGER*4
array statb is as described for the structure stat understat
(2).Spare values are not included. The order is shown in the following table:
See also
stat
(2),access
(3F),perror
(3F), andtime
(3F).Note: the path names can be no longer than
MAXPATHLEN
as defined in<sys/param.h>
.
stat64
,lstat64
,fstat64
: Get File Status64-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 declaredINTEGER*8
.
system
: Execute a System CommandThe function is called by:
string character*
nInput String containing command to do Return value INTEGER*4
Output Exit status of the shell executed. See wait(2) for an explanation of this value.
Example:
system()
:
character*8 string / 'ls s*' /INTEGER*4 status, systemstatus = system( string )if ( status .ne. 0 ) stop 'system: error'endThe 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 variableSHELL
, thensystem
uses the value ofSHELL
as the command interpreter (shell); otherwise, it usessh
(1).The current process waits until the command terminates.
Historically,
cc
andf77
developed with different assumptions:
- If
cc
callssystem
, the shell is always the Bourne shell.- If
f77
callssystem
, then which shell is called depends on the environment variableSHELL
.The
system
function flushes all open files:
- For output files, the buffer is flushed to the actual file.
- For input files, the position of the pointer is unpredictable.
See also:
execve
(2),wait
(2), andsystem
(3).The
system()
function is not MT-safe. Do not call it from multithreaded or parallelized programs.
time
,ctime
,ltime
,gmtime
: Get System TimeThese routines have the following functions:
time
: Get System TimeFor
time()
, there are two versions, a standard version and a VMS version. If you use thef77
command-line option-lV77
, then you get the VMS version fortime()
and foridate()
; otherwise, you get the standard versions. (The VMS versions of certain library routines is only available withf77
through the-lV77
library option, and not withf95
.)The standard function is called by:
Return value INTEGER*4
Output Time, in seconds, since 0:0:0, GMT, 1/1/70 INTEGER*8
Output In 64-bit environments, time
returns an INTEGER*8 value
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:
INTEGER*4 n, timen = time()write(*,*) 'Seconds since 0 1/1/70 GMT = ', nenddemo%f77 -silent ttime.f
demo%a.out
Seconds since 0 1/1/70 GMT = 913240205demo%The VMS version of
time
is a subroutine that gets the current system time as a character string.The VMS subroutine is called by:
t character*8
Output Time, in the form hh:mm:ss
hh, mm, and ss are each two digits: hh is the hour; mm is the minute; ss is the second
Example:
time(
t)
, VMS version,ctime
--convert the system time to ASCII:
character t*8call time( t )write(*, "(' The current time is ', A8 )") tenddemo%f77 -silent ttimeV.f -lV77
demo%a.out
The current time is 08:14:13demo%
ctime
: Convert System Time to CharacterThe function
ctim
e converts a system time, stime, and returns it as a 24-character ASCII string.The function is called by:
stime INTEGER*4
Input System time from time()
(standard version)Return value character*24
Output System time as character string. Declare ctime
and string ascharacter*24
.
The format of the
ctime
returned value is shown in the following example. It is described in theman
pagectime
(3C).Example:
ctime()
:
character*24 ctime, stringINTEGER*4 n, timen = time()string = ctime( n )write(*,*) 'ctime: ', stringenddemo%f77 -silent tctime.f
demo%a.out
ctime: Wed Dec 9 13:50:05 1998demo%
ltime
: Split System Time to Month, Day,... (Local)This routine dissects a system time into month, day, and so forth, for the local time zone.
The subroutine is called by:
stime INTEGER*4
Input System time from time()
(standard version)tarray INTEGER*4(9)
Output System time, local, as day, month, year, ...
For the meaning of the elements in
tarray
, see the next section.Example:
ltime()
:
integer*4 stime, tarray(9), timestime = time()call ltime( stime, tarray )write(*,*) 'ltime: ', tarrayenddemo%f77 -silent tltime.f
demo%a.out
ltime: 25 49 10 12 7 91 1 223 1demo%
gmtime
: Split System Time to Month, Day, ... (GMT)This routine dissects a system time into month, day, and so on, for GMT.
The subroutine is:
stime INTEGER*4
Input System time from time()
(standard version)tarray INTEGER*4(9)
Output System time, GMT, as day, month, year, ...
Example:
gmtime
:
integer*4 stime, tarray(9), timestime = time()call gmtime( stime, tarray )write(*,*) 'gmtime: ', tarrayenddemo%f77 -silent tgmtime.f
demo%a.out
gmtime: 12 44 19 18 5 94 6 168 0demo%Here are the
tarray()
values forltime
andgmtime
: 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), andfdate
(3F).
ctime64,
gmtime64,
ltime64:
System Time Routines for 64-bit EnvironmentsThese are versions of the corresponding routines
ctime
,gmtime
, andltime
, to provide portability on 64-bit environments. They are identical to these routines except that the input variable stime must beINTEGER*8
.When used in a 32-bit environment with an
INTEGER*8
stime, if the value of stime is beyond theINTEGER*4
rangectime64
returns all asterisks, whilegmtime
andltime
fill the tarray array with -1.
topen
,tclose
,tread
,...,tstate
: Tape I/O(FORTRAN 77 Only) These routines provide an alternative way to manipulate magnetic tape:
On any one unit, do not mix these functions with standard Fortran I/O.
You must first use
topen
() to open a tape logical unit, tlu, for the specified device. Then you do all other operations on the specified tlu. tlu has no relationship at all to any normal Fortran logical unit.Before you use one of these functions, its name must be in an
INTEGER*4
type statement.
topen
: Associate a Device with a Tape Logical UnitThe function is called by:
This function does not move the tape. See
perror
(3F) for details.Example:
topen()
--open a 1/4-inch tape file:
The output is:
topen ok: 0 1 /dev/rst0
tclose
: Write EOF, Close Tape Channel, Disconnect tluThe function is called by:
tlu INTEGER*4
Input Tape logical unit, in range 0 to 7 n INTEGER*4
Return value n=0: OK n<0: Error
Caution tclose(
) places an EOF marker immediately after the current location of the unit pointer, and then closes the unit. So if youtrewin()
a unit before youtclose()
it, its contents are discarded.
Example:
tclose()
--close an opened 1/4-inch tape file:
The output is:
tclose ok: 0 1 /dev/rst0
twrite
: Write Next Physical Record to TapeThe function is called by:
The physical record length is the size of
buffer
.Example:
twrite()
--write a 2-record file:
The output is:
twrite ok: 512 1 /dev/rst0
tread
: Read Next Physical Record from TapeThe function is called by:
If the tape is at EOF or EOT, then
tread
does a return; it does not read tapes.Example:
tread()
--read the first record of the file written above:
The output is:
tread ok: 512 1 /dev/rst0abcd
trewin
: Rewind Tape to Beginning of First Data FileThe function is called by:
tlu INTEGER*4
Input Tape logical unit, in range 0 to 7 n INTEGER*4
Return value n=0: OK n<0: Error
If the tape is labeled, then the label is skipped over after rewinding.
Example 1:
trewin()
--typical fragment:
Example 2:
trewin()
--in a two-record file, try to read three records, rewind, read one record:
The output is:
1 abcd2 wxyz3 wxyztrewin ok: 0 1 /dev/rst0abcd
tskipf
: Skip Files and Records; Reset EoF StatusThe function is called by:
This function does not skip backward.
First, the function skips forward over nf end-of-file marks. Then, it skips forward over nr physical records. If the current file is at EOF, this counts as one file to skip. This function also resets the EOF status.
Example:
tskipf()
--typical fragment: skip four files and then skip one record:
INTEGER*4 nfiles / 4 /, nrecords / 1 /, tskipf, tlu / 1 /...n = tskipf( tlu, nfiles, nrecords )IF ( n .LT. 0 ) STOP "tskipf: cannot skip"...
tstate
: Get Logical State of Tape I/O ChannelThe function is called by:
While eoff is true, you cannot read from that tlu. You can set this EOF status flag to false by using
tskipf()
to skip one file and zero records:
n = tskipf( tlu, 1, 0).Then you can read any valid record that follows.
End-of-tape (EOT) is indicated by an empty file, often referred to as a double
EOF
mark. You cannot read past EOT, but you can write past it.Example: Write three files of two records each:
The next example uses
tstate()
to trap EOF and get at all files.Example: Use
tstate()
in a loop that reads all records of the 3 files written in the previous example:
The output is:
A summary of EOF and EOT follows:
- If you are at either EOF or EOT, then:
- Any
tread()
just returns; it does not read the tape.- A successful
tskipf(tlu,1,0)
resets the EOF status to false, and returns; it does not advance the tape pointer.- A successful
twrite()
resets the EOF and EOT status flags to false.- A successful
tclose()
resets all those flags to false.tclose()
truncates; it places an EOF marker immediately after the current location of the unit pointer, and then closes the unit. So, if you usetrewin()
to rewind a unit before you usetclose()
to close it, its contents are discarded. This behavior oftclose(
) is inherited from the Berkeley code.See also:
ioctl
(2),mtio
(4s),perror
(3F),read
(2),st
(4s), andwrite
(2).
ttynam
,isatty
: Get Name of a Terminal Port
ttynam
andisatty
handle terminal port names.
ttynam
: Get Name of a Terminal PortThe function
ttynam
returns a blank padded path name of the terminal device associated with logical unit lunit.The function is called by:
isatty
: Is this Unit a Terminal?The function
lunit INTEGER*4Input Logical unit Return value LOGICAL*4Output terminal=true: It is a terminal device terminal=false: It is not a terminal device
Example: Determine if lunit is a tty:
character*12 name, ttynamINTEGER*4 lunit /5/logical*4 isatty, terminalterminal = isatty( lunit )name = ttynam( lunit )write(*,*) 'terminal = ', terminal, ', name = "', name, '"'endThe output is:
terminal = T, name = "/dev/ttyp1 "
unlink
: Remove a FileThe function is called by:
patnam character*
nInput File name Return value INTEGER*4Output n=0: OK n>0: Error
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 thetunlink.data
file:
call unlink( 'tunlink.data' )enddemo%f77 -silent tunlink.f
demo%ls tunl*
tunlink.f tunlink.datademo%a.out
demo%ls tunl*
tunlink.fdemo%See also:
unlink
(2),link
(3F), andperror
(3F). Note: the path names cannot be longer thanMAXPATHLEN
as defined in<sys/param.h>
.
wait
: Wait for a Process to TerminateThe function is:
status INTEGER*4
Output Termination status of the child process Return value INTEGER*4
Output n>0: Process ID of the child process n<0: n=System error code; see wait
(2).
wait
suspends the caller until a signal is received, or one of its child processes terminates. If any child has terminated since the lastwait
, return is immediate. If there are no children, return is immediate with an error code.Example: Code fragment using
wait()
:
INTEGER*4 n, status, wait...n = wait( status )if ( n .lt. 0 ) stop 'wait: error'...end
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |