Movatterモバイル変換


[0]ホーム

URL:


OverIQ.com

  1. Home
  2. C Programming Tutorial
  3. fgetc() Function in C

fgetc() Function in C

Last updated on July 27, 2020


The syntax of thefgetc() functon is:

Syntax:int fgetc(FILE *fp);

This function is complementary tofputc() function. It reads a single character from the file and increments the file position pointer. To use this function file must be opened in read mode. On success, it returns the ASCII value of the character but you can also assign the result to a variable of typechar. On failure or end of file, it returnsEOF or-1.

Just asfputc() this function uses buffer memory too. So instead of reading a single character from the file one by one, a whole block of characters from the file is read into the buffer. The characters are then handed over one at a time to the functionfgetc(), until the buffer is empty. If there are still some characters left to read in the file then again a block of characters is read into the buffer.

The following program demonstrates how to usefgetc() function.

 1 2 3 4 5 6 7 8 910111213141516171819202122232425
#include<stdio.h>#include<stdlib.h>intmain(){intch;FILE*fp;fp=fopen("myfile.txt","r");if(fp==NULL){printf("Error opening file\n");exit(1);}printf("Reading contents of myfile.txt:\n\n");while((ch=fgetc(fp))!=EOF){printf("%c",ch,ch);}fclose(fp);return0;}

Expected Output:

123
Reading contents of myfile.txt:Testing fputc() function

How it works:

In line 6, a variablech of typeint is declared.

In line 7, a structure pointer variablefp of typestruct FILE is declared.

In line 8,fopen() function is called with two arguments namely"myfile.txt" and"r" . On success, it returns a pointer to file"myfile.txt" and opens the file"myfile.txt" in read-only mode. On failure or end of file, it returnsNULL.

In line 10, if statement is used to test the value offp. If it isNULL,printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.

In line 16,printf() statement prints"Reading contents of myfile.txt: \n\n" to the console.

In lines 18-21, a while loop is used to read characters one by one from the file and prints it to the console usingprintf() statement (you can also use putchar() function). The parentheses aroundch = fgetc(fp) is necessary because the precedence of!= operator is greater than that of= operator.

In line 23,fclose() function is used to close the file.


Load Comments


C Programming Tutorial

Recent Posts

x

[8]ページ先頭

©2009-2025 Movatter.jp