C Programming File Handling PDF
C Programming File Handling PDF
in C
Files
A file is a collection of related data placed on the disk.
File handling in C
• 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
4
File operation in C
• Open a File
1.
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
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
13
fseek()
• Used for setting the file position pointer at the specified byte.
Declaration:
int fseek(FILE *fp, long displacement, int origin);
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
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
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.
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.
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);
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