3.2.10. fgetc

Reads a byte from a file.

Syntax

int fgetc (fileid)
int fileid;

where:

fileid

The ID of the file containing the next byte to be read. This must be a user-defined fileid.

Description

This macro returns the contents of the next byte from a file. The fgetc macro name is short for [file getc()], where file indicates that the macro operates on a file, and getc is the standard function for getting a character from a user defined file. This is distinct from the getchar function, which can only retrieve a character from the standard input, and is typically the keyboard.

fgetc returns the contents of the next memory location byte from the specified file. You define the identity of the file with the fopen macro, or the FOPEN command. Any file used to read, or get, the contents of the next byte, must be opened in read mode.

Return value

int

Returns the contents of the next byte of memory from a user specified file. Returns the value -1 if either an end-of-file mark (EOF) or an error is encountered.

Rules

The file read from must be opened in read mode, for example:

fopen(100,"c:\\myfiles\\data_in.txt","r")

Example

This example shows how to use fgetc, together with fopen, fputc, and fclose:

define /R void copyFile()
{
  int retval;
  int ch;
  // Create data file to read
  retval = fopen(100,"c:\\myfiles\\data_in.txt","w");
  if (retval < 0)
    error(2,"Cannot open file for writing!\n",101);
  else {
    retval = fwrite("1234567890\n1234567890\n1234567890", 1, 32, 100);
    fclose(100);
    fopen(100,"c:\\myfiles\\data_in.txt","r");       // open for read-only
    if (retval < 0)
      error(2,"Source file not opened!\n",101);
    else
      fopen(200,"c:\\myfiles\data_out.txt","w");    // open for writing
      if (retval < 0)
        error(2,"Destination file not opened!\n",101);
      else
        do {
          ch = fgetc(100);                            // fgetc()
          if (ch < 0)
            $printf "Finished copying the file!"$;
          else
            fputc(ch,200);                            // fputc()
        } while (ch > 0);
    }
    fclose(100);
    fclose(200);
  }
}
.

See also

Copyright © 2002-2009 ARM Limited. All rights reserved.ARM DUI 0175K
Non-Confidential