Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

COMPUTER SCIENCE

12

CHAPTER 14: File Handling in C

Copyright @ IT Series www.itseries.com.pk


Topics
• Stream
• File Access Methods
• Use of Newline and EOF
• Data File
• Text file and Pointer
• File Pointer
• Opening a File
• Closing a File
• fputc Function
• fgetc Function
• String
• String Assignment in C
• fputs function
Copyright @ IT Series www.itseries.com.pk
Topics(Cont.)
• fgets Function
• Formatted File Input and Output
• fprintf Function
• fscanf Function

Copyright @ IT Series www.itseries.com.pk


 A logical interface to a file
 It is flow of data
 Input stream is a sequence of characters from an input device to computer
 Output stream is a sequence of characters from computer to output device
 A stream is associated with a file using an open operation
 Stream is disassociated from a file using a close operation

Types of Stream
 Text stream
 Binary Stream

Copyright @ IT Series www.itseries.com.pk


• A sequence of characters
• A certain character translation may occur in a text stream
• Example
Text Stream • A new line may be converted to a carriage return
• It means that there may not be a one to one relationship between
written characters

• A sequence of bytes
• Translation is not performed in binary stream
Binary Stream • It exists with a one to one correspondence to the external devices
• It means that the number of bytes written or read is the same as the
number of bytes on the external device

Copyright @ IT Series www.itseries.com.pk


Text Stream Binary Stream
Sequence of characters Sequence of bytes

Does not have one to one Has one to one relationship


relationship with external devices with external devices

A certain character translation may No translation occurs in binary


occur stream

Less efficient than binary stream More efficient than text stream

Can be used for different types


Can be used only for text data
of data

Copyright @ IT Series www.itseries.com.pk


File Access Method
 The way in which file can be accessed
 Sequential Access Method
 Used to access data in the same sequence in which it is stored in file
 This method reads and write data in a sequence
 In order to read the last record, it has to read all records stored before the last one
 Slow and time consuming method
 Search operation with sequential access method take lot of time
 Random Access Method
 Used to access any data item directly without accessing the preceding data
 Does not read or write data in sequence
 Very fast access method as compared to sequential method
 A searching operation with random access method takes far less time to find data item

Copyright @ IT Series www.itseries.com.pk


 EOF
 EOF (end-of-file) is a is special character

 Indicate the end of text file

 Placed after the last character in the file

 Added automatically at the end of the file

 Frequently used in C programs to find the end of file

Example
While( ( ch==fgetc(in) ) !=EOF)
Printf(“%c”, ch);

 The above loop will continues to execute until it finds the EOF character

Copyright @ IT Series www.itseries.com.pk


 New Line
 A newline character is placed at the end of each line when the user presses Enter key
 Denoted by \n in C

Example
 Use of newline and EoF marker

Copyright @ IT Series www.itseries.com.pk


 Data File
 A data file is a collection of related records

 A record contains data about an entity

 Data file can be used to save any type of data

 Use of Data Files


 Data file can be used to provide input to a program

 It can be used to store output of a program permanently

 If a program gets input from a file , it will get the same data each time for execution

Copyright @ IT Series www.itseries.com.pk


 Text Files
 A type of file that stores data as readable and printable charcters
 A source program of C language is an example of text file
 User can easily view and read the contents of a text file
 It can also be printed to get hard copy
 Pointer
 A type of variable that is used to store the memory address of another variable
 Data type of pointer must be same as data type of the variable whose memory address is stored in
pointer
 Declared in the similar way as ordinary variable except an asterisk (*) is placed before pointer
variable or after data type
 int* var;
 & operator is used to get a memory address of a variable and assign to pointer variable through
assignment statement
 var= #

Copyright @ IT Series www.itseries.com.pk


Example
#include <stdio.h>
#include <conio.h>
void main()
{ int* var;
int num = 25;
crlscr();
var = &num;
printf("Address of variable num is %x", &num);
printf("\nContents of num is %d", num);
printf("\nAddress of memory location pointed to by var is %x", var);
printf("\nContents of memory pointed by var is %d", *var); }

Working of above Program


The pointer var stores the memory address of num. It does not store its value. The ampersand '&' is used
to assign the memory address of num to var. The memory address fff4 in the output may be different in
each execution of the program. It is because the memory addresses are assigned when the program is
executed.

Copyright @ IT Series www.itseries.com.pk


File Pointer
• File pointer is a pointer that refers to a file on the secondary storage
• It is a variable that is defined in stdio.h
• Used to access and manipulate a data file
• Program has to declare a file pointer to use a file
• Pointer is associated with a file after declaration
• One file pointer can be associated with only one data file

Syntax
FILE *MyFile;
 The identifier MyFile is a file pointer
 FILE is the type of MyFile pointer
 The symbol '*' indicates that it is a pointer to a file structure

Copyright @ IT Series www.itseries.com.pk


• A file should be opened before it can be processed
• All standard file handling functions of C are declared in stdio.h
• It must be included in almost every program
• File pointer is declared and associated with the file to be opened
• A function fopen is used to open a file

Syntax
File_Pointer = fopen(File_Name, Mode);
File_Pointer It is the name of file pointer declared in the program
File_Name It is name of data file to be opened. It can be string variable or string constant
If the specified file does not exist, it is created and opened
Mode It indicates the mode in which the file is to be opened

Copyright @ IT Series www.itseries.com.pk


Modes of Opening Files
r The file is opened in read mode
The data can be read but cannot be written or modified
The file must exist already
w The file is opened in write mode
The data can be written to the file
The existing data in the file is destroyed
a The file is opened in append mode
The new data is written at the end of existing data
The data cannot be read in this mode
r+ The file is opened in read/write mode
The data can be read and written to a file
The file must exist already
Copyright @ IT Series www.itseries.com.pk
Modes of Opening Files
w+ The file is opened in read/write mode
The data can be written to the file
The existing data in the file is destroyed
The data can also be read.
a+ The file is opened in append mode
The new data is written at the end of existing data
The existing data can also be read.
Example
FILE MyFile;
MyFile = fopen("book.txt", "w");
 The above example declares a file pointer MyFile
 Uses fopen function to open the file book.txt in write mode

Copyright @ IT Series www.itseries.com.pk


Verifying File Open
• An error may occur while opening a file

• fopen function returns NULL if an error occurs during opening a file

• It can be used to verify that the file is opened successfully

FILE MyFile;

If((MyFile = fopen("book.txt", "w")) == NULL);

printf("File Open Error!");

• The above condition becomes true if there is any error during opening the file

• If there is no error, the condition becomes false and no message is displayed

Copyright @ IT Series www.itseries.com.pk


• When a file is opened, a connection is established between the file and program
• After processing the file, connection is terminated
• When a file is closed, the file pointer is destroyed in memory
• Closing of a file is optional
• If it is not closed, operating system automatically closes it when program finishes
• Each opened file occupies memory
• Closes of file releases the memory occupies by file
• A file is closed by using fclose statement
• Function disconnects the opened file form the program
Syntax
fclose(File_Pointer);

• fclose is the function that closes a file


• File_Pointer is a file pointer that refers to the file to be closed

Copyright @ IT Series www.itseries.com.pk


• Data can be written to a file one character at a time
• Fputc function is used for this purpose
fputc Function • Syntax
• fputc(char, File_Pointer);

• Data can be written to a file as string


• Fputs function is used for this purpose
fputs Function • Syntax
• fputs(string, File_Pointer);

• Data can be written to afile as formatted input


• Fprintf function is used for this purpose
fprintf Function • Syntax
• fprintf(File_Pointer, Control_String, Write_List);

Copyright @ IT Series www.itseries.com.pk


• Data can be written to a file one character at a time using fputc function
Syntax
fputc(char, File_Pointer);
char It is the character to be written to text file
File_Pointer It is a file pointer that refers to the file in which the character will be written

Example
void main()
{ FILE *out;
char ch;
clrscr();
out = fopen("c:\\test.txt", "w");
printf("Enter a character (. to end): ");
ch = getche();
while(ch != '.')
{ fputc(ch, out);
ch = getche(); }
fclose(out); }

Copyright @ IT Series www.itseries.com.pk


Data can be read from text file one character at a time by using fgetc function
Syntax ch = fgetc(File_Pointer);
File_Pointer It is the file pointer that refers to a file
fgetc It is the function to read the file character by character
ch It is a variable that store the character that is read from the file

Example
void main()
{ FILE *in;
char ch;
clrscr();
if((in = fopen("c:\\test.txt", "r"))==NULL)
printf("File opening error.");
while((ch = fgetc(in)) != EOF)
printf("%c",ch);
fclose(in);
getch(); }

Copyright @ IT Series www.itseries.com.pk


Program 14.1
Write a program that inputs characters from the user and appends it in an existing file.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out;
char ch;
out = fopen("c:\\test.txt", "a");
fputc('\n', out);
printf("Enter a character (. to end): ");
ch = getche();
while(ch != '.')
{
fputc(ch, out);
ch = getche();
}
fclose(out);
}
Copyright @ IT Series www.itseries.com.pk
Program 14.2
Write a program that copies contents of one file to another file character by character.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out, *in;
char ch;
clrscr();
if((in = fopen("c:\\ctest.txt", "r"))==NULL)
printf("File opening error.");
out = fopen("c:\\second.txt", "w");
while((ch = fgetc(in)) != EOF)
fputc(ch, out);
fclose(out);
fclose(in);
getch();
}
Copyright @ IT Series www.itseries.com.pk
String
• A collection of characters written in double quotations
• Character variables are used to store a string
• The length of string is given in brackets in declaration statement
String Declaration
• C language stores a string as an array of characters
• Array is a group of contiguous memory locations that can store same type of data
• Syntax
data_type array_name [length];
Example
char book[20];
The above statement declares a variable book. The value 20 in brackets indicates the length of
string that can be stored in the variable. It allocates twenty memory locations as follows

Figure 14.1: Memory allocation for string variable book

Copyright @ IT Series www.itseries.com.pk


• Each memory location can store one character
• The string variable can be initialized with a string value as follows:
char book[20] = “C Programming”;
This statement will store the string as follows

• The last character \0 in the memory is known as null character


• It consists of back slash and zero
• It indicates the end of string
• It is added at the end of string automatically

char name[] = “Pakistan”;

P a k i s t a n \0

Copyright @ IT Series www.itseries.com.pk


• Process of assigning a value to string is different from assigning a value to other variables
• Simple assignment is invalid with this string
book = "Programming Concepts";
Will generate an error.
• The variable book does not consist of single memory location.
• It consists of many memory location
• It can store different characters in different memory location
• One character should be copied in each memory location one by one
• C language provides a library for handling string manipulation called string.h
• File contains many functions used to manipulate strings
• Strcpy function is used to copy a string to an array of characters
strcpy(destination, source);
• Destination indicates the name of array in which the string is to be copied
• Source indicates the string that is copied to the array of characters
strcpy(book, "Programming Concepts");

Copyright @ IT Series www.itseries.com.pk


Program 14.3
Program 14.4
Write a program that displays the value stored in a string variable name.
Write a program that displays the name of a person right-justified and address left-justified by using
25 character spaces for each.
#include <stdio.h>
#include <conio.h> #include <stdio.h>
void main() #include <conio.h>
Output: void main()
{ Name is ICS {
char name[ ] = "ICS"; char name[ ] = "Usman"; Output:
clrscr(); char address[ ] = "Faisalabad."; Usman
printf("%25s \n",name); Faisalabad
printf("Name is %s ",name);
printf("%-25s ",address);
getch(); getch();
} }

Copyright @ IT Series www.itseries.com.pk


Data is written to file as string by using fputs function
Syntax
fputs(string, File_Pointer);

string It is the string to be stored in the file


File_Pointer It is a file pointer associated with a data file in which the string will be written

Copyright @ IT Series www.itseries.com.pk


Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out;
char ch[25];
int i;
clrscr();
if((out = fopen("c:\\stest.txt", "w")) == NULL)
printf("File opening error.");
for(i=0; i<3; i++)
{
printf("Enter string: ");
gets(ch);
fputs(ch, out);
fputs("\n", out);
}
fclose(out);
getch();
}

Copyright @ IT Series www.itseries.com.pk


Data can be read from file as string by using fgets function
Syntax
fgets(string, File_Pointer);

string It is the string to be stored in the file

File_Pointer It is a file pointer associated with a data file in which the string will be written

Copyright @ IT Series www.itseries.com.pk


Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *in;
char ch[25];
int i;
if((in = fopen("c:\\stest.txt", "r")) == NULL)
printf("File opening error.");
while(fgets(ch, 25, in) != NULL)
{
printf("%s \n", ch);
}
fclose(in);
getch();
}

Copyright @ IT Series www.itseries.com.pk


Program 14.5

Write a program that inputs three strings from user and appends them in existing file.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out;
char ch[25];
int i;
if((out = fopen("c:\\stest.txt", "a")) == NULL)
printf("File opening error.");
for(i=0; i<3; i++)
{
printf("Enter string: ");
gets(ch);
fputs(ch, out);
fputs("\n", out);
}
fclose(out);
getch();
}

Copyright @ IT Series www.itseries.com.pk


• The data in formatted output is written in a particular manner with the help of format
specifiers
• In this method, a series of different types of data is written in files
• The data in formatted input is read in a particular manner with the help of format specifiers
• In this method, data is read in the same sequence in which it was written
• C language provides different functions for formatted input and output
• These functions are used to read and write data in a specific format
• Two most important functions are as follows:
fprintf This function is used to write formatted output in a file
fscanf This function is used to read formatted data from a file

Copyright @ IT Series www.itseries.com.pk


Formatted data can be written to file by using fprintf function
Syntax

fprintf(File_Pointer, Control_String, Write_List);

File_Pointer It is a file pointer associated with data file in which formatted data will be written
Control_String It is the string that contains format specifiers and escape sequences
It indicates the format according to which data is written to data file
Write_List It is a list of variables, constants or expressions whose values are written in the file
Each item in the list is separated by comma

Copyright @ IT Series www.itseries.com.pk


Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out;
int rno, marks;
char grade;
int i;
clrscr();
if((out = fopen("c:\\ftest.txt", "w")) == NULL)
printf("File opening error.");
for(i=1; i<=5; i++)
{
printf("Enter Roll No, marks and grade: ");
scanf("%d %d %c", &rno, &marks, &grade);
fprintf(out, "%d %d %c \n", rno, marks, grade);
}
fclose(out);
getch();
}

Copyright @ IT Series www.itseries.com.pk


Formatted data can be read from text file using fscanf function
Syntax

fscanf(File_Pointer, Control_String, Read_List);

File_Pointer It is a file pointer associated with data file from which formatted data will be read
Control_String It is the string that contains format specifiers and escape sequences
It indicates the format according to which data is read from data file
Write_List It is a list of variables in which values are stored from the file
Each item in the list is separated by comma

Copyright @ IT Series www.itseries.com.pk


Example
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *in;
int rno, marks;
char grade;
int i;
clrscr();
if((in = fopen("c:\\ftest.txt", "r")) == NULL)
printf("File opening error.");
else
while(fscanf(in, "%d %d %c \n", &rno, &marks, &grade) != EOF)
{
printf("%d %d %c \n", rno, marks, grade);
}
fclose(in);
getch();
}

Copyright @ IT Series www.itseries.com.pk


Copyright @ IT Series www.itseries.com.pk

You might also like