Sun Studio 12: Fortran Library Reference

1.4.16 getc, fgetc: Get Next Character

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.

1.4.16.1 getc: Get Next Character From stdin

The function is called by:

INTEGER*4 getc

status = getc( char )

char

character

Output 

Next character 

Return value 

INTEGER*4

Output 

status=0: OK

status=-1: End of file

status>0: System error code or f95 I/O error code

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:


demo% a.out
ab            Program reads letters typed in
0 141         Program outputs status and octal value of the characters entered
0 142            141 represents ’a’, 142 is ’b’
0 012            012 represents the RETURN key
^D               terminated by a CONTROL-D.
-1 377        Next attempt to read returns CONTROL-D
demo%

For any logical unit, do not mix normal Fortran input with getc().

1.4.16.2 fgetc: Get Next Character From Specified Logical Unit

The function is called by:

INTEGER*4 fgetc

status = fgetc( lunit, char )

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 f95 I/O error code

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).