File Handling in C
File Handling in C
1
• Introduction *Writing into a file
• File handling in C
* Writing simple data
• File handling commands * Writing structure data
• Opening and closing files
2
Introduction
3
What is a File?
• A named collection of data, typically stored in a secondary
storage (e.g., hard disk).
Examples
• Records of all employees in an organization
• Document files created using Microsoft Word
• Video of a movie
• Audio of a music
4
How a File is Stored?
• Stored as sequence of bytes, logically contiguous (may not be
physically contiguous on disk).
• Discrete storage unit for data in the form of a stream of bytes.
• Every file is characterized with a starting of file, sequence of bytes
(actual data), and end of stream (or end of file).
• Allow only sequential access of data by a pointer performing.
• Meta-data (information about the file) before the stream of actual
data can be maintained to have a knowledge about the data stored
in it.
5
How a File is Stored?
Start EOF
Meta Data 40 65 87 90 24 67 89 90 60 0
File pointer
Note:
• The last byte of a file contains the end end-of-file character
(EOF, with ASCII code 1A (Hex).
• While reading a file, the EOF character can be checked to
know the end.
6
Type of Files
• Text files
– Contain ASCII code only
• C-programs
• Binary files
– Contain non-ASCII characters
• Image, audio, video, executable, etc.
7
File Handling in C
8
Operations on Files
• Typical operations on a file are
• Open : To open a file to store/retrieve data in it
9
Opening and Closing a File
10
File Handling Commands
• Include header file <stdio.h> to access all file handling
utilities.
• A data type namely FILE is there to create a pointer to a file.
Syntax
FILE * fptr; // fptr is a pointer to file
11
fopen() function
• The first argument is a string to characters indicating the name of
the file to be opened.
• The convention of file name should follow the convention of giving file
name in the operating system.
Examples:
xyz12.c student.data File PDS.txt
myFile
12
fopen() function
• The second argument is to specify the mode of file opening.
There are five file opening modes in C
• "r" : Opens a file for reading
• "a" : Opens a file for appending - writing on the end of the file
13
fopen() function
• If a file that does not exist is opened for writing or appending, it
is created as a new.
• Opening an existing file for writing causes the old contents to be
discarded.
• Opening an existing file for appending preserves the old contents,
and new contents will be added at the end.
• File opening error
• Trying to read a file that does not exist.
• Trying to read a file that doesn’t have permission.
• If there is an error, fopen() returns NULL.
14
Example: fopen()
#include <stdio.h>
void main()
{
FILE *fptr; // Declare a pointer to a file
char filename[]= "file2.dat";
fptr = fopen(filename,"w");
// Also, alternatively
// fptr = fopen (“file2.dat”,"w");
if (fptr == NULL) {
printf (“Error in creating file”);
exit(-1); // Quit the function
}
else /* code for doing something */
}
15
Reading from a File
16
Reading from a File
• Following functions in C (defined in stdio.h) are usually used
for reading simple data from a file
• fgetc(…)
• fscanf(…)
• fgets(…)
• The fgetc() function returns the next character in the stream fptr as an
unsigned char (converted to int).
FILE *fptr;
int c;
/* Open file and check it is open */
while ((c = fgetc(fptr)) != NULL)
{
printf ("%c",c);
}
18
Reading from a File: fscanf()
Syntax for fscanf(…)
int fscanf(FILE *fptr, char *format, ...);
• fscanf reads from the stream fptr under control of format and assigns
converted values through subsequent assignments, each of which must be a
pointer.
• It returns when format is exhausted.
• fscanf returns EOF if end of file or an error occurs before any conversion.
19
Example: Using fscanf(…)
FILE *fptr; input.dat
fptr= fopen (“input.dat”,“r”);
int n; 20 30 40 50
/* Check it's open */
if (fptr == NULL)
{
printf(“Error in opening file \n”);
}
n = fscanf(fptr,“%d %d”,&x,&y);
x = 20
x = 30
...
20
Reading from a File: fgets(…)
Syntax for fgets(…)
char *fgets(char *s, int n, FILE *fptr)
s The array where the characters that are read will be stored.
n The size of s.
fptr The stream to read.
21
Example: Using fgets(…)
FILE *fptr;
char line [1000];
/* Open file and check it is open */
22
Writing into a File
23
Writing into a File
• Following functions in C (defined in stdio.h) are usually used
for writing simple data into a file
• fprintf(…)
• fputs(…)
void main()
{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);
fclose(fptr);
return;
}
• The fputs() function writes a string (which need not contain a newline) to
a file.
void main()
{
FILE *fptr;
fptr = fopen(“test.txt”, “w”);
fclose(fptr);
return;
}
{
int c;
main()
{
FILE *f1;
char c;
printf("Data Input\n\n");
/* Open the file INPUT */
Contd…
f1 = fopen("INPUT", "w");
30
Writing into a File
while((c=getchar()) != EOF) /* Get a character from keyboard*/
OUTPUT
putc(c,f1); /* Write a character to INPUT*/
Data Input
32
Special Streams
• When a C program is started, the operating system environment is
responsible for opening three files and providing file pointer for
them. These files are
Note:
getc(stdin) is same as fgetc (stdin)
33
Special Streams
printf(“"Hello World!\n");
34
Example: Special Streams
#include <stdio.h>
main()
{
int i;
OUTPUT
Give value of i
15
Value of i=15
35
Error Handling : stderr and exit
• What happens if the errors are not shown in the screen instead
if it's going into a file or into another program via a pipeline.
• To handle this situation better, a second output stream, called
stderr, is assigned to a program in the same way that
stdin and stdout are.
• Output written on stderr normally appears on the screen
even if the standard output is redirected.
36
Example: Error Handling
#include <stdio.h>
Contd…
37
Example: Error Handling
if (ferror(stdout)) {
fprintf(stderr, "%s: error writing stdout\n", prog);
exit(2);
}
exit(0);
}
38
Direct Input and Output
39
Structured Input/Output for Files
• Other than the simple data, C language provides the following
two functions for storing and retrieving composite data.
40
Writing Records: fwrite()
fwrite() writes data from the array pointed to, by ptr to the
given stream fptr.
Syntax:
41
Example: fwrite()
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
int ch;
struct Student Stu;
fp = fopen("Student.dat","w"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
Contd…
42
Example: fwrite()
do
{
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);
fwrite(&Stu,sizeof(Stu),1,fp);
}while(ch=='y' || ch=='Y');
fclose(fp);
}
Contd…
43
Example: fwrite()
OUTPUT
Enter Roll : 1
Enter Name : AA
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : BB
Enter Marks : 72.65
Do you want to add another data (y/n) : y
Enter Roll : 3
Enter Name : CC
Enter Marks : 82.65
Do you want to add another data (y/n) : n
44
Reading Records: fread()
fread() reads data from the given stream into the array pointed
to, by ptr.
Syntax:
45
Example: fread()
#include<stdio.h>
struct Student
{
int roll;
char name[25];
float marks;
};
void main()
{
FILE *fp;
int ch;
struct Student Stu;
fp = fopen("Student.dat","r"); //Statement 1
if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}
Contd…
46
Example: fread()
printf("\n\tRoll\tName\tMarks\n");
while(fread(&Stu,sizeof(Stu),1,fp)>0)
printf("\n\t%d\t%s\t
%f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);
}
OUTPUT
47
Random Accessing Files
48
File Positioning Functions in C
• When doing reads and writes to a file, the OS keeps track of where
you are in the file using a counter generically known as the file
pointer.
49
Random Accessing a File: ftell()
long ftell(FILE *fptr);
Example
long n;
n = ftell(fptr);
Note:
In this case, n gives the relative offset (in bytes) of the current position. This
means that n bytes have already been read (or written).
50
Random Accessing a File: fseek()
int fseek(FILE *fptr, long offset, int whence);
51
Example: fseek()
• You can set the value of whence to one of the three things:
52
Random Accessing a File: rewind()
void rewind(FILE *fptr);
Example
rewind (fptr); // Set the file pointer at the beginning
fseek(fptr, 0L, SEEK_SET); // same as the rewind()
53
fseek() vs. rewind()
Return value
• For fseek(), on success zero is returned; -1L is returned on
failure.
• The call to rewind() never fails.
Examples:
54
Examples
55
File Handling : Example
A program to copy a text file to another file.
1
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch, sourceFile[20], targetFile[20];
FILE *source, *target;
fclose(source);
fclose(target);
return 0;
}
57
File Handling : Example 2
A program to copy a text file to another file. Read the file names through command line.
#include <stdio.h>
#include <stdlib.h>
Contd…
58
File Handling : Example 2
target = fopen(argv[2], "w");
fclose(source);
fclose(target);
return 0;
}
59
File Handling : Example 3
A program to concatenate a file (say A) to another file (say B) so that the resultant file is A
= A+B. Read the file names for A and B through command line.
#include <stdio.h>
#include <stdlib.h>
Contd…
60
File Handling : Example 3
fpA = fopen(argv[1], “a"); //Open the file A in append mode
fclose(fpA);
fclose(fpB);
return 0;
}
61
File Handling : Example 4
A program to encrypt a text file. Read the file names through command line.
#include <stdio.h>
#include <stdlib.h>
Contd…
62
File Handling : Example 4
target = fopen(argv[2], "w");
fclose(source);
fclose(target);
return 0;
}
63
File Handling : Example 5
A program to display a file on the screen. Read the file name through command line.
#include <stdio.h>
#include <stdlib.h>
fclose(source);
return 0;
}
64
File Handling : Example 6
A program to store a record in file. Read the file and store all records in an array.
#include <stdio.h>
#include <stdlib.h>
struct Student {
int rollNo;
char name[20];
float marks;
};
Contd…
65
File Handling : Example 6
A program to store a record in file. Read the file and store all records in an array.
while (choice) {
data = (struct *)malloc(sizeof(struct Student));
if (data != NULL) {
printf(\nEnter Roll No: “); scanf(“%d”,&data->rollNo;);
printf(\nEnter Name: “); scanf(“%s”,data->name;);
fclose(outfile);
return 0;
}
Contd…
66
File Handling : Example 6
return 0;
}
67