HP 3000 Manuals

getc [ HP C/iX Library Reference Manual ] MPE/iX 5.0 Documentation


HP C/iX Library Reference Manual

getc 

Reads a character from an open stream.

Syntax 

     #include <stdio.h>
     int getc (FILE *stream);

Parameters 

stream        A pointer to an open stream.

Return Values 

x             The character read, expressed as an integer.

EOF           No more data, or an error occurred.

Description 

The getc function returns the next character from the input stream
pointed to by stream.  The getc function is equivalent to the fgetc
function except that it is implemented as a macro.  Because getc() can
evaluate the stream more than once, the arguments should never be an
expression with side effects.

Examples 

A simple version of a command to print a file can be written using getc()
and putc():

        #include <stdio.h>
        main(argc, argv)
        int argc;
        char *argv[ ];
        {
           int c;
           FILE *fp;

           if(argc != 2) {
              printf("Usage:  cat file\n");
              exit(1);
           }

           fp = fopen(argv[1], "r");
           if(fp == NULL) {
              printf("Can't open %s.\n", argv[1]);
              exit(1);
           }

           while((c = getc(fp)) != EOF)
              putc(c, stdout);
           putc('\n', stdout);

           exit(0);
        }

This program accepts a single argument that is assumed to be the name of
a file whose contents are to be printed on the terminal.  The specified
file is opened for reading, and the resulting file pointer fp is used in
getc() to read a character from the file.  Each character read is written
on stdout using putc().  (Note that stdout, stdin, and stderr are legal
file pointers.)  The reading and writing loop terminates when the
constant EOF is returned from getc(), indicating that the end of the file
has been reached.  This constant is defined in <stdio.h>.

You can use the flexibility of putc() to send data somewhere other than
to the user's terminal.  For example, the file copy program from the
previous example can be rewritten using getc() and putc().

        #include <stdio.h>
        main(argc, argv)
        int argc;
        char *argv[ ];
        {
           int c;
           FILE *from, *to;

           if(argc != 3) {
              printf("Usage:  cp fromfile tofile\n");
              exit(1);
           }

           from = fopen(argv[1], "r");
           if(from == NULL) {
              printf("Can't open %s.\n", argv[1]);
              exit(1);
           }
           to = fopen(argv[2], "w");
           if(to == NULL) {
              printf("Can't create %s.\n", argv[2]);
              exit(1);
          }

          while((c = getc(from)) != EOF)
              putc(c, to);

          exit(0);
        }

See Also 

fclose(), ferror(), fopen(), fread(), fgetc(), gets(), putc(), fputc(),
scanf(), ANSI C 4.9.7.5, POSIX.1 8.1



MPE/iX 5.0 Documentation