w3resource

C getc() function

C library function - getc()

This getc() function is used to read one unsigned character from the input stream at the current position and increases the file pointer, if any, so that it points to the next character in the input stream.

Syntax:

int getc(FILE *stream)

Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value

  • Upon successful completion, getc() shall return the next byte from the input stream pointed to by stream.
  • If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream shall be set and getc() shall return EOF.
  • If a read error occurs, the error indicator for the stream shall be set, getc() shall return EOF, and shall set errno to indicate the error.

Example: getc() function

In this example, a line of input is gathered from a stream.

#include <stdio.h>
 
#define  MAX_LEN  80
 
int main(void)
{
   FILE *fp;
   char buffer[MAX_LEN + 1];
   int i, ch;
   
    // Write some text in test.txt
    char str[] = "C Programming Tutorial and Exercises.";
    fp = fopen( "test.txt" , "w" );
    fwrite(str , 1 , sizeof(str) , fp );
    fclose(fp); 
    
   fp = fopen("test.txt","r");
 
   for (i = 0; (i < (sizeof(buffer)-1) &&
         ((ch = fgetc(fp)) != EOF) && (ch != '\n')); i++)
      buffer[i] = ch;
 
   buffer[i] = '\0';
 
   if (fclose(fp))
      perror("fclose error");
 
   printf("Text in the said file:\n%s\n", buffer);
}
Text in the said file: C Programming Tutorial and Exercises.

Output:

Text in the said file:
C Programming Tutorial and Exercises.

C Programming Code Editor:

Previous C Programming: C fputs()
Next C Programming: C putc()



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

How to read the content of a file to a string in C?

char * buffer = 0;
long length;
FILE * f = fopen (filename, "rb");

if (f)
{
fseek (f, 0, SEEK_END);
length = ftell (f);
fseek (f, 0, SEEK_SET);
buffer = malloc (length);
if (buffer)
  {
fread (buffer, 1, length, f);
  }
fclose (f);
}
if (buffer)
{
  // start to process your data / extract strings here...
}

Ref: https://bit.ly/3iCh0vp