File Management in C
File Management in C
File Management
We have been using the functions such as printf and scanf to read and write data. This works fine as long as data is small. But it has two major problems:
It becomes cumbersome and time consuming to handle large volume of data through terminals. The entire data is lost when either the program is terminated or the computer is turned off.
Prepared By: Vinod Pillai Chaudhari Technical Institute - Gandhinagar
File Management
So it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying data. This concept is called files. Files: A file is a place on the disk where a group of related data is stored.
FILE is a structure declared in stdio.h . We have to use file pointer, a pointer variable that points to a structure FILE.
Prepared By: Vinod Pillai Chaudhari Technical Institute - Gandhinagar
3
C File Management
C supports a number o functions that have the ability to perform basic file operations:
Creating a file Opening a file Reading data from a file Writing data to a file Closing a file Renaming a file Deleting a file
Prepared By: Vinod Pillai Chaudhari Technical Institute - Gandhinagar
4
Using Files in C
Declaration of File Pointer
FILE *fp; FILE *fp1; Opening a File
fp=fopen(one.txt,r);
Using Files in C
Closing Files
fclose(fp);
r+b = Open binary file for read/write w+b= Create binary file for read/write a+b= Append binary file for read/write
7
fgets()
fgetc() fread()
fputs()
fputc() fwrite()
8
10
Programs
Example 4 : Count the number of characters and number of lines.
Example 6: Compare two files.
11
Programs
while(ch1!=EOF && ch2!=EOF && ch1==ch2) { ch1=getc(fp1); ch2=getc(fp2); }
if(ch1 == ch2) { printf(Same); } else if(ch1 != ch2) { printf(Not Same); } fclose(fp1); fclose(fp2);
12
Programs
Example 7: Copy one file to another. fprintf() : Writing to a file
fscanf() : Reading content from file
FILE *fp1;
fp1=fopen(one.txt,w);
13
Programs
FILE *fp1; char name[30]; int value;
fp1=fopen(one.txt,r); fscanf(fp1,%s, name); fscanf(fp1,%d,value); fclose(fp1);
Binary Files
FILE *fp1,*fp2; fp1=fopen(one.txt,rb); fp2=fopen(two.txt,wb);
int ch;
if(!feof(fp1)) { fputc(ch,fp2); } else { break; }
}
While(1) { ch=fgetc(fp1);
fclose(fp1); fclose(fp2);
15
16
IMP Programs
Example 16.
Example 17.
18
fclose(fp);
20
21
0 = Successfully
Starting Point:
Non-Zero = Error
SEEK_SET ( 0 Beginning File)
22
23
Renaming a File:
int rename(old_name,new _name);
0 = Success 1 = Failure
0 = Success 1 = Failure
24
References
Programming in ANSI C Edition 2.1 by E Balagurusamy.
Programming in C by Paradip Dey & Manas Ghosh.
25