File Input in C Language | Read data from file in C Language | fgetc(), getc(), getw(), fgets(), fscanf() function in C language

File input output in c

File Input in C Language | Read data from file in C Language | fgetc(), getc(), getw(), fgets(), fscanf() function in C language

Different predefined functions of C language for file input are:

1.  fgetc()/getc() function

This function is used to read single character from a file.

Syntax:

v=fgetc( Fpointer);

OR

v=getc( Fpointer);

v is character variable to hold character read from file.

Fpointer is the file pointer variable . 

 Program to demonstrate fgetc()/getc()
#include<stdio.h>
int main()
{
FILE *f1;
char s;
f1=fopen(“myfile.txt”,”r”);
printf(“File contains:”);
s=fgetc(f1);  //or s=getc(f1);
printf(“%c”,s);
fclose(f1);
return(0);

}
Output
File contains:k

2.  getw() function

This function is used to read integer value from a file.

Syntax

v=getw( F);

v refers to integer variable to store integer value read from a file.

Fpointer is the file pointer variable. 

 Program to demonstrate getw().
#include<stdio.h>
int main()
{
FILE *f1;
int n;
f1=fopen(“integers.txt”,”r”);
printf(“File contains”);
n=getw(f1);
printf(“%d”,n);
fclose(f1);
return(0);
}
Output
File contains 100

3. fgets() function

fgets()  function is used to get a string from a specified fileS

Syntax:

fgets(S , N, Fpointer);

S represents the string variable to store string value read from file.

N represents the number of characters to be extracted from the file.

F refers to the file pointer variable to refer a file.

 Program to demonstrate fgets().
#include<stdio.h>
int main()
{
FILE *f1;
char str[100];
f1=fopen(“words.txt”,”r”);
fgets(str,100,f1); 
printf(“\nFile contains:”);
printf(“%s”,str);
fclose(f1);
return(0);
}
Output
File contains: This is a string value

4. fscanf() function

This function is used to read different types of data from a file.

Syntax:

fscanf(Fpointer,”Control-String”,var1,var2,….);

Fpointer represents file pointer variable to refer to a file.

Control-string can contain conversion characters like %d, %f, %s to read values of different types from file.

var1,var2,….  are variables to contain values read from the file. 

Program to demonstrate fscanf() function.
#include<stdio.h>
int main()
{
FILE *f1;
int empid;
char ename[20];
f1=fopen(“emp.dat”,”r”);

fscanf(f1,”%d%s”,&empid,ename);
printf(“\nEmployee id=%d”,empid);
printf(“\nEmployee Name=%s”,ename);
fclose(f1);
return(0);
}
Output
Rollno of student=1
Name of student=Amit 

Spread the love
Lesson tags: fgetc() function in c, fgets() function in c, File Input output in C in c, fprintf() function in c, fputc() function in c, fputs() function in c, fread() function in c, fscanf() function in c, fwrite() function in c, getc() function in c, getw() function in c, put content into file in c, putc()  in c, putw() function in c, read contents of file in c
Back to: C Programming Language
Spread the love