CC-112L PF Lab-12
CC-112L PF Lab-12
Programming Fundamentals
Laboratory 12
File Handling
Version: 1.0.0
Contents:
Learning Objectives
Required Resources
General Instructions
Background and Overview
o Bit Fields
o Enumeration Constants
o Sequential Access
o Random Access
o File Handling in C
Activities
o Pre-Lab Activity
Bitwise Operators
Bit Fields
– Defining Bit Fields
– Unnamed Bit Fields
Enumeration Constants
Task 01: Bitwise Operations
Task 02: Enums
o In-Lab Activity
Creating a Sequential-Access File
– Pointer to File
– Open a File
– End-of-file Indicator
– Close a File
– File Open Modes
Read from a Sequential-Access File
Random-Access File
– Creating a Random-Access File
– Writing Data Randomly
– fseek() function
– Reading Data Randomly
Task 01: Maximum Digit
Task 02: Second Largest Word
Task 03: Word Occurrence
Task 04: Batsman Average
o Post-Lab Activity
Task 01: Vigenère Cipher using File Handling
Submissions
Evaluations Metric
References and Additional Material
Lab Time and Activity Simulation Log
Learning Objectives:
Bitwise Operators
Bit Fields
Enumeration Constants
File Handling in C
Resources Required:
Desktop Computer or Laptop
Microsoft ® Visual Studio 2022
General Instructions:
In this Lab, you are NOT allowed to discuss your solution with your colleagues, even not
allowed to ask how is s/he doing, this may result in negative marking. You can ONLY discuss
with your Teaching Assistants (TAs) or Lab Instructor.
Your TAs will be available in the Lab for your help. Alternatively, you can send your queries
via email to one of the followings.
Teachers:
Course Instructor Prof. Dr. Syed Waqar ul Qounain [email protected]
Enumeration Constants:
In C programming, an enumeration type (also called enum) is a data type that consists of integral
constants. To define enums, the “enum” keyword is used.
Sequential Access:
It is the simplest access method. Information in the file is processed in order, one record after the other.
This mode of access is by far the most common.
Random Access:
A random-access file behaves like a large array of bytes stored in the file system. There is a kind of
cursor, or index into the implied array, called the file pointer; input operations read bytes starting at the
file pointer and advance the file pointer past the bytes read.
File Handling in C:
File handling refers to the method of storing data in the C program in the form of an output or input that
might have been generated while running a C program in a data file, i.e., a binary file or a text file.
Activities:
Pre-Lab Activities:
Bitwise Operators:
The bitwise operators are used to manipulate the bits of integral operands. Bitwise data manipulations
are machine dependent. The following table summarizes the bitwise operators.
Operator Description
“&” bitwise AND Compare its two operands bit by bit. The bits in the result are set to 1 if
the corresponding bits in the two operands are both 1.
“|” bitwise OR Compare its two operands bit by bit. The bits in the result are set to 1 if at
least one of the corresponding bits in the two operands is 1.
“^” bitwise XOR Compare its two operands bit by bit. The bits in the result are set to 1 if
the corresponding bits in the two operands are different.
“<<” left shift Shifts the bits of the first operand left by the number of bits specified by
the second operand; fill from the right with 0 bits.
“>>” right shift Shifts the bits of the first operand right by the number of bits specified by
the second operand; the method of filling from the left is machine-
dependent when the left operand is negative.
“~” complement All 0 bits are set to 1, and all 1 bit are set to 0. This is often called toggling
the bits.
Suppose two numbers 12 and 25. Their bitwise AND operation will be as follows
Bit Fields:
You can specify the number of bits in which to store an unsigned or signed integral member of a struct
or union. Known as bit fields, these enable better memory utilization by storing data in the minimum
number of bits required. Bit field members typically are declared as int or unsigned int.
struct{
data_type member_name: width of bit field;
}
Element Description
It is an integer type that determines the bit-field value which is to
data_type
be interpreted.
member_name The member name is the name of the bit field.
width The number of bits in the bit-field.
The output of month comes out to be negative. What happened behind is that the value of 9 was stored
in 4 bits as 1001. The MSB is a 1, so it’s a negative number and you need to calculate the 2’s
complement of the binary number. By calculating 2’s complement you will arrive at value 0111 which
equivalent to decimal number 7 and since it’s a negative number you will get -7.
Unnamed Bit Fields:
An unnamed bit field is used as padding in a struct. For example, the definition
struct example {
unsigned int a : 13;
unsigned int : 19;
unsigned int b : 4;
};
uses an unnamed 19-bit field as padding. Nothing can be stored in those 19 bits. Member b (assuming
a four-byte-word computer) is stored in a separate word of memory.
Enumeration Constants:
“enum” keyword for defining a set of integer enumeration constants represented by identifiers. Values
in an enum start with 0, unless specified otherwise, and increment by 1.
For example,
enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
creates the new type enum months in which the identifiers are set to the integers 0 through 11. . To
number the months 1 to 12, use:
enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
Input Output
AND: 8
OR: 9
First Number: 9
XOR: 1
Second Number: 8
Complement of first number: -10
Complement of second number: -9
In-Lab Activities:
Creating a Sequential-Access File :
The following example shows how you can impose your own record structure on a file.
Pointer to File:
Line 3 defines cfPtr as a pointer to a FILE structure. A program refers to each open file with a separate
FILE pointer.
Open a File:
Line 5 calls “fopen” to create the file "clients.txt". The file pointer that fopen returns is assigned to
cfPtr.
Function fopen takes two arguments:
a filename (which can include path information leading to the file’s location)
a file open mode.
The file open mode "w" indicates fopen should open the file for writing. If the file does not exist and
the file open mode is "w", fopen creates the file. If you open an existing file, fopen discards the file’s
contents without warning. This is a logical error.
End-of-File Indicator:
Line 21 calls “feof” to determine whether the end-of-file indicator is set for stdin. The end-of-file
indicator informs the program that there’s no more data to process.
Write to a File:
Line 22 writes a record as a line of text to the file clients.txt. The “fprintf” function is equivalent to
printf, but fprintf also receives a FILE pointer argument specifying the file to which the data will be
written. Function fprintf can output data to the standard output by using stdout as the FILE pointer
argument.
Close a File:
After the user enters end-of-file, the program closes the clients.txt file by calling “fclose”, then
terminates. Function fclose receives the FILE pointer as an argument. If you do not call fclose explicitly,
the file closes when program execution terminates.
The execution of above program is:
Mode Description
r Open an existing file for reading.
w Create a file for writing. If the file already exists, discard the current
contents.
a Open or create a file for writing at the end of a file—this is for write
operations that append data to a file.
r+ Open an existing file for update (reading and writing).
w+ Create a file for reading and writing. If the file already exists, discard the
current contents.
a+ Open or create a file for reading and updating where all writing is done at
the end of the file—that is, write operations append data to the file.
rb Open an existing binary file for reading.
wb Create a binary file for writing. If the file already exists, discard the current
contents.
ab Open or create a binary file for writing at the end of the file (appending).
rb+ Open an existing binary file for update (reading and writing).
wb+ Create a binary file for update. If the file already exists, discard the current
contents.
ab+ Open or create a binary file for update. Writing is done at the end of the
file.
fseek() Function:
If you have many records inside a file and need to access a record at a specific position, you need to
loop through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data can be
achieved using fseek() function.
As the name suggests, fseek() seeks the cursor to the given record in the file. Following is the syntax of
fseek():
Whence Description
SEEK_SET Starts the offset from the beginning of the file.
SEEK_END Starts the offset from the end of the file.
SEEK_CUR Starts the offset from the current location in the file.
The following program writes data to the file "student.txt". It stores data at precise points in the file
using fseek() and fwrite(). The file position pointer is set to a given place in the file by fseek(), and then
the data is written by fwrite().
Operation Description
fseek(fp, 0, 0) This takes us to the beginning of the file.
This takes us to the end of the file.
fseek(fp, 0, 2)
This takes us to (N + 1)th bytes in the file.
fseek(fp, N, 0)
This takes us N bytes forward from the current position in the file.
fseek(fp, N, 1)
This takes us N bytes backward from the current position in the file.
fseek(fp, -N, 1)
fseek(fp, -N, 2) This takes us N bytes backward from the end position in the file.
Input Output
1893 Maximum Digit: 9
11 Maximum Digit: 1
Input Output
10 20 30 40 Second Largest Number: 30
10 20 10 13 Second Largest Number: 13
Input Output
10 20 30 40 Batsman Average: 25
15 20 10* 30 Batsman Average: 25
Post-Lab Activities:
Task 01: Vigenère Cipher using File Handling [Estimated 60 minutes / 50 marks]
Vigenère Cipher is a method of encrypting alphabetic text.
Create a C program that:
Input Output
MY NAME
Keyword is bigger than string
THIS IS A MESSAGE
THIS IS A MESSAGE Encrypted: DLGO WJ D WIQOOXH Decrypted: THIS IS A
KEYWORD MESSAGE
TEXT
Encrypted: DIVD Decrypted: TEXT
KEY
Submissions:
For In-Lab Activity:
Save the files on your PC.
TA’s will evaluate the tasks offline.
For Pre-Lab & Post-Lab Activity:
Submit the .c file on Google Classroom and name it to your roll no.
Evaluations Metric:
All the lab tasks will be evaluated offline by TA’s
Division of Pre-Lab marks: [40 marks]
Task 01: Bitwise Operations [20 marks]
Task 02: Enums [20 marks]
Division of In-Lab marks: [120 marks]
Task 01: Maximum Digit [20 marks]
Task 02: Second Largest Number [30 marks]
Task 03: Word Occurrence [30 marks]
Task 04: Batsman Average [40 marks]
Division of Post-Lab marks: [50 marks]
Task 01: Vigenère Cipher using File Handling [50 marks]
Bit Fields
https://www.geeksforgeeks.org/bit-fields-c/
Enumeration Constants
https://www.programiz.com/c-programming/c-enumeration
File Handling in C
https://www.programiz.com/c-programming/c-file-input-output