Files in C
Files are used to store data’s in the secondary memory(eg:- hard disk,
floppy, flash disk etc).
There are various file operations that can be done in C like Creating a
file, deleting a file, renaming a file, opening a file to read/write/append
data’s etc.
Syntax for declaring a file pointer in C
FILE
*file_pointer;
|
Where,
FILE = keyword
*fp = user defined file pointer variable.
Once the file pointer is declared next step is to create/open a file.
Creating / opening a file in C
fopen() is used to
open a specified file from disk, if it exist. If it doesn’t exist a new file
will be created and opened for further file operations.
Syntax for fopen() in C
fp=fopen(“file_name
with extension”,”mode”);
|
fp= user defined file pointer variable.
filename= name of the file with file type as extension.
mode= mode in which the file is to be opened.
Eg :-
To Read – “r”, To Write - “w”, To Append – “a”
To Read & Write – “w+”, To Read and write – “ r+”
To Read Write with append – “a+”
In w+ mode the contents in existing file is destroyed and then can perform read/write operations.
In r+ mode just read and write operations can be performed.
In a+ mode we can perform read and write operations with appending contents. So no existing data’s in a file are destroyed.
Eg :-
fp=fopen(“data.txt”,”a+”);
After a file is opened, we have to perform read or wrote operations into it.
Writing to a file in C
fprintf()
fprintf() is used
to write data’s to a file from memory.
Syntax for fprintf()
fprintf(file
pointer,”control string”,variables);
|
Reading from a file in C
fscanf() is used
to read data from a file to the memory.
Syntax for fscanf()
fscanf(file
pointer,”control string”,variables);
|
Closing a file in C
fclose() is used
to close a file in C.
Syntax for fclose()
fclose(fp);
|
Reading and Writing to a file in C
Sample
Program :fprintf_fscanf.c
#include<stdio.h> #include<conio.h> void main() { FILE *fp; char c[60]; int no,n; fp=fopen("data2.txt","a+"); printf("Enter the Employee Name and No : "); scanf("%s %d",c,&no); fprintf(fp,"\n\n%s\n%d",c,no); rewind(fp); printf("Enter the Employee No : "); scanf("%d",&n); while(!feof (fp)) { fscanf(fp,"%s %d",c,&no); if(no==n) { printf("\n%s \n %d",c,no); } } fclose(fp); getch(); } |