File handling in C language Reviewed by Momizat on . A file is a collection of related information define by the user generally files represents program both source code and object code and data.The data may be nu A file is a collection of related information define by the user generally files represents program both source code and object code and data.The data may be nu Rating: 0

File handling in C language

A file is a collection of related information define by the user generally files represents program both source code and object code and data.The data may be numeric alphabetic or alpha numeric files may be free for such as text or format.In general a file is a secretes of bits,bytes,lines or records.whose meaning is define by it is created.A file is named and refereed to by its name.The operating system provides must of the essential file such as create,open,read,write,append,close etc.

C language allows the user to create data file and provide various facilities for the management of the file which is simply known as file handly.

In c language a file can be opened in three modes such as:-
(1) Read mode (r) - In read mode we can read or retrieve the informations of a file.
(2) Write mode (w) - In the mode a new file is created in the disk and write new information in it.
(3) Append mode (a) - In this mode new information can be store in a existing file.It doesn’t overwrite the old information.

FILE pointer - In c language a pointer type identifiers is required to hold the address of memory of a file which is known as file pointer and it is always declare as file type.
Syn:-FILE <*filename>;
EX:-FILE *mk;
fopen()-It opens a file in a specific mode.
Syn:-filepointer=fopen(“filename”,”mode”);
Ex:-mk=fopen(“filename.txt”,”r”);
fclose()-it is used to close a file.
Syn:-fclose(filepointer);
Ex:-fclose(mk);

Input or Output in a file:-
fprintf():-It is used to print the value of the variable in a file.
Syn:-fprintf(filepointer,”formate”,variable);
fscanf()-It is used to read information from a file and assign it in variable.
Syn:-fscanf(filepointer,”formate”,variable);

Ex-Create a file a student.txt to store name,roll, and course.

#include <stdio.h>
#include <conio.h>
#include <fstream.f>
main(){
	clrscr();
	FILE *fp;
	char n[10],cr[10];
	int d;
	fp=fopen("stud.txt","w");
	printf("Input name, roll, course:");
	scanf("%s%d%s",n,&d,cr);
	fprintf(fp,"%s\n%d\n%s",n,d,cr);
	fclose(fp);
	getch();
}

Ex-Display the information from stud.txt file.

#include <stdio.h>
#include <conio.h>
#include <fstream.f>
main(){
	clrscr();
	FILE *fp;
	char n[10],cr[10];
	int d;
	fp=fopen("stud.txt","r");
	fscanf(fp,"%s %d %s",n,&d,cr);
	printf(fp,"%s\n%d\n%s",n,d,cr);
	fclose(fp);
	getch();
}

Leave a Comment

© 2014 Powered By