0% found this document useful (0 votes)
10 views11 pages

File Handling in C

The document provides an overview of file handling in C, detailing various operations such as opening, closing, reading, writing, and deleting files. It explains the FILE structure and functions from the <stdio.h> header file, including fopen, fclose, putw, getw, and others, along with their syntax and examples. Additionally, it includes assignments and project examples related to file handling operations.

Uploaded by

Sandeep sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views11 pages

File Handling in C

The document provides an overview of file handling in C, detailing various operations such as opening, closing, reading, writing, and deleting files. It explains the FILE structure and functions from the <stdio.h> header file, including fopen, fclose, putw, getw, and others, along with their syntax and examples. Additionally, it includes assignments and project examples related to file handling operations.

Uploaded by

Sandeep sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

AIM POINT INFOSYSTEM PVT. LTD.

2015

-:FILE HANDLING IN “C”:-

File Handling: Collection of same type information which stored permanently in secondary
memory(HDD,FDD) and File Handling is a mechanism which provide different kind of
operation on file.

Operation on File:

1. Open a File
2. Close File
3. Read from File
4. Write into File
5. Append File
6. Insert into File
7. Delete from File
8. Delete File
9. Update File
10. Sort File

FILE : FILE is a structure that define in file “stdio.h”. FILE structure manages the link between
our program and operating system and contains information about the file being used such as its
size in bytes , its location in memory, starting address, Ending address, File mode etc. Example:
FILE *fp;

FUNCTION DETAIL IN FILE HANDLING

Note : all function defined in < stdio.h> header file

fopen( ): Fill open a file in memory for reading or writing or both according to modE and return
a “pointer to structure FILE” ( base address of opned file ) .

Syntax: fopen ( “filename” , ”mod” );

Example: 1) fp=fopen(“number”,”r”); // File openfrom default path(c:\tc\bin)

2) fp = fopen ( “d:\\Aim\\number” , ”r” ); // File open from another path

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 1


AIM POINT INFOSYSTEM PVT. LTD. 2015

Mode: (for text files)

“r”: Open existing file in reading mode only .

“w”: Open existing file /new file in writing mode .

Note : if file is exist then all the contents of this file will be deleted in “w” mode and

new data will be overwrite

“a”: Open existing file / new file in append mode .

“r+”: Open existing file in reading / writing mode .

“w+”: Open existing file in reading / writing mode .

Note : if file is exist then all the contents of this file will be deleted in “w” mode and

new data will be overwrite

“a+”: Open existing file in append / reading mode and return its address ,otherwise return
NULL.

“b” : Open file in binary mode and return its address ,otherwise return NULL.

Mode: (for binary files)

“rb”, “wb”, “ab”, “rb+”, “wb+”, “ab+”

fclose( ) : use to close an open file.

Example : fclose(fp);

putw( ) : use to write a integer( 2 bytes ) into a file

Example: putw( no , fp ) ;

getw( ): use to read a integer (2 byte ) from a file.

Example: no=getw(fp);

putc( ): use to write a character into a file.

Example: putc(ch,fp);

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 2


AIM POINT INFOSYSTEM PVT. LTD. 2015

getc( ) : use to read a character from a file.

Example: ch=getc( fp ) ;

fprintf( ): use to print formatted data into file.

Example: fprintf ( fp ,”\n %d %s %d %f ”, rolno , name , marks , per ) ;

fscanf( ): use to read the formatted data from file.

Example: fscanf( fp , ”%d%s%d%f” , &rolno , name , &marks , &per ) ;

fwrite( ): use to write structured dat (the number of specified bytes in binary mode) into file.

Syntax: fwrite( &var , sizeof( var) , no of record , file pointer);

struct student s ;

Example: fwrite( &s , sizeof(s) , 1 , fp ) ;

fread( ): use to read the structured data ( number of specified bytes in binary mode ) from file.

Syntax: fread (&var , sizeof( var) , no of record , file pointer ) ;

struct student s ;

Example: fread ( &s , sizeof(s) , l , fp ) ;

feof( ): This function use to check the position of “file pointer” in file. Return non-zero if

pointer at end of file otherwise return zero.

Example: feof ( fp ) ;

rewind( ): Set the file pointer at beginning of file.

Example: rewind(fp);

ftell( ): Return the current position of file pointer in file.

Example: long int pos ;

Pos=ftell ( fp ) ;

fseek( ): Set the position of file pointer at specified byte in opened file .
Syntax: fseek ( file pointer , no of bytes , from ) ;
Value of ‘from’ SEEK_SET / 0 from starting
SEEK_CUR / 1 from current position
SEEK_END / 2 from end of file

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 3


AIM POINT INFOSYSTEM PVT. LTD. 2015

remove( ) :- it’s a function of <stdio.h> header file,which is used to remove file from secondary
memory(HDD).
Syntex : remove(“file name or path”);

6)rename( ) :- it’s a function of <stdio.h> header file,which is used to rename file from one
name to another name.
Syntex :

rename(“source file name”,“target file name ”);

//Write some integer into a file //Read integer from a file and display on monitor

#include<stdio.h> #include<stdio.h>

#include<conio.h>
#include<conio.h>
void main()
void main( )
{ int no;
{ int no,tno,i;
FILE *fp;
FILE *fp;
printf("\nEntry in files are:\n");
printf("\nHow many no write into file");
fp=fopen("number","rb");
scanf("%d",&tno);
if(fp==NULL)
fp=fopen("number","wb");
{ printf("\nUnable to open file...");

return; }
for(i=1;i<=tno;i++)
while(!feof(fp))
{ printf("\nEnter %d number : ",i);
{ no=getw(fp);
scanf("%d",&no); printf(" %d",no); }
putw(no,fp); }
fclose(fp);
fclose(fp); }
printf("\nOne file created");

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 4


AIM POINT INFOSYSTEM PVT. LTD. 2015

ASSIGNMENT:

1. WAP to create a file of int and write 30 numbers.


2. Open file “number” – “r” and create three files even, odd and prime in “w” mod. Read
one by one int from “number” and write according status.
3. Open all four files and display no. on monitor.

//Write char data into a text file //Read the content of a text file and display on monitor

#include<stdio.h> #include<stdio.h>

#include<conio.h> #include<conio.h>

void main()
void main()
{ char ch; int i;
{ char s1[100];
FILE *fp;
int i=0; FILE *fp;
char fname[30];
printf("\nEnter a String:- ");
printf("\nEnter file name which content you want to read:");
gets(s1);
scanf("%s",fname);
fp = fopen ( "str.txt" , "w" );
fp=fopen(fname,"r");
while(s1[i]!='\0')
if(fp==NULL)
{ putc(s1[i],fp);
{ printf("\nUnable to open file...");
i++ ; }
return; }
printf("\n One file created");
while((ch=getc(fp))!=EOF)
fclose(fp); { printf("%c",ch); }
} fclose(fp);

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 5


AIM POINT INFOSYSTEM PVT. LTD. 2015

//Read the content of a text file and write into another file

#include<stdio.h>
//Write formatted data into file
#include<conio.h> #include<stdio.h>
void main() #include<conio.h>

{ char ch,fname[30],fname1[30]; void main()

int i; { int ino,price,tno,i; char name[30];

FILE *fp,*fp1; FILE *fp;

printf("\nEnter Source file name:"); printf("\n\nHow many records write into file? ");

scanf("%s",fname); scanf("%d",&tno);

printf("\nEnter Destination file name:"); fp=fopen("record","w");

for(i=1;i<=tno;i++)
scanf("%s",fname1);
{ printf("Enter %d Record (Record no,name,price): ",i);
fp=fopen(fname,"r");
scanf("%d%s%d",&ino,name,&price);
fp1=fopen(fname1,"w");
fprintf(fp,"\n%d %s %d",ino,name,price);
if(fp==NULL)
}
{ printf("Unable to open Source file...");
fclose(fp);
return;
printf("\n One file created");
}
}
while((ch=getc(fp))!=EOF)

{ putc(ch,fp1); }

fclose(fp);

fclose(fp1);

printf("One file Copied");

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 6


AIM POINT INFOSYSTEM PVT. LTD. 2015

//Read formatted data from file

#include<stdio.h>

#include<conio.h>

void main()

{ int ino,price,tno,i; char name[30];

FILE *fp;

fp=fopen("record","r");

if(fp==NULL)

{ printf("\nUnable to open file...");

return;

while(fscanf(fp,"%d%s%d",&ino,name,&price)!=EOF)

{ printf("\n%d %s %d",ino,name,price); }

fclose(fp);

ASSIGNMENT:

 WAP to open any text file and count no. of alphabet, no. of uppercase ch., no. of l
lowercase ch., no. of punctuation, no. of space.
 WAP to convert any uppercase file into lowercase file.
 WAP to concat two files into third file.
 WAP to count white spaces (‘\n’, ‘\t’,’ ‘, backspace etc.).

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 7


AIM POINT INFOSYSTEM PVT. LTD. 2015

//Project on file handling//

#include<stdio.h> #include<conio.h> #include<alloc.h> #include<string.h>


struct record
{ int ino;
char iname[20];
int price; } ;
void add_rec( )
{ FILE *fp; struct record I;
fp=fopen("COMP","ab");
printf("\nEnter record to be Add : ");
scanf("%d%s%d",&I.ino,I.iname,&I.price);
fwrite(&I,sizeof(I),1,fp);
printf("\n Record Added");
fclose(fp);
}
void traverse_rec( )
{ FILE *fp; struct record I;
fp=fopen("COMP","rb");
if(fp= =NULL)
{ printf("\nSorry file not found...");
return; }
while(fread(&I,sizeof(I),1,fp))
printf("\n%d %s %d",I.ino , I.iname , I.price ) ;
fclose(fp);
}
void search_rec( )
{ FILE *fp; struct record I;
int icode;
fp=fopen("COMP","rb");
if(fp==NULL)
{ printf("\nSorry file not found...");
return; }
printf("\nEnter Record no to be search : ");
scanf("%d",&icode);
while(fread(&I,sizeof(I),1,fp))
{ if(icode==I.ino)
{ printf("\nCongrates Record Found !\n");
printf("\n%d %s %d", I.ino , I.iname , I.price ) ;
fclose(fp);
return; } }
printf("\nSorry Record not found!");
fclose(fp);
}// end of search_rec() fn

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 8


AIM POINT INFOSYSTEM PVT. LTD. 2015

Insertion procedure in file


void insert_rec( ) Step 1 : open original file in reading mode(“r”)
{ FILE *fp1,*fp2; and temporary file in writing mode (“w”)
struct record I , t ; Step 2 : copy all the records from original file into
int icode,flag=0; temporary file upto the record ,after which
we want to insert a new record
fp1=fopen("COMP","rb"); step 3 : write inserted record in temporary file .
if(fp1==NULL) step 4 : copy remaining records from original file
{ printf("\nSorry file not found..."); into temporary file .
return; } step 5 : close both files in HDD .
fp2=fopen("TEMP","wb"); step 6 : remove original file , and rename
“temporary file name” to “original file name “
printf("\nEnter Record no, after which you want…. ");
scanf("%d",&icode);
while(fread(&t,sizeof(t),1,fp1))
{ fwrite(&t,sizeof(t),1,fp2);
if(icode==t.ino)
{ printf("Enter Record to be inserted(record no,record name,price): ");
scanf("%d%s%d",&I.ino,I.iname,&I.price);
fwrite(&I,sizeof(I),1,fp2);
printf("\nRecord Inserted");
flag=1; }
}
if(flag==0)
printf("\nSorry %d record no not found",icode);
fclose(fp1);
fclose(fp2);
remove("COMP");
rename("TEMP","COMP");
}// end of insert_rec() fn
void delete_rec( )
Deletion procedure in file
{ FILE *fp1,*fp2; struct record t; Step 1 : open original file in reading
int icode,flag=0; mode(“r”) and temporary file in
fp1=fopen("COMP","rb"); writing mode (“w”)
if(fp1==NULL) Step 2 : copy all the records from original file
into temporary file except the the
{ printf("\nSorry file not found...");
record , which we want to delete .
return; } step 3 : close both files in HDD .
fp2=fopen("TEMP","wb"); step 4 : remove original file , and rename
printf("\nEnter Record no to be deleted : "); “temporary file name” to “original file name
scanf("%d",&icode); “
while(fread(&t,sizeof(t),1,fp1))
{ if(icode!=t.ino)
fwrite(&t,sizeof(t),1,fp2);

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 9


AIM POINT INFOSYSTEM PVT. LTD. 2015

else
{ printf("\nRecord Deleted");
flag=1; }
}
if(flag==0)
printf("\nSorry %d record no not found",icode);
fclose(fp1);
fclose(fp2);
remove("COMP");
rename("TEMP","COMP");
} // end of delete_sort() fn

void update_rec( )
{ FILE *fp; struct record t,I;
Updation procedure in file
int icode,flag=0; Step 1 : open original file in reading mode(“r”) and in
fp=fopen("COMP","rb"); writing mode (“w”), so we can perform reading as well
if(fp==NULL) as writing operation
{ printf("\nSorry file not found..."); Step 2 : first read one by one record in file by FILE
POINTER upto the record ,which we want to update
return; }
step 3 : MoveFILE POINTER into file up to the record to
printf("\nEnter Record no to be updated : "); be updated
scanf("%d",&icode); step 4 : perform updation operation in object and over
while(fread( &t , sizeof(t) , 1 , fp) ) write into file .
{ if(icode= =t.ino) step 5 : close file .
{ printf("\nEnter new price : ");
scanf("%d", & t . price);
fseek(fp , -sizeof( t ) , 1 ) ;
fwrite(&t,sizeof(t),1,fp);
printf("\nRecord updated");
flag=1; }
}
if(flag==0)
printf("\nSorry %d record no not found" , icode ) ;
fclose(fp);
}// end of update_sort() fn

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 10


AIM POINT INFOSYSTEM PVT. LTD. 2015

void sort_rec( ) Sorting procedure in file


{ struct record t,*p; int nor,i=0,j; Step 1 : open original file in reading mode(“r”) .
FILE *fp; Step 2 : count no of records in file .
step 3 : create dynamic array ( for no of records ) on
fp=fopen("COMP","rb"); pointer
if(fp==NULL) step 4 : copy complete file in dynamic array
{ printf("\nSorry file not found..."); step 5 : perform sorting operation in this array
return; } step 6 : display this sorted dynamic array / copy this
fseek(fp,0,2); sorted dynamic array into another file
step 7 : close file
nor=ftell(fp)/sizeof(t);
p=(struct record *)malloc(nor * sizeof(struct record));
rewind(fp);

while(fread(&t,sizeof(t),1,fp))
{ p[i++]=t; }
for(i=0;i<nor-1;i++)
{ for(j=i+1;j<nor;j++)
{ if(p[ j ] . price< p [ i ] . price)
{ t=p[ i ]; p[i]=p[ j ]; p[ j ]= t ; }
} }
printf("\nSorted files are :\n");
for(i=0;i<nor;i++)
printf("\n%d %s %d" , p [i] . ino , p[i] . iname , p[i] . price ) ;
free(p); fclose(fp) ; } // end of sort_rec() fn
void main( )
{ int ch;
do
{ printf("\n**MENU**\n"); case 4 : insert_rec( );
printf("\n 1 Add Record"); break;
printf("\n 2 Traverse Record"); case 5 : delete_rec( );
printf("\n 3 Search Record"); break;
printf("\n 4 Insert Record"); case 6 : update_rec( );
printf("\n 5 Delete Record"); break;
printf("\n 6 Update Record"); case 7 : sort_rec( );
printf("\n 7 Sort Records"); break;
printf("\n 0 Exit"); case 0 : break ;
printf("\n Enter your choice"); deafault : printf(“\n Invalid Choice “);
scanf("%d",&ch); } // end of switch
switch( ch ) } while ( ch != 0 ); // end of while
{ case 1 : add_rec( ); } // end of main fn
break;
case 2 : traverse_rec( );
break;
case 3 : search_rec( ); // END OF FILE HANDLING //
break;

FACULTY : SANDEEP SAHU( M.Tech(CSE)) Page 11

You might also like