0% found this document useful (0 votes)
5 views35 pages

POP Module 5

This document outlines the curriculum for a course on programming using C, focusing on structures, unions, and file handling. It includes detailed explanations of structure declarations, typedefs, initialization, member access, and examples of programs using structures. The document also covers nested structures and arrays of structures, providing practical examples and exercises for students.

Uploaded by

prateekchikkoppa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views35 pages

POP Module 5

This document outlines the curriculum for a course on programming using C, focusing on structures, unions, and file handling. It includes detailed explanations of structure declarations, typedefs, initialization, member access, and examples of programs using structures. The document also covers nested structures and arrays of structures, providing practical examples and exercises for students.

Uploaded by

prateekchikkoppa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Principles of Programming using C

Course Code: BCSESC103/203 CIE Marks:50


Course Type SEE Marks:50
Integrated
(Theory/Practical/Integrated) Total marks:100

Teaching Hours/Week (L:T:P: S) 2:0:2 Exam Hours 3+2


Total Hours of Pedagogy 40 hours Credits 03

Module-5 (8 Hours of Pedagogy)

Structure and Union: Introduction, Nested structures, Array of structures, Structures and
functions, Self- referential structures, Unions.
Files: Introduction to files, using files in C, Reading and Writing data files.
Textbook: Chapter 15.1-15.6, 16.1-16.4

Textbook:
1. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University,
Third edition, 2023.
Principles of Programming using C Module 5

Structure, Union, and Enumerated Data Type


5.1 Introduction
✓ Structure is basically a user-defined data type that can store related information
(even of differentdata types) together.
✓ The major difference between a structure and an array is that an array can store only
information ofsame data type.
✓ A structure is a collection of variables under a single name. The variables within a
structure are of different data types and each has a name that is used to select it from the
structure.
✓ “A Structure is a user defined data type, which is used to store the values of different
data typestogether under the same name”.
5.1.1 Structure Declaration
✓ A structure is declared using the keyword struct followed by the structure name.
✓ All the variables of the structure are declared within the structure.
✓ A structure type is generally declared by using the following syntax:

struct struct–name
{
data_type var–name;
data_type var–name;
...............
};

For example:
struct student
{
int r_no; Figure 5.1: Memory allocation for a structure
char name[20];
char course[20];
float fees;
};
✓ A variable of structure student can be defined by writing:
struct student stud1;
struct student is a data type and stud1 is a variable.

Dept. of CSE, BIET, Davanagere 1


Principles of Programming using C Module 5

✓ In the following syntax, the variables are declared at the time of structure declaration.
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
} stud1, stud2;
stud1 and stud2 of the structure student.
5.1.2 Typedef Declarations
✓ The typedef (derived from type definition) keyword enables the programmer to
create a new datatype name by using an existing data type alternate name is given
to a known data type.
✓ The general syntax of using the typedef keyword is given as:

typedef existing_data_type new_data_type;


For example: typedef int INTEGER;
then INTEGER is the new name of data type int.
✓ To declare variables using the new data type name, precede the variable name with the
data type name(new).
✓ Therefore, to define an integer variable,
✓ INTEGER num=5;
✓ For example, consider the following declaration:
typedef struct student
{
int r_no;
char name[20]; char course[20];float fees;
};

5.1.3 Initialization of Structures


✓ Initializing a structure means assigning some constants to the members of the
structure.
✓ When the user does not explicitly initialize the structure, then C automatically does it.

Dept. of CSE, BIET, Davanagere 2


Principles of Programming using C Module 5

✓ For int and float members, the values are initialized to zero, and char and string
members areinitialized to '\0' by default.
✓ The initializers are enclosed in braces and are separated by commas.
✓ The general syntax to initialize a structure variable is as follows:
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
}struct_var = {constant1, constant2, constant3,...};
OR
struct struct_name
{
data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................
};
struct struct_name struct_var = {constant1, constant2, constant 3,...};
✓ For example, we can initialize a student structure by writing,
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1 = {01, "Rahul", "BCA", 45000};
OR,
by writing,
struct student stud1 = {01, "Rahul", "BCA", 45000};

Dept. of CSE, BIET, Davanagere 3


Principles of Programming using C Module 5

5.1.4 Accessing the Members of a Structure


✓ A structure member variable is generally accessed using a '.' (dot) operator. The
syntax of accessinga structure or a member of a structure can be given as:
struct_var. member_name
For example, to assign values to the individual data members of the structure variable
studl, we may write
stud1.r_no = 01; stud1.name = "Rahul"; stud1.course = "BCA";stud1.fees = 45000;
✓ To input values for data members of the structure variable stud1, we may write
scanf("%d", &stud1.r_no);
scanf("%s", stud1.name);
✓ Similarly, to print the values of structure variable stud1, we may write
printf("%s", stud1.course);
printf("%f", stud1.fees);
5.1.5 Copying and Comparing Structures
✓ We can assign a structure to another structure of the same type:
✓ Then to assign one structure variable to another, we will write stud2 = stud1;
✓ C does not permit comparison of one structure variable with another. However,
individual members of one structure can be compared with individual members of
another structure.
✓ For example, to compare the fees of two students, we will write
✓ if(stud1.fees > stud2.fees) //to check if fees of stud1 is greater than stud2

Dept. of CSE, BIET, Davanagere 4


Principles of Programming using C Module 5

5.1.6 Finding the Size of the structures


✓ There are two different ways through which we can find the number of bytes a
structure will occupyin the memory.
1. Simple Addition
✓ In this technique, make a list of all data types and add the memory required by each.
✓ Consider a simple structure of an employee
struct Employee
{
int emp_id;
char name[20];
double salary;
char designation[20];
float experience;
};
Size = size of emp_id+ size of name + size of salary + size of designation + size of
experience
Size of emp_id = 2
Size of name =20* size of character
Size of salary = 8
Size of designation = 20 * Size of character
Size of experience = 4
Therefore, Size= 2 + 20*1 +8 +20 *1+4
= 2 +20+8+20+4
= 54bytes
2. Using sizeof operator
✓ The sizeof operator is used to calculate the size of a data type, variable, or an
expression.
✓ This operator can be used as follows:
sizeof(struct_name);
Ex: #include<stdio.h>
struct employee
{
int emp_id;

Dept. of CSE, BIET, Davanagere 5


Principles of Programming using C Module 5

char name[10];
double salary;
char designation [20];
float experience;
};
void main()
{
struct employee e;
printf(“%d”, sizeof(e));
}
Output: 54
Example: C program to read and display the student details using structures.
#include<stdio.h>
struct student
{
int rnum;
char name[20];
int marks;
}s[60];
void main()
{
int i,n;
printf("Enter the number of students");
scanf("%d",&n);
printf("\nEnter the roll number, Name , Marks\n");
for(i=1;i<=n;i++)
{
printf("\nStudent %d details\n",i);
scanf("%d",&s[i].rnum);
scanf("%s",s[i].name);
scanf("%d",&s[i].marks);
}
printf("\nStudent Details are:");

Dept. of CSE, BIET, Davanagere 6


Principles of Programming using C Module 5

printf("\nRoll_number\tName\tMarks");
for(i=1;i<=n;i++)
printf("\n%d\t\t%s\t%d\n",s[i].rnum,s[i].name,s[i].marks);
}
Output:
Enter the number of students: 5
Enter the roll number, Name, Marks and Grade of
Student 1 details
14 Dhavan 89
Student 2 details
15 Karan55
Student 3 details
11 Deepa 45
Student 4 details
12 Lakshmi 35
Student 5 details
10 Soma 68
Student Details are:
Roll_number Name Marks
14 Dhavan 89
15 Karan 55
11 Deepa 45
12 Lakshmi 35
10 Soma 68
write a program using structures to find the largest of 3 numbers
#include <stdio.h>
struct Numbers {
int num1;
int num2;
int num3;
};
int main() {
struct Numbers nums;

Dept. of CSE, BIET, Davanagere 7


Principles of Programming using C Module 5

printf("Enter three numbers: ");


scanf("%d %d %d", &nums.num1, &nums.num2, &nums.num3);
int largest;
if ((nums.num1 >= nums.num2) && (nums.num1 >= nums.num3)) {
largest = nums.num1;
} else if ((nums.num2 >= nums.num1) && (nums.num2 >= nums.num3)) {
largest = nums.num2; }
else {
largest = nums.num3; }
printf("The largest number is: %d\n", largest);
return 0;
}
Output: Enter three numbers 7 9 1
The largest number is 9
Write a program to read, display, add, and subtract two complex numbers.
#include <stdio.h>
int main()
{
typedef struct complex
{
int real;
int imag;
}COMPLEX;
COMPLEX c1, c2, sum_c, sub_c;
int option;
do{
printf("\n ** MAIN MENU **");
printf("\n 1. Read the complex nos.");
printf("\n 2. Display the complex nos.");
printf("\n 3. Add the complex nos.");
printf("\n 4. Subtract the complex nos.");
printf("\n 5. EXIT");
printf("\n Enter your option: ");

Dept. of CSE, BIET, Davanagere 8


Principles of Programming using C Module 5

scanf("%d", &option);
switch(option)
{
case 1: printf("\n Enter the real and imaginary parts of the first complex number: ");
scanf("%d %d", &c1.real, &c1.imag);
printf("\n Enter the real and imaginary parts of the second complex number: ");
scanf("%d %d", &c2.real, &c2.imag);
break;
case 2:
printf("\n The first complex number is: %d %di", c1.real, c1.imag);
printf("\n The second complex number is: %d %di", c2.real, c2.imag);
break;
case 3:
sum_c.real c1.real + c2.real; sum_c.imag c1.imag + c2.imag;
printf("\n The sum of two complex numbers is: %d %di", sum_c.real, sum_c.imag);
break;
case 4:
sub_c.real c1.real c2.real;
sub_c.imag c1.imag c2.imag;
printf("\n The difference between two complex numbers is: %d %di", sub_c.real,
sub_c.imag);
break;
} }while(option != 5);
return 0;
}
Output
MAIN MENU
1. Read the complex nos
2. Display the complex nos.
3. Add the complex nos.
4. Subtract the complex nos.
5. EXIT
Enter your option: 1
Enter the real and imaginary parts of the first complex number: 2 3
Dept. of CSE, BIET, Davanagere 9
Principles of Programming using C Module 5

Enter the real and imaginary parts of the second complex number: 4 5
MAIN MENU
1. Read the complex nos.
2. Display the complex nos.
3. Add the complex nos.
4. Subtract the complex nos.
5. EXIT
Enter your option: 3
The sum of two complex numbers is: 6+ 8i
write a program to enter two points then calculate distance between two points
using structures
#include <stdio.h>
#include <math.h>
struct Point {
int x;
int y;
};
double calculateDistance(struct Point p1, struct Point p2) {
int x_diff = p2.x - p1.x;
int y_diff = p2.y - p1.y;
double distance = sqrt((x_diff * x_diff) + (y_diff * y_diff));
return distance;
}
int main() {
struct Point p1, p2;
printf("Enter coordinates for Point 1: ");
scanf("%d %d", &p1.x, &p1.y);
printf("Enter coordinates for Point 2: ");
scanf("%d %d", &p2.x, &p2.y);
double dist = calculateDistance(p1, p2);
printf("Distance between the two points: %.2lf\n", dist);
return 0;
}

Dept. of CSE, BIET, Davanagere 10


Principles of Programming using C Module 5

Output:
Enter coordinates for Point 1: 2 3
Enter coordinates for Point 2: 9 9
Distance between the two points:9.219544

Nested Structures :- A nested structure is a structure that contains another structure as


itsmember.
Syntax :-
struct structure_name1
{
datatype member 1;
datatype member 2;
};
struct structure_name2
{
datatype member 1;
datatype member 2;
struct structure_name1 var1;
};

/* C program to demonstrate nested structures */


#include<stdio.h>
struct stud_dob
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char sname[20];
struct stud_dob date;
};
void main()

Dept. of CSE, BIET, Davanagere 11


Principles of Programming using C Module 5

{
struct student s;
printf("Enter Student Rollno :");
scanf("%d",&s.rollno);
printf("Enter Student Name :");
scanf("%s",s.sname);
printf("Enter date of birth as day month year:");
scanf("%d%d%d",&s.date.day,&s.date.month,&s.date.year);
printf("Student Details are\n");
printf("Student Rollno = %d\n",s.rollno);
printf("Student Name=%s",s.sname);
printf("Student DOB= %d-%d-%d\n", s.date.day, s.date.month, s.date.year);
}
Arrays of Structures
Array of structure is a data structure that stores a collection of related data items, where each
item is composed of multiple data elements or fields.
In an array of structure, each element of the array represents a separate instance of the
structure, and the fields of the structure are accessed using dot notation.
Write a program to read and display the information of all the students in the
class. Then edit the details of the ith student and redisplay the entire information.
#include <stdio.h>
#include <string.h>
int main()
{
struct student {
int roll_no;
char name[80];
int fees;
char DOB[80];
};
struct student stud[50];
int n, i, rolno, new_rolno;
int new_fees;

Dept. of CSE, BIET, Davanagere 12


Principles of Programming using C Module 5

char new_DOB[80], new_name[80];


printf("\n Enter the number of students: ");
scanf("%d", &n);
for ( i = 0; i < n ;i++)
{
printf("\n Enter the roll number: ");
scanf("%d", &stud[i].roll_no);
printf("\n Enter the name: ");
gets(stud[i].name);
printf("\n Enter the fees: ");
scanf("%d", stud[i].fees);
printf("\n Enter the DOB: ");
gets(stud[i].DOB);
} for( i = 0 i < n;i++)
{
printf("\n **DETAILS OF STUDENT %d***", 1+1);
printf("\n ROLL No. =\% d ^ prime prime , stud[1]. roll_no); printf("\n NAME =\% s ^
prime prime stud[i].name);
printf("\n FEES =\% d " , stud[i].fees);
printf("\n DATE OF BIRTH =\% s ^ prime prime , stud[i]. DOB);
}
printf("\n Enter the roll no. of the student whose record has to be edited: ");
scanf("%d", &rolno);
printf("\n Enter the new roll number: ");
scanf("%d", &new_rolno);
printf("\n Enter the new name: ");
scanf("%s", new_name);
printf("\n Enter the new fees: ");
scanf("%d", &new_fees);
printf("\n Enter the new date of birth: ");
scanf("%s", new_DOB);
stud[rolno-1].roll_no = new_rolno;
strcpy(stud[rolno-1].name, new_name);
stud[rolno-1].fees = new_fees;
Dept. of CSE, BIET, Davanagere 13
Principles of Programming using C Module 5

strcpy(stud[rolno-1].DOB, new_DOB);
for(i=0;i<n;i++) {
printf("\n DETAILS OF STUDENT \n“);
printf("\n ROLL No. = x d^ \ stud[1].roll_no);
printf("\n NAME=%s", stud[1].name);
printf("\n FEES = x d^ prime prime stud[1].fees);
printf("\n DATE OF BIRTH %s",stud[1].DOB);
return 0;
}
Output
Enter the number of students: 2
Enter the roll number: 1
Enter the name: kirti
Enter the fees: 5678
Enter the DOB: 9 9 91
Enter the roll number: 2
Enter the name: kangana
Enter the fees: 5678
Enter the DOB: 278 91
***DETAILS OF STUDENT 1***
ROLL No. 1
NAME kirti
FEES 5678
DOB 9 9 91
**DETAILS OF STUDENT 2***
ROLL No. 2
NAME kangana
FEES 5678
DOB 27 8 91
Enter the roll no. of the student whose record has to be edited: 2
Enter the new roll number: 2
Enter the new name: kangana khullar
Enter the new fees: 7000
Enter the new date of birth: 278 92
Dept. of CSE, BIET, Davanagere 14
Principles of Programming using C Module 5

**DETAILS OF STUDENT 1***


ROLL No. 1
NAME kirti
FEES 5678
DOB 99 91
*DETAILS OF STUDENT 2***
ROLL No. = 2
NAME kangana
FEES 7000
DOB 27 8 92
Structures and Functions
✓ A function may access the members of a structure in three ways.

Figure 5.2: Different ways of passing structures to functions


1. Passing Individual Members
✓ To pass any individual member of a structure to a function, we must use the direct
selection operator to refer to the individual members.
#include<stdio.h>
typedef struct
{
int x, y;
}POINT;
void display(int, int);
void main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
}
void display(int a, int b)

Dept. of CSE, BIET, Davanagere 15


Principles of Programming using C Module 5

{
printf(" The coordinates of the point are: %d %d", a, b);
}
Output: The coordinates of the point are: 2 3

2. Passing the Entire Structure


✓ The entire structure can be passed as a function argument.
✓ When a structure is passed as an argument, it is passed using the call by value method,
i.e., a copy ofeach member of the structure is made.
✓ The general syntax for passing a structure to a function and returning a structure can be
given as,
struct struct_name func_name(struct struct_name struct_var);
#include <stdio.h>
typedef struct
{
int x;
int y;
}POINT;
void display(POINT);
void main()
{
POINT p1 = {2, 3};
display(p1);
}
void display(POINT p)
{
printf("The coordinates of the point are: %d %d", p.x, p.y);
}
3. Passing Structures through Pointers
✓ The syntax to declare a pointer to a structure can be given as,

Dept. of CSE, BIET, Davanagere 16


Principles of Programming using C Module 5

✓ For the student structure, we can declare a pointer variable by writing


struct student *ptr_stud, stud;
And to assign the address, we will write
ptr_stud = &stud;
✓ To access the members of a structure, we can write
/* get the structure, then select a member */
(*ptr_stud).roll_no;
This operator is known as ‘pointing-to’ operator (->). It can be used as:
ptr_stud ->roll_no = 01;
Write a program using pointer to structure to initialize the members in the
structure.
#include<stdio.h>
struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
void main()
{
struct student stud1, *ptr_stud1;
ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
strcpy(ptr_stud1->name, "Rahul");
strcpy(ptr_stud1->course, "BCA");

Dept. of CSE, BIET, Davanagere 17


Principles of Programming using C Module 5

ptr_stud1->fees = 45000;
printf("\n DETAILS OF STUDENT");
printf("\n ");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME = %s", ptr_stud1->name);
printf("\n COURSE = %s", ptr_stud1->course);
printf("\n FEES = %f", ptr_stud1->fees);
return 0;
}
Output: DETAILS OF STUDENT
ROLL NUMBER= 01
NAME= Rahul
COURSE=BCA
FEES=45000.00
Self-Referential Structures
Self-referential structures are those structures that have one or more pointers which point to
the same type of structure, as their member.

Union
✓ Like structure, a union is a collection of variables of different data types. The only
difference between a structure and a union is that in case of unions, you can only store
information in one field at any one time.
✓ To better understand union, think of it as a chunk of memory that is used to store variables
of different types. When a new value is assigned to a field, the existing data is replaced
with the new data.

Dept. of CSE, BIET, Davanagere 18


Principles of Programming using C Module 5

Declaring a Union
✓ The syntax for declaring a union is same as that of declaring a structure.
union union-name
{
data_type var-name;
data_type var-name;
……….
};
✓ Again, the typedef keyword can be used to simplify the declaration of union variables.
✓ The most important thing to remember about a union is that the size of an union is the
size of its largest field. This is because a sufficient number of bytes must be reserved to
store the largest sized field.
Accessing a Member of a Union
✓ A member of a union can be accessed using the same syntax as that of a structure.
✓ To access the fields of a union, use the dot operator(.).
✓ That is the union variable name followed by the dot operator followed by the member
name.
Initializing Unions
✓ It is an error to initialize any other union member except the first member.
✓ A striking difference between a structure and a union is that in case of a union, the fields
share the same memory space, so fresh data replaces any existing data. Look at the code
given below and observe the difference between a structure and union when their fields
are to be initialized.
#include<stdio.h>
typedef struct POINT1
{
int x, y;
};
typedef union POINT2
{
int x;
int y;
};

Dept. of CSE, BIET, Davanagere 19


Principles of Programming using C Module 5

void main()
{
POINT1 P1 = {2,3};
// POINT2 P2 ={4,5}; Illegal with union
POINT2 P2;
P2. x = 4;
P2.y = 5;
printf("\n The co-ordinates of P1 are %d and %d", P1.x, P1.y);
printf("\n The co-ordinates of P2 are %d and %d", P2.x, P2.y);
}
Output:
The co-ordinates of P1 are 2 and 3
The co-ordinates of P2 are 5 and 5
Differences between structure and union
Structure Union
The struct keyword is used to define it. The union keyword is used to define it.
Syntax: Syntax:
struct struct–name union union-name
{ {
data_type var–name; data_type var-name;
data_type var–name; data_type var-name;
............... ……….
}; };
Example: Example:
struct student union student
{ {
int r_no; int r_no;
char name[20]; char name[20];
char course[20]; char course[20];
float fees; float fees;
}; };
A variable of structure student can A variable of union student can be
be defined by writing: defined by writing:

Dept. of CSE, BIET, Davanagere 20


Principles of Programming using C Module 5

struct student stud1; union student stud1;


Several members of a structure can Individual members of a structure can
be initialized at once. be initializedone by one.
Ex: Ex:
struct student stud1 = {01, "Rahul", union student stud1;stud1. r_no=01;
"BCA",45000}; stud1. name= "Rahul";stud1.
course="BCA";
stud1. fees =45000;
Each member within structure is The members or fields share the
assigned unique storage area of same memory space, so fresh data
location. replaces any existing data.
The size of the structure is the sum of The size of the union is the size of
all members or fields. the largest member or field.
Altering the value of a member will Altering any value of a member will
not affect other members of the alter other member values.
structure.

Introduction to Files
➢ A file is a collection of data stored on a secondary storage device like hard disk.
➢ A file is basically used because real life applications involve large amounts of data and in
such situations the console oriented I/O operations pose two major problems:
• First, it becomes cumbersome and time consuming to handle huge amount of data
through terminals.
• Second, when doing I/O using terminal, the entire data is lost when either the program is
terminated or computer is turned off. Therefore, it becomes necessary to store data on a
permanent storage (the disks) and read whenever necessary, without destroying the data.

Streams in C
✓ In C, the standard streams are termed as pre-connected input and output channels
between a text terminal and the program (when it begins execution).
✓ Therefore, stream is a logical interface to the devices that are connected to the computer.
✓ Stream is widely used as a logical interface to a file where a file can refer to a disk file,
the computer screen, keyboard, etc.

Dept. of CSE, BIET, Davanagere 21


Principles of Programming using C Module 5

✓ Although files may differ in the form and capabilities, all streams are the same.
✓ The three standard streams (figure 16.1) in C languages are- standard input (stdin),
standard output (stdout) and standard error (stderr).
• Standard input (stdin): Standard input is the stream from which the program
receives its data. The program requests transfer of data using the read operation.
However, not all programs require input. Generally, unless redirected, input for a
program is expected from the keyboard.
• Standard output (stdout): Standard output is the stream where a program writes its
output data. The program requests data transfer using the write operation. However, not
all programs generate output.
• Standard error (stderr): Standard error is basically an output stream used by
programs to report error messages or diagnostics. It is a stream independent of standard
output and can be redirected separately. No doubt, the standard output and standard
error can also be directed to the same destination.
A stream is linked to a file using an open operation and disassociated from a file using a
close operation

Figure 5.3: Standard streams


Buffer Associated with File Stream
✓ When a stream linked to a disk file is created, a buffer is automatically created and
associated with the stream.
✓ A buffer is nothing but a block of memory that is used for temporary storage of data that
has tobe read from or written to a file.
✓ Buffers are needed because disk drives are block oriented devices as they can operate
efficiently when data has to be read/ written in blocks of certain size. The size of ideal
buffer size is hardware dependant.
✓ The buffer acts as an interface between the stream (which is character-oriented) and the disk
hardware (which is block oriented).
✓ When the program has to write data to the stream, it is saved in the buffer till it is full.

Dept. of CSE, BIET, Davanagere 22


Principles of Programming using C Module 5

Then the entire contents of the buffer are written to the disk as a block as in the below
figure.

✓ .
Figure 5.4: Buffers associated with streams
✓ Similarly, when reading data from a disk file, the data is read as a block from the file and
written into the buffer. The program reads data from the buffer. The creation and operation of
the buffer is automatically handled by the operating system. However, C provides some
functions for buffer manipulation. The data resides in the buffer until the buffer is flushed or
written to a file.
Types of Files
✓ In C, the types of files used can be broadly classified into two categories- text files and
binary files.
1. ASCII Text files
✓ A text file is a stream of characters that can be sequentially processed by a computer in
forward direction. For this reason a text file is usually opened for only one kind of
operation (reading, writing, or appending) at any given time.
✓ Because text files only process characters, they can only read or write data one character
at a time.
✓ In a text file, each line contains zero or more characters and ends with one or more
characters that specify the end of line. Each line in a text file can have maximum of 255
characters.
✓ A line in a text file is not a C string, so it is not terminated by a null character.
✓ When data is written to a text file, each newline character is converted to a carriage
return/line feed character. Similarly, when data is read from a text file, each carriage
return/ line feed character is converted in to newline character.
✓ Another important thing is that when a text file is used, there are actually two
representations of data- internal or external. For ex, an int value will be represented as 2
or 4 bytes of memory internally but externally the int value will be represented as a
string of characters representing its decimal or hexadecimal value. To convert internal

Dept. of CSE, BIET, Davanagere 23


Principles of Programming using C Module 5

representation into external, we can use printf and fprintf functions. Similarly, to convert
an external representation into internal scanf and fscanf can be used.
2. Binary Files

✓ A binary file is a file which may contain any type of data, encoded in binary form
for computerstorage and processing purposes.
✓ Like a text file, a binary file is a collection of bytes.
✓ Note that in C a byte and a character are equivalent. Therefore, a binary file is also
referred to as acharacter stream with following two essential differences.
• A binary file does not require any special processing of the data and each byte
of data istransferred to or from the disk unprocessed.
• C places no constructs on the file, and it may be read from, or written to, in any
manner theprogrammer wants.
✓ Binary files store data in the internal representation format. Therefore, an int value
will be stored I binary form as 2 or byte value. The same format is used to store data in
memory as well as in file. Like text file, binary file also ends with an EOF marker.
✓ Binary files can be either processed sequentially or randomly.
✓ In a text file, an integer value 123 will be stored as a sequence of three characters- 1, 2
and 3. So each character will take 1 byte and therefore, to store the integer value 123 we
need 3 bytes. However, in a binary file, the int value 123 will be stored in 2 bytes in the
binary form. This clearly indicates that binary files takes less space to store the same
piece of data and eliminates conversion between internal and external
representations and are thus more efficient than the text files.

Using Files in C
✓ To use files in C, we must follow the steps given below.
• Declare a file pointer variable
• Open the file
• Process the file
• Close the file
1. Declaring a File Pointer Variable
✓ There can be a number of files on the disk. In order to access a particular file, you must
specify thename of the file that has to be used.
✓ This is accomplished by using a file pointer variable that points to a structure FILE

Dept. of CSE, BIET, Davanagere 24


Principles of Programming using C Module 5

(defined in stdio.h).
✓ The file pointer will then be used in all subsequent operations in the file.
✓ The syntax for declaring a file pointer is
FILE *file_pointer_name;
✓ For example, if we write FILE *fp;
Then, fp is declared as a file pointer.
✓ An error will be generated if you use the filename to access a file rather than the file
pointer
1.Opening a File
✓ A file must be first opened before data can be read from it or written to it.
✓ In order to open a file and associate it with a stream, the fopen() function is used.
✓ The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
✓ Using the above prototype, the file whose pathname is the string pointed to by file_name
is opened inthe mode specified using the mode.
✓ If successful, fopen() returns a pointer-to-structure and if it fails, it returns NULL.
File Name
✓ Every file on the disk has a name associated with it.
✓ In DOS the file name can have one to eight characters optionally followed by a
period and anextension that has one to three characters.
✓ Windows and UNIX permit filenames having maximum of 256 characters.
✓ In C, fopen() may contain the path information instead of specifying the filename.
The path givesinformation about the location of the file on the disk.
File Mode
✓ Mode conveys to C the type of processing that will be done with the file.
✓ The different modes in which a file can be opened for processing are given in Table below:
MODE DESCRIPTION
r Open a text file for reading. If the stream (file) does not exist then an error will
be reported.
Open a text file for writing. If the stream does not exist then it is created
w
otherwise if the file already exists, then its contents would be deleted
a Append to a text file. if the file does not exist, it is created.
Open a binary file for reading. B indicates binary. By default this will be a
rb

Dept. of CSE, BIET, Davanagere 25


Principles of Programming using C Module 5

sequential file in format


wb Open a binary file for writing
ab Append to a binary file
Open a text file for both reading and writing. The stream will be positioned at
r+ the beginning of the file. When you specify "r+", you indicate that you want to
read the file before you write to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created if it
w+
does not exist, and will be truncated if it exists.
Open a text file for both reading and writing. The stream will be positioned at
a+
the end of the file content.
r+b/ rb+ Open a binary file for read/write
w+b/wb+ Create a binary file for read/write
a+b/ab+ Append a binary file for read/write

✓ The fopen() can fail to open the specified file under certain conditions that are listed below:
• Opening a file that is not ready for usage.
• Opening a file that is specified to be on a non-existent directory/drive.
• Opening a non-existent file for reading.
• Opening a file to which access is not permitted.

Ex:
FILE *fp;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
OR
char filename[30];
FILE *fp;
gets(filename);
fp = fopen(filename, "r+");
if(fp==NULL)

Dept. of CSE, BIET, Davanagere 26


Principles of Programming using C Module 5

{
printf("\n The file could not be opened");exit(1);
}
2. Closing a File Using fclose()
✓ To close an opened file, the fclose() function is used which disconnects a file pointer
from a file.
✓ After the fclose() has disconnected the file pointer from the file, the pointer can be used
to access a different file or the same file but in a different mode.
✓ The fclose() function not only closes the file but also flushes all the buffers that are
maintained for that file
✓ If you do not close a file after using it, the system closes it automatically when the
program exits. However, since there is a limit on the number of files which can be open
simultaneously; the programmer must close a file when it has been used.
✓ The prototype of the fclose() function can be given as,
int fclose(FILE *fp);
Here, fp is a file pointer which points to the file that has to be closed. The function returns an
integer value which indicates whether the fclose() was successful or not. A zero is returned if
the function was successful; and a non-zero value is returned if an error occurred.
Read Data from Files
✓ C provides the following set of functions to read data from a file.
• fscanf()
• fgets()
• fgetc()
• fread()

1.fscanf()
✓ The fscanf() is used to read formatted data from the stream.
✓ The syntax of the fscanf() can be given as,
int fscanf(FILE *stream, const char *format,…);
✓ The fscanf() is used to read data from the stream and store them according to the
parameterformat into the locations pointed by the additional arguments.
Ex: #include<stdio.h>
void main()

Dept. of CSE, BIET, Davanagere 27


Principles of Programming using C Module 5

{
FILE *fp;
char name[80];
int roll_no;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); /* read from keyboard */
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no); // READ FROM
FILE-
Student.DAT
fscanf(fp, "%s %d", name, &roll_no);
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);
fclose(fp);
}

2. fgets()
✓ fgets() stands for file get string.
✓ The fgets() function is used to get a string from a stream.
✓ The syntax of fgets() can be given as:
char *fgets(char *str, int size, FILE *stream);
✓ The fgets() function reads at most one less than the number of characters specified by
size (gets size - 1 characters) from the given stream and stores them in the string str. The
fgets() terminates as soon as it encounters either a newline character or end-of-file or
any other error. However, if a newline character is encountered it is retained. When all
the characters are read without any error, a '\0' character is appended to end the string.
Ex: #include<stdio.h>
void main()
{
FILE *fp;

Dept. of CSE, BIET, Davanagere 28


Principles of Programming using C Module 5

char str[80];
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
while (fgets(str, 80, fp) != NULL)
printf("\n %s", str);
printf("\n\n File Read. Now closing the file");
fclose(fp);
}

3. fgetc()
✓ The fgetc() function returns the next character from stream, or EOF if the end of file is
reached or if there is an error.
✓ The syntax of fgetc() can be given as
int fgetc( FILE *stream );
✓ fgetc returns the character read as an int or return EOF to indicate an error or end of file.
✓ fgetc() reads a single character from the current position of a file (file associated with
stream). After reading the character, the function increments the associated file pointer
(if defined) to point to the next character. However, if the stream has already reached the
end of file, the end-of-file indicator for the stream is set.
Write a C program to copy a text file to another, read both the input file name
and target file name.
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char filename1[100], filename2[100],ch;
printf("Enter the filename to open for reading: \n");
scanf("%s", filename1);

Dept. of CSE, BIET, Davanagere 29


Principles of Programming using C Module 5

fptr1 = fopen(filename1, "r");


if (fptr1 == NULL)
{
printf("Error in opening the file");
exit(0);
}

printf("Enter the filename to open for writing: \n");

scanf("%s", filename2);
fptr2 = fopen(filename2, "w");
if (fptr2 == NULL)
{
printf("Error in opening the file");
exit(0);
}

while (!feof(fptr1))
{
ch=fgetc(fptr1);
fputc(ch,fptr2);
}

printf("\n Contents copied to %s", filename2);

fclose(fptr1);

fclose(fptr2);
}
4. fread()
✓ The fread() function is used to read data from a file.
✓ Its syntax can be given as
int fread( void *str, size_t size, size_t num, FILE *stream );
✓ The function fread() reads num number of objects (where each object is size bytes) and
places theminto the array pointed to by str. The data is read from the given input stream.
✓ Upon successful completion, fread() returns the number of bytes successfully read.
The number of objects will be less than num if a read error or end-of-file is encountered. If
size or num is 0, fread()

Dept. of CSE, BIET, Davanagere 30


Principles of Programming using C Module 5

will return 0 and the contents of str and the state of the stream remain unchanged. In case of
error, theerror indicator for the stream will be set.
✓ The fread() function advances the file position indicator for the stream by the number of
bytes read.
Ex:
#include <stdio.h>
void main()
{
FILE *fp; char str[10];
fp = fopen("Letter.TXT", "r+");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
fread(str, 1, 10, fp);
str[10]= '\0';
printf("\n First 9 characters of the file are : %s", str);
fclose(fp);
}

Writing Data to Files


✓ C provides the following set of functions to read data from a file.
• fprintf()
• fputs()
• fputc()
• fwrite()
1. fprintf()
✓ The fpritnt() is used to write formatted output to stream.
✓ Its syntax can be given as,
int fprintf ( FILE * stream, const char * format, ... );
✓ The function writes to the specified stream, data that is formatted as specified by the format
argument. After the format parameter, the function can have as many additional arguments

Dept. of CSE, BIET, Davanagere 31


Principles of Programming using C Module 5

as specified in format.
✓ The parameter format in the fprintf() is nothing but a C string that contains the text that
has to be written on to the stream.
Ex:
#include <stdio.h>
void main()
{
FILE *fp;int i;
char name[20];
float salary;
fp = fopen("Details.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
for(i=0;i<10;i++)
{
printf ("\n Enter your name : ");
gets(name);
printf ("\n Enter your salary : ");
scanf("%f", &salary);
fprintf(fp, " NAME : %s \t SALARY: %f", name, salary);
}
fclose(fp);
}
2. fputs()
✓ The fputs() is used to write a line into a file.
✓ The syntax of fputs() can be given as
int fputs( const char *str, FILE *stream );
✓ The fputs() writes the string pointed to by str to the stream pointed to by stream.
✓ On successful completion, fputs() returns 0. In case of any error, fputs() returns EOF.
✓ Ex:
#include<stdio.h>

Dept. of CSE, BIET, Davanagere 32


Principles of Programming using C Module 5

void main()
{
FILE *fp;
char feedback[100];
fp = fopen("Comments.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
printf("\n Kindly give the feedback on this book : ");
gets(feedback);
fputs(feedback, fp);
fclose(fp);
}
3.fputc()
✓ The fputc() is used to write a character to the stream.
✓ The syntax of fputc() can be given as,
int fputc(int c, FILE *stream);
✓ The fputc() function will write the byte specified by c (converted to an unsigned char) to
the output stream pointed to by stream. Upon successful completion, fputc() will return the
value it has written. Otherwise, in case of error, the function will return EOF and the error
indicator for the stream will be set.
Ex: #include<stdio.h>
void main()
{
FILE *fp;
char feedback[100];
int i;
fp = fopen("Comments.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);

Dept. of CSE, BIET, Davanagere 33


Principles of Programming using C Module 5

}
printf("\n Kindly give the feedback on this book : ");
gets(feedback);
for(i=0;i<feedback[i];i++)
fputc(feedback[i], fp);
fclose(fp);
}

4. fwrite()
✓ The fwrite() is used to write data to a file.
✓ The syntax of fwrite() can be given as,
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
✓ The fwrite() function will write, from the array pointed to by str, up to count objects of
size specifiedby size, to the stream pointed to by stream.
✓ The file-position indicator for the stream (if defined) will be advanced by the
number of bytes successfully written. In case of error, the error indicator for the stream
will be set.
Ex: #include<stdio.h>
void main()
{
FILE *fp; size_t count;
char str[] = "GOOD MORNING ";
fp = fopen("Welcome.txt", "wb");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
count = fwrite(str, 1, strlen(str), fp);
printf("\n %d bytes were written to the files”, count);
fclose(fp);
}
✓ fwrite() can be used to write characters, integers, structures, etc to a file.
However, fwrite() can beused only with files that are opened in binary mode.

Dept. of CSE, BIET, Davanagere 34

You might also like