Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is fgetc() in C?

Kainat Asif

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

fgetc() reads a single character from a file at the location indicated by the file pointer. After reading the character from the file, fgetc() increments the file pointer by one location. Below is the declaration of the fgetc() function:

int fgetc (FILE * stream);

Return value

The fgetc() function returns the ASCII value of the character that is read from the file if the read operation is successful. If there is an error when reading from the file, EOFEnd-of-File is returned.

Parameter of the fgetc() function

  • stream: Pointer to the file from which the character is read.

Code

Consider the code snippet below, which uses fgetc() to read the content of a file character by character:

main.c
fgetcExample.txt
#include <stdio.h>
int main() {
FILE * fPointer;
char character;
fPointer = fopen ("fgetcExample.txt", "r");//opening file
while( !feof(fPointer) )//checking EOF
{
character = fgetc(fPointer);
if(character!=EOF)//if EOF returned
{
printf("%c",character);
}
}
fclose(fPointer);
return 0;
}

The fgetc() function is used in line 12, which reads the content of the file fgetcExample.txt character by character and prints the content of the file on the screen.

RELATED TAGS

c

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. 💪

Keep Exploring
Related Courses