C PROGRAMMING
MULTIPLE CHOICE QUESTION
OLD QUESTION BANK
SAMPLE QUESTION 2080 AND SOLUTION

Character I/O (fputc(), fgetc())

1. fgetc()

Definition: fgetc() is a standard C library function used for reading a single character from a file.

Syntax:

int fgetc(file_pointer);

Example :

char ch;
FILE *fptr;
ch=fgetc(fptr);

Question:

WAP to open a file , read its content one character at a time and display it to the screen using getc() function.

#include<stdio.h>
int main()
{
	FILE *fptr;
	char c;
	fptr=fopen("abc.txt","r");
	if(fptr==NULL)
	{
		printf("file cannot be open");
	}
	
	
	printf("the content from file is \n");
	while((c=fgetc(fptr))!=EOF)
	{
		putchar(c);
	}
	
	fclose(fptr);
}

2. fputc()

Definition: fputc() is a standard C library function used for writing a single character to a file.

Syntax:

int fputc(int character, file_pointer);

Example:

char ch;
FILE *fptr;
fputc(ch,fptr);

Question:

WAP to create a file and write some text to it, writing one character at a time using the fputc() function. The program should write until the user hits the enter key. Read filename from user.


#include<stdio.h>
#include<stdlib.h>
int main()
{
	FILE *fptr;
	char c;
	fptr=fopen("abc2.txt","w");
	if(fptr==NULL)
	{
		printf("file cannot be open");
		exit(0);
	}
	else
	{
		printf("file created successfully");
			printf("enter text till enter key is hit\n");
			do
			{
				
				c = getchar();
				fputc(c,fptr);
			}while(c!='\n');
	}

	fclose(fptr);
}