File handling
in C
Files
A file is a collection of related data placed on the disk.
File handling in C
High Level Low Level
(Stream oriented files (System oriented files)
Or Standard file)
Data files can be stored in two ways
Data files
Text format Binary format
• Data is stored as lines of characters • Data is stored on the disk in same way
terminated by ‘\n’ or ‘\r’ (carriage return) as represented in the computer memory.
• Human readable form • Not human readable form
• Created and read by any text editor • Created and read by specific program
e.g. integer 1679 takes 4 bytes in text file. e.g. integer 1679 takes 2 bytes in binary file.
Because it is stored as a sequence of • Hexadecimal of 1679 is 0x068F and
Characters i.e. ‘1’, ’6’, ’7’, ’9’ represented by two bytes 0x06, 0x8F.
• Hexadecimal of 1679 is represented by 0000, 0110, 1000, 1111
The bytes 0x31, 0x36, 0x37, 0x39 (ASCII)
0011, 0001, 0011, 0110, 0011,0111,0011,1001
3
Concept of Buffer
• Buffer is an area in memory where the data is
temporarily stored before written to the file.
• File pointer is associated while opening a file.
User Data send Buffer RAM Saved in file
• When buffer full, data are written to the file.
• Flushing the buffer - Writing the contents to the file
4
File operation in C
• Open a File
1.
• Read the file or
• Write data in the file
2. • Append to a file
• Close the file
3.
5
Opening a File
• Process of establishing a connection between the
program and file is called opening a file.
• A file must be opened before any I/O operations
can be performed on that file.
• A structure named FILE contains all Hidden from
programmer
information about the file like name, typedef struct {
status, buffer size, current position, -------,
-------
end of file etc. --------
• A file pointer is a pointer to a --------
structure of type FILE. } FILE; 6
Opening a File in mode
Possible values of mode in opening a file:
Mode Meaning
Write: create a new file for writing if file does not exist.
“w” New data is to write to existing file after erasing old contents.
Append: create a new file if file does not exist.
“a” New data is to append at the end of last contents to the file.
Read: open an existing file in reading purpose only.
“r”
Write + Read : read and modify the data if file exist.
“w+” Create a new file if file does not exist . (same as “w”)
Read + Write: write and modify existing data of existing file.
“r+” Also known as update mode. (same as “r”)
Append + Read: a new file is created if file does not exist.
“a+” New data is created if file does not exist. No modification to existing data.
New data is appended at the end of existing data if file exists. 7
Opening a file in binary mode
To open a file binary mode: put ‘b’ next to the mode specifies
Binary mode Meaning
“wb” Binary file opened in write mode
“ab+” or “a+b” Binary file opened in append mode
“rt+” or “r+t” Text file opened in update mode
“w” Text file opened in write mode
8
Opening a File: fopen()
Declaration:
FILE *fopen (const char *filename, const char *mode);
Sample code:
FILE *fp;
fp= fopen(“myfile.txt”, “w”);
// fp=fopen(“e:\\books\\Let-Us-C.txt”, “r”);
if(fp==null)
{
printf(“error in opening a file”);
exit(1);
} 9
Closing a File: fclose()
• A opened file must be closed when no more
operations are to be performed on it.
Declaration: int fclose (FILE *fp);
• fclose() returns 0 (zero) on success and
EOF(end of file, constant value -1) on error
Sample code: EOF is returned by
n= fclose(fp); /* n=fcloseall(); */ file reading function
if(n==EOF) When end of file is
printf(“Error:could not close all opened files”); reached
else
printf(“%d files successfully closed”, n);
Functions used for File I/O
Input/Output Used in Functions
Formatted I/O fscanf(), fprintf()
Record I/O fread(), fwrite()
Integer I/O getw(), putw()
String I/O fgets(), fputs()
Charcater I/O fgetc(), fputc(), getc(), putc()
11
Random Access to File
• So far we have used only sequential access in our
programs.
e.g. to access 43rd record then first 42 records should be read
sequentially to reach the 43rd record.
• In random access, data can be accessed and processed
randomly.
e.g. in this case, 43rd record can be accessed directly.
Random access file processing
fseek() ftell() rewind()
12
File Position Pointer
• File position pointer points to a particular byte in
the file and all read and write operations on the
file take place at this byte.
• This pointer automatically moves forward when a
read or write operation takes place.
• To access the data randomly, we have to take
control of this position pointer.
13
fseek()
• Used for setting the file position pointer at the specified byte.
Declaration:
int fseek(FILE *fp, long displacement, int origin);
where fp = file pointer
displacement= long integer is which may be +ve or –ve and denotes the
number of bytes which are skipped backward (if -ve) or
forward (if +ve) from the position specified in the third
argument.
origin= position relative to which the displacement takes place.
Origin can take one of these three values.
Value Constant Position
0 SEEK_SET Beginning of file
1 SEEK_CURRENT Current Position
14
2 SEEK_END End of file
fseek() example
#include<stdio.h> /* use of fseek()*/
#include<conio.h> /*skip n-1 records*/
#include<stdlib.h> fseek(fp,(n-1)*sizeof(student),0);
struct record { /* read the nth record*/
char name[20]; fread(&student,sizeof(student),1,fp);
int roll; printf("%s\t",student.name);
float marks; printf("%d\t",student.roll);
}student; printf("%.2f\t",student.marks);
int main() { fclose(fp);
int n; getch();
FILE *fp; return 1;
fp=fopen("stu.dat","rb"); }
if(fp==NULL) {
printf("\n Error: File can't be opened.");
exit(1);
Output:
}
Enter the nth(randomly) record to be read: 3
printf("\n Enter the nth record to be read\n");
scanf("%d",&n);
3rd record will be fetched from “stu.dat” file
15
ftell()
• ftell() function returns the current position of the file
position pointer.
• Value is counted from the beginning of the file.
• On error, ftell() returns -1L and set errno to a +ve
value.
Declaration:
long ftell(FILE *fp);
16
ftell() example
#include<stdio.h> printf("\n position pointer in the beginning -> %ld\n",ftell(fp));
#include<conio.h> while(fread(&student,sizeof(student),1,fp)==1)
#include<stdlib.h> {
struct record { printf("\n\n Position pointer -> %ld::::\t",ftell(fp));
char name[20]; printf("%s\t",student.name);
int roll; printf("%d\t",student.roll);
float marks; printf("%.2f\t",student.marks);
}student; }
int main() { printf("\n\n\n size of file in bytes is %ld\n",ftell(fp));
int n; fclose(fp);
FILE *fp;
fp=fopen("stu.dat","rb");
getch();
return 1; Output: Opening a file “stu.dat”
if(fp==NULL) } Position pointer in the beginning -> 0
{
printf("\n Error: File can't be opened."); Position pointer->28:::: ajay 11 89
exit(1); Position pointer->56:::: vijay 12 99
} Position pointer->84:::: sanjay 13 100
Size of file in byte is 84 17
rewind()
• Used to move the file position pointer to the
beginning of the file.
• Rewind() is used to update an opened file.
• Rewind(fp) is equivalent to fseek(fp,0L,0).
Declaration:
rewind(FILE *fp);
18
rewind() example
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> Output:
int main() {
FILE *fp; Position pointer set to 0
fp=fopen("stu.dat","rb+");
if(fp==NULL) {
printf("\n Error: File can't be opened.");
exit(1);
}
printf("\n\n Position pointer -> %ld::::\t",ftell(fp));
rewind(fp);
//fseek(fp,0,2);
printf("\n\n Position pointer -> %ld::::\t",ftell(fp));
rewind(fp);
printf("\n\n Position pointer -> %ld::::\t",ftell(fp));
fclose(fp);
getch();
return 1;
19
}
Formatted I/O: fprintf()
• Formatted I/O means formatting in files is generally
used to display data on terminal or print data in some
format.
• Same as printf() but fprintf() writes formatted data
into the file instead of the standard output (screen).
• On success, it returns the number of characters
output to the file.
• On error, it returns EOF.
Declaration:
fprintf(FILE *fp, const char *format*, argument, …+);
20
fprintf() example1
#include<stdio.h>
#include<conio.h> output;:
int main()
{ Open a file “rec.dat” in notepad
FILE *fp;
char name[10]; You see only one line
int age;
fp=fopen("rec.dat","w"); My name is xyz and age is xx
printf("\n enter your name and age\n");
scanf("%s%d",name,&age);
fprintf(fp,"My name is %s and age is %d",name,age);
fclose(fp);
getch();
return 1;
}
21
fprintf() example2
#include<stdio.h>
#include<conio.h> Output;
struct student {
char name[20]; Open a file “students.dat” in notepad
float marks;
} stu; You see name and age in a listed form
int main () {
FILE *fp;
int i,n;
fp=fopen("students.dat","w");
printf("\n Enter how many records: ");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("\n enter name and marks:");
scanf("%s%f",stu.name,&stu.marks);
fprintf(fp,"\n\n%s %f",stu.name,stu.marks);
}
fclose(fp);
getch();
return 1;
} 22
Formatted I/O: fscanf()
• Similar to scanf() but it reads data from file
instead of standard input
• On success, fscanf() returns the number of
arguments that were assigned some value .
• On error, it returns EOF at the end of file.
Declaration:
fscanf(FILE *fp, const char *format*, address, …+);
23
fscanf() example
#include<stdio.h>
#include<conio.h>
Output:
struct student {
char name[20]; All data are accessed from “students.dat”
float marks; and print like
}stu;
int main () NAME MARKS
{ -------------------------
FILE *fp; xxxxx xx
fp=fopen("students.dat","r"); xxxxxx xx
printf("\nNAME \t MARKS \n ");
printf(" ");
while(fscanf(fp,"%s%f",stu.name,&stu.marks)!=EOF)
printf("\n\n%s \t %f \n",stu.name,stu.marks);
fclose(fp);
getch();
return 1;
}
24
Record I/O: Block Read/Write
• Used to store block of data into file rather than
individual elements.
• Each block has fixed size. It may be array or structure.
• Easy to read the entire block from file or write the
entire block to the file.
• Although the two functions fread() and fwrite() can be
used to read or write any type of data varying from a
single character to arrays and structure.
• File is generally opened in binary mode (e.g. “wb”,”rb”)
25
Record I/O: fwrite()
Declaration:
size_t fwrite(const void *ptr, size_t size, size_t n,FILE *fp);
where
size_t is defined as typedef unsigned int size_t;
ptr = a pointer which points to a block of memory that contains the
information to be written to the file,
size = denotes the length of each items in bytes,
n = number of items to be written to the file.
fp= a FILE pointer which points to the file to which the data is written.
• Used to write an entire block to a given file.
• On success, fwrite() will return n items or total (n * size)
bytes to the file and will return n.
• On error or end of file, it will return a number less than n.
fwrite() example
#include<stdio.h> printf("\n enter number of records:\n");
#include<conio.h> scanf("%d",&n);
#include<stdlib.h> for(i=0;i<n;i++)
struct record {
{ printf("\n enter name:");
char name[20]; scanf("%s", student.name);
int roll; printf("\n Enter Roll no.:");
float marks; scanf("%d",&student.roll);
} student; printf("\n Enter marks:");
scanf("%d",&student.marks);
int main() fwrite(&student,sizeof(student),1,fp);
{ }
FILE *fp;
int i,n;
fp=fopen("stu.dat","wb");
fclose(fp);
getch();
Output:
if(fp==NULL) { return 0; Open the file “stu.dat”
printf("\n Error in opening file"); }
exit(1);
with Notepad to See the
} record entered by user 27
Record I/O: fread()
Declaration:
size_t fread(void *ptr, size_t size, size_t n,FILE *fp);
where
size_t is defined as typedef unsigned int size_t;
ptr = a pointer which points to a block of memory that
receives the data read from the file,
size = denotes the length of each items in bytes,
n = number of items to be read from the file.
fp= a FILE pointer which points to the file from which the data is read.
• Used to read an entire block from a given file.
• On success, fread() will read n items from the file and return n
• On error or end of file, it will return a value less than n.
28
fread() example
#include<stdio.h> /* to see the output column-wise */
#include<conio.h> printf("\n NAME \t ROLL NO \t MARKS \n");
#include<stdlib.h> while(fread(&student,sizeof(student),1,fp)==1)
struct record { {
char name[20]; printf("%s\t ", student.name);
int roll; printf("%d\t",&student.roll);
float marks; printf("%d\n",&student.marks);
} student; }
fclose(fp);
int main() getch();
{ return 0;
FILE *fp; }
int i,n;
fp=fopen("stu.dat","rb");
if(fp==NULL) {
To see the output:
printf("\n Error in opening file");
exit(1); This file will automatically fetch all the data
} from “stu.dat” created earlier
29
Character I/O: fputc()
• fputc() function is used to write a character to
the specified file at the current file position
and increment the file position pointer.
• On success, it returns an integer representing
the character written.
• On error, it returns EOF.
Declaration:
int fputc(int ch, FILE *fp);
30
fputc() example
#include<stdio.h>
#include<conio.h> Output:
#include<stdlib.h>
int main() { Enter text
FILE *fp; (to stop, press ctrl+z):
int ch;
if((fp=fopen("myfile.txt","w"))==NULL) { Hi I am studying BTech (ME) first year.
printf("\n Error: file does not exist."); ^Z (press ctrl+z)
exit(1);
}
else { Now open file “myfile.txt”
printf("\n enter text\n( To stop, press ctrl+z):\n"); You find the same contents written
/* press ctrl+z to stop reading characters */ There.
while((ch=getchar())!=EOF)
fputc(ch,fp); Hi I am studying BTech(ME) first year
}
fclose(fp);
getch();
return 1; 31
}
Characater I/O: fgetc()
• fgetc() function is used to read a single
character from a given file and increment the
file pointer position.
• On success, it returns the character after
converting it to an int without sign extension.
• On error or end of file, it returns EOF.
Declaration:
int fgetc(FILE *fp);
32
fgetc() example
#include<stdio.h>
#include<conio.h> Output;
#include<stdlib.h>
int main() { Display the contents of file “myfile.txt”
FILE *fp;
int ch; Hi I am studying BTech (ME) first year.
if((fp=fopen("myfile.txt","r"))==NULL) {
printf("\n Error: file does not exist.");
}
else {
while((ch=fgetc(fp))!= EOF)
printf("%c",ch);
}
fclose(fp);
getch();
return 1;
}
33
Character I/O: putc()
• putc() function is used to write data to files.
• On success, it returns the character.
• On error, it returns EOF
• Declaration: putc(character, file pointer);
Character I/O: getc()
• getc() function is used to read the data from file.
• On success, it returns the next character from stream
or a EOF value if file reaches at the end.
• Declaration: getc(fp);
34
Example: getc() and putc()
35
Integer I/O: putw()
• putw() function writes an integer value to the
file pointed to by File pointer (fp).
• on success , It returns the integer written to
the file.
• On error, it returns EOF
Declaration:
int putw(int value, FILE *fp);
36
putw() example
#include<stdio.h>
#include<conio.h> To see the Output:
int main()
{ Open a file “num.dat” with notepad.
FILE *fp;
int value;
“num.dat” file will have a printed
fp=fopen("num.dat","wb"); number from 1 to 30
for(value=1;value<=30;value++)
putw(value,fp);
fclose(fp);
getch();
return 0;
}
37
Integer I/O: getw()
• getw() function returns the integer value from
the file associated with file pointer (fp).
• On success, it returns the next inetger from
the input file .
• On error, it returns EOF or end of file.
Declaration:
int getw(FILE *fp);
38
getw() example
#include<stdio.h> This file will read and print integers
#include<conio.h>
int main() from file “num.dat” which was created
{
FILE *fp;
earlier.
int value;
getw() will stop reading text file
fp=fopen("num.dat","rb"); because If 26 is present in the text file
while((value=getw(fp))!=EOF)
printf("%d\t",value); then file will understand the value of
EOF=26(ASCII) is there which EOF
fclose(fp); means it is an End Of File.
getch();
return 0;
} Moral: never use getw() with text file.
39
String I/O: fputs()
40
fputs() example
41
String I/O: fgets()
42
fgets() example
43
References
• C in Depth [BPB Publication],
Authors: S.K.Srivastava, Deepali Srivastava
44