0% found this document useful (0 votes)
12 views53 pages

Ch-14 (ICS II) - File Handling in C

The document provides an overview of file handling in C, covering definitions of files, file handling processes, types of data files (text and binary), data access methods (sequential and direct), and the concept of streams. It details the functions for opening and closing files, character and string input/output, and formatted input/output using functions like fopen(), fclose(), fputc(), fgetc(), fprintf(), and fscanf(). Additionally, it explains the structure of arrays, specifically one-dimensional arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views53 pages

Ch-14 (ICS II) - File Handling in C

The document provides an overview of file handling in C, covering definitions of files, file handling processes, types of data files (text and binary), data access methods (sequential and direct), and the concept of streams. It details the functions for opening and closing files, character and string input/output, and formatted input/output using functions like fopen(), fclose(), fputc(), fgetc(), fprintf(), and fscanf(). Additionally, it explains the structure of arrays, specifically one-dimensional arrays.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

COMPUTER SCIENCE – 12

Chapter 14
File Handling in C
Contents
• File, File Handling & Data file
• Types of Data File
• Data Access Methods
• Stream
• New-Line Marker & EOF
• Pointer
• Opening a File
• Closing a File
• Character Input / Output
• String Input / Output
• Formatted Input / Output

File, File Handling & Data
file
Q.1Define the terms file, file handling, and data file. Describe the advantages of file
handling.
File, File Handling & Data file
File
• File  A collection of related data or records which is stored on disk with a specific
name
• Files are used to store different types of data on the secondary storage devices such
as hard disk or USB drive
File Handling
• A process to store data in files and to perform different operations of these files
• Computer processes data through program
• Input data and output results are stored temporarily in memory
• Erased from memory when computer is turned off
• In file handling, a program can read input data from a data file for processing
• Processed results can be stored into another data file
• Output data file created by one program can be used as input data file by another
program
File, File Handling & Data file
Data File
• A data file contains data or information
• In file handling, program reads data as input from data file
• Program processes data and writes output into a data file
• Data files are linked with a program during run-time to write and read data to and from data files
• More than one data file can be linked with a program
Advantages of File Handling
+ Saves time of user to enter data each time the program is executed
+ Input data can be checked before processing by program  less chances of errors in output result
+ Execution of program becomes fast, because program has not to pause for getting input from user via
keyboard  directly reads input from data file loaded in memory
+ Data stored in a data file (as input data) can easily be updated
+ Single program may read input data from many data files at the same time
+ Output returned by one program can be permanently saved on the disk for later use
+ Output of a program stored on a disk in a file can be used any time without running program
+ Output of a program stored on a disk can easily be printed on printer or sent by e-mails to other or it can
Types of Data File
Q.2 How many types of data files are used in C?
Text Files
• A type of file that stores data as readable and printable form
• User can easily understand data of text file
• Data of data file can also easily be printed on printer
• Source code of C program is an example of text file
• Text files can easily be created in any text editor programs such as Notepad in
Windows
• In C, text file (as data file) can be created and output of program can be stored
in it
• Data is accessed sequentially
• Data is stored in ASCII code
• One character or digit takes one byte in memory
• Number 3.5 will take 3 bytes (one byte for each digit including decimal point)
Binary Files
• A type of file that stores data in binary format
• Data of binary file is only understandable by computer
• In C, binary file can be created to store output of program
• User cannot understand the data of binary file
• Example  object code of C program
• Binary file provides efficient way to access data
• Data can be accessed randomly and quickly
• In binary file
• Integer type data  takes 2 bytes
• Float type data  takes 4 bytes etc.
• For example: in binary format, integer value “29673”  take only two bytes
• Binary format is used to organize large amount of data on disk
Data Access Methods
Q.3 Describe the data access methods.
Sequential Access Method
• Used to access required data from a file in a sequence
• Data is accessed in order, one after the other
• For example: to read record number 15 within a data file, program must have to read
records 1 to 14 in order to reach at record number 15
• Very slow access method
• Takes more time to access a required record
• Sequential access files  Data files in which data is written and read
sequentially
• Formatted input/output files
• In C, text data files are sequential access data files
Direct Access Method
• Random access method is used to access required data in a file directly
• Very fast access method as compared to sequential access method
• Takes less time to access a required record
• Binary data files in C are direct access data files
Stream
Q.4 What is a stream? Illustrate the difference between text and binary
streams.
Stream
• A logical interface between data file or input/output device and program
• It is a general name given to a flow of data
• Data flows as a sequence of bytes
• Stream  may be input stream or output stream
Input Stream
• A flow of data from input device to computer
• Examples:
• A program loaded in memory reads data from input device such as keyboard
• A program reads data from data file stored on disk
• Data flows from keyboard or disk to computer memory
Output Stream
• A flow of data from computer to output device
• Examples:
• A program loaded in memory sends information to output device such as monitor
• A program writes data into data file on disk
Types of Stream
Text Stream
• Text stream  a sequence of characters
• In a text stream, certain character conversion may occur
• For example:
• When a sequence of characters flows from main memory to output device, a carriage return (‘\
r’) is converted into new line
• ‘\t’ is converted into horizontal tab and so on
• There may not be a one-to-one relationship between characters written and those
saved on an external device
Binary Stream
• Binary stream  a sequence of bytes
• In a binary stream, there is one-to-one relationship between bytes and those saved
on external device
• Number of bytes written or read is the same as the number of bytes on external
New-Line Marker & EOF
Q.5 Distinguish between new-line and EOF markers.
New-Line Marker
• In a C-program, escape sequence ‘\n’ is used to insert a new-line on output
device and in a text data file
• ‘\n’  indicates end-of-line character or new-line marker
• In a text editor (such as TC editor or notepad), when Enter key is pressed, a
new line character ‘\n’ is automatically inserted at the end of a line
EOF
• EOF  End-Of-File
• Special character
• Indicate the end of a text file
• Automatically inserted at the end of data file
• Sequential file  When program is reading data, it reads data upto required
data item or end-of-file character is reached
• In C, EOF identifier is used to detect the end-of-file
Pointer
Q.6 What is pointer in C? Briefly explain its concept.
Q.7 What is file pointer? Why is it used in C language?
Pointer
• Variable, which points the memory address of another variable
• Pointer variable is used to store memory address of another variable
• Data type of pointer variable must be same as data type of variable whose
memory address is to be stored into pointer variable
• Declared in the similar way as ordinary variable except an asterisk (*) is placed
before pointer variable (or after data type)
• For example: int *x;
Address Operators (&)
• Address operator  used to get memory address allocated to a specific variable
• Denoted by &
• Unary operator  Reference operator
• & operator is used to get a memory address of a variable and assign to pointer
variable through assignment statement
Pointer
• Example

• The pointer variable ‘px’ is said to point to variable ‘x’


File Pointer
• A pointer variable of type FILE
• FILE  special data structure, which is defined in ‘stdio.h’ header file
• Used to hold information of a data file opened in memory
FILE *fp;
• Fp  file pointer, valid user-defined identifier
• FILE  data type of file pointer
• File pointer is associated with data file
• Points memory location where data file is opened
• Data is read from data file or data is written into file with reference to file
pointer and not by actual name of data file
• File pointer is a key for communication with the data file
Opening a File
Q.8 What is meant by opening a file? Describe the fopen() function to open
a data file in C.
Q.9 Discuss different modes of opening a file in C.
Q.10 How is file open operation verified?
Opening a File
• Before reading or writing data in a file, it must be opened
• When a file is opened, a portion of memory is reserved for it
• This portion of memory is used to temporarily store data being read from or
written into the file  file buffer or simply buffer
The fopen() Function
• Used to open a file in memory in a specified access mode
• A file pointer is associated with the file to be opened
• General syntax  fp = fopen(filename, mode);

• If file is not in current directory (or you want to create a file in a particular
directory) then absolute path of file is given
• Escape sequence ‘\\’ is used in absolute path
File Opening Modes
• A data file can be opened in C to perform various operations
• Operations  reading, writing and appending etc.
• Opening mode of a file indicates type of operation to be performed on data
file
• Different codes are used for opening mode
• “r”  Reading mode, used if file already exists on disk
• “w”  Writing mode, all data is deleted and file is opened as new file
• If data file does not exist, a new file is created
• “a”  Append mode, new data is added at the end of current data of file
• “r+”  Reading/writing mode, file must already exist on disk
• “w+”  Reading/writing mode, If file already exists then its contents are overwritten
• “a+”  Reading/appending mode, If file does not exist, a new file is created for both
reading and writing data
Verifying File Open Operation
• fopen() function returns NULL pointer if it fails to open data file
• Open operation may fail due to some error
• Possible errors  disk full, disk error or file does not exist etc.
• Statements verify file open operation

• Function exit() is used to terminate program


• Argument ‘0’ indicates that program is terminated normally while other value (such as 1)
indicates that program is terminated due to an error
• Calling environment (such as operating system) uses returned value by exit()
function to respond appropriately to the error
Closing a File
Q.11 How is a data file closed?
Closing a File
• After performing input/output operation on data file, it should be closed from
memory
• Memory occupied by data file can be used by system for other purposes
• The fclose() function is used to close a data file opened by fopen() function
• General syntax  fclose(fp);
• fp  indicates file pointer associated with file that is to be closed
• The use of fclose() function to close a file is optional
• If an opened file is not closed using fclose() function, then OS automatically
closes file when program is terminated
Character Input / Output
Q.12 How data is read/written one character at a time in a data file?
Q.13 Explain the method to write data character by character in text file OR
Explain the fputc() function with program example.
Q.14 Explain the method to read data character by character from a text file
OR Describe the fgetc() function with program example.
Reading & Writing Character to a
File
• In character input/output (or read/write), data is written or read in a text file
one character at a time
• Functions for reading & writing characters in this manner provided by C
• fputc()  To write a single character at a time into a data file
• fgetc()  To read a single character at a time from a data file
The fputc() Function
• Used to write a single character at a time into a text data file
• Declared in header file “stdio.h”
• Data file must be opened in output (write or append) mode to use this function
• General syntax  fputc(character, fp);
• Statements write a single character ‘Q’ in a data file “xyz.txt”
The fputc() Function
• ASCII code of ESC key  27
• Escape sequence ‘\r’ is used in body of loop with ‘if’
statement to check whether Enter key is pressed
The fputc() Function
The fgetc() Function
• The fgetc() function is used to read a single character at a time from a text data
file
• This function is also declared in header file “stdio.h”
• Data file must be opened in read mode or input mode to use this function
• General syntax  var = fgetc(fp);
• For example: to read a single character from data file “xyz.txt”
The fgetc() Function
String Input / Output
Q.15 How data is read/written one string at a time in data file?
Q.16 Explain the method to write data as string in a text file OR Explain the
fputs() function with program example.
Q.17 Explain the method to read data as string from a text file OR Explain the
fgets() function with program example.
Reading and Writing Strings to a File
• In string read/write, data is read from or written in a text data file as one string
of characters at a time
• Functions for reading and writing strings of characters in this manner provided
by C
• fputs()  To write one string of characters at a time into a data file
• fgets()  To read one string of characters at a time from a data file
The fputs() Function
• Used to write one string at a time into a
text data file
• Declared in the header file “stdio.h”
• Data file must be opened in output
(write or append ) mode to use this
function
• General syntax  fputs(string, fp);
The fgets() Function
• Used to read one string of characters of specified length at a time from a text
data file
• Declared in header file “stdio.h”
• Data file must be opened in read mode (input mode) to use this function
• General syntax  fgets(string, len, fp);
The fgets() Function
Formatted Input / Output
Q.18 Explain the formatted file input/output. What functions are used in C for
formatted file input/output.
Q.19 Explain the method to write formatted data in a text file OR Explain the
fprintf() function with program example.
Q.20 Explain the method to read formatted data from a text file OR Explain the
fscanf() function with program example.
Formatted Input/Output
• In formatted file input/output, data is written into a data file in a specific
format using format specifiers
• Data is read from formatted data file in the manner in which it is stored
• Format specifiers are also used to read data
• Functions for writing and reading formatted data to and from data files
provided by C
• fprintf()  To write data into a data file in a specified format
• fscanf()  To read data from a data file in the same format in which it was
written
The fprintf() Function
• Used to write data into a data file in a
specified format
• Similar to printf() function and uses same
format specifiers
• General syntax 
fprintf(fp, format_string, arguments);
The fscanf() Function
• Used to read data from a data file in a specified format
• Similar to scanf() function and uses same format specifiers
• General syntax  fscanf(fp, format_string, arguments);
Array
Q.21 What is an array? Discuss one-dimensional array with examples.
Array
• Array  consecutive group of memory locations with same name and type
• Memory locations in an array  elements of the array
• Total number of elements in the array  size of array (or its length)
• A string is an array of characters
• Each element in array is accessed by specifying the name of array and its
position number in array
• Position number  index or subscript
• Index is written within square brackets ([]) with the name of array
• Index must be an unsigned integer value
• In C, first element of the array has an index value of 0
One-Dimensional Array
• One-dimensional array  linear array
• Consists of only one row or one column
• For example: temperature of each day of a month is stored in an array
• Name of array = “day”
• Elements = day[0], day[1], day[2], -----, day[30]
• Contains floating-point data (or real data)
• 31 elements
• First element = day[0], value is 5.2
• Last element = day[(30], value is 8.1
One-Dimensional Array
Declaring One-Dimensional Array
• In C, arrays are declared in similar way as simple variables are declared
• Specifying the name of array, its total number of elements and data type
• General syntax  type arrayname[n];
• Examples
• double day[31];
• char std_name[25];
• Data type of string is always “char”
One-Dimensional Array
Storing Values In One-Dimensional Array
• Values are stored in an array using assignment statement or input statement
• In C, scanf() function is used to input data into elements of array during program
execution
• Values can also be assigned to individual elements of array using assignment
statement
temp[0] = 15 ;
temp[1] = 20 ;
temp[2] = 28 ;
temp[3] = 30 ;
• An array may have several elements
• Usually, loop statement is used to access all elements of array and a single input
statement is used within body of loop to input data to all elements by changing
One-Dimensional Array
Displaying Data From Array
• Output statements are used to display
contents of an array
• Contents of array can be displayed on
screen using printf() function
Assignment
• Write a program that makes a copy of a text file to another file.
• Write a program to read a source code file of C. Verify that the number of right and left
braces in the source code file are equal. Use fgetc() function to read the file.
• Write a program that reads data from data file “student.txt” in the format given below.

Process the above data and write into data file “result.txt” in the following format.

• Write a program that counts the number of words in a text file.


• Write a program that inputs five values into an array and displays the sum and average
of these values.
For more details and solved assignment, refers to

PM Series

Computer Science
ICS Part-II

by
CM Aslam, Aqsa Aslam, Abdur Rehman &
Mudassir Saleem

Publisher: Majeed Sons


22- Urdu Bazar, Lahore

You might also like