Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Steps to process a file

1.Declare a file pointer variable


2.Open a file using fopen() function
3.Process the file using suitable function
4.Close the file using fclose() function

Declare a file pointer

FILE *Pointer_name; FILE *fp

Open a file
1.Use fopen function
fopen(filename,mode);
2.Assign it to the pointer
Pointer_name=fopen(filename,mode);
Fp=fopen(emp.txt,r);

Close the file


Fclose(Pointer_name);
fclose(fp);

Example
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;

fp=fopen("student.txt","r");
if(fp==NULL)
{
printf("File could not be opened");
}
getch();
}
Or
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char fname[20];
printf("Enter file name");
gets(fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("File could not be opened");
}
getch();
}
File Modes

Reading Data from files


1.fscanf()
2.fgets()
3.fgetc()
4.fread()

Writing Data to files


1.fprintf()
2.fputs()
3.fputc()
4.fwrite()

Example:fprintf()

int fprintf(FILE *stream, const char *format, ...)


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int i;
char name[20];
int empid;
float salary;
char fname[20];
clrscr();
printf("Enter file name");
gets(fname);
fp=fopen(fname,"w");
if(fp==NULL)
{
printf("File could not be opened");
}
for(i=0;i<2;++i)
{ printf("Enter your name");
gets(name);
printf("Enter your empid");

scanf("%d",&empid);
printf("Enter your salary");
scanf("%f",&salary);
fprintf(fp,"%s\t%d\t%f\t",name,empid,salary);
fflush(stdin);
}
fclose(fp);
getch();
}
Example:fscanf()

int fscanf(FILE *stream, const char *format, ...)


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int i,empid;
char name[20];
float salary;
char fname[20];
clrscr();
printf("Enter file name");
gets(fname);
fp=fopen(fname,"r");
if(fp==NULL)
{
printf("File could not be opened");
}
for(i=0;i<2;++i)
{
fscanf(fp,"%s%d%f",&name,&empid,&salary);
printf("\nName:(%s)\tEmpid:(%d)\tsalary:(%f)",name,empid,salary);
}
fclose(fp);

getch();
}

You might also like