0% found this document useful (0 votes)
2 views

CPNM Unit 5 & 6 Structures & Files

The document covers the concepts of structures and unions in C programming, detailing memory allocation, differences between structures and arrays, and examples of structure declarations and member access. It also includes file handling functions, operations, and sample C programs for creating and manipulating student profiles. Key topics include nested structures, arrays of structures, and file operations such as reading and writing data.

Uploaded by

Lakshman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CPNM Unit 5 & 6 Structures & Files

The document covers the concepts of structures and unions in C programming, detailing memory allocation, differences between structures and arrays, and examples of structure declarations and member access. It also includes file handling functions, operations, and sample C programs for creating and manipulating student profiles. Key topics include nested structures, arrays of structures, and file operations such as reading and writing data.

Uploaded by

Lakshman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

1

UNIT-V, VI
STRUCTURES, UNIONS & FIlES
Frequently Asked Questions

Structures and Unions:


1. Explain the memory allocation with a diagram, for the following structure and also give
the memory allocation with a diagram using union.
struct student
{
int rollno;
char name[10];
int total;
};
struct student x, y;
struct student a[10];
2. How does a structure differ from an array?
3. Explain the following with suitable example. i) Nested structure. ii) Array of structures
with an example?
4. Give a brief note about the implementation of structure within a structure. Give one
example with C-syntax.
5. Explain the meaning and purpose of the following: i) Tag ii) sizeof iii) Structure.
6. Differentiate between unions and structures? Give their application areas.
7. A Employee profile consists of Define a structure with the following three members:
rollnumber, name, and total marks of a student. Develop a C program for the above to
read and display the details of a student.
8. Write a C program to create a student profile consisting of name, father name, roll
number, marks as a structure. Determine the student who scored maximum marks.
2

Files:

1. List all file handling functions. Explain in detail.


2. Explain various file operations of C by giving syntax of each Operation?
3. Write a short note on functions that are used to
i) Read data from a file ii) Write data to a file
4. What is file? Explain the terms file pointer and EOF with suitable examples.
5. Write a C program to append the contents into an existing file?
6. A student profile consists of name, father name, date of birth. Write a C-program
to read the above student data from the key-board and save into a file.
7. Write a C-program to read from a file and print the contents of file on the screen.
8. WAP that reads a character file and encrypts it by replacing each alphabet by its
next alphabet cyclically i.e. z is replaced by a. Non-alphabets in the file are
retained as they are. Write the encrypted text into another file.

Structures
3

Structures: Declaring Structures and Structure variables, Accessing Members of a Structure,


Arrays of Structures, Arrays within a Structure
-----------------------------------------------------------------------------------------------------------------
Why Use Structures
The ordinary variables can hold one piece of information and how arrays can hold a number of
pieces of information of the same data type. These two data types can handle a great variety of
situations. But quite often we deal with entities that are collection of dissimilar data types.
Definition: A structure is a collection of heterogeneous data items that are stored in consecutive
memory locations.
The structure comes under the category of user defined data types.
For example, suppose you want to store data about a book. You might want to store its name (a
string), its price (a float) and number of pages in it (an int). If data about say 3 such book is to
be stored, then we can follow two approaches:
(a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
(b) Use a structure variable.

Let us examine these two approaches one by one.. Let us begin with a program that uses Arrays.
#include<stdio.h>
void main( )
{
char name[3] ;
float price[3] ;
int pages[3], i ;
printf ( "\nEnter names, prices and no. of pages of 3 books\n"
) ;
for ( i = 0 ; i <= 2 ; i++ )
scanf ( "%c %f %d", &name[i], &price[i], &pages[i] );
printf ( "\nAnd this is what you entered\n" ) ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %f %d\n", name[i], price[i], pages[i] );
}

Output:
Enter names, prices and no. of pages of 3 book And
this is what you entered
A 100.00 354 A 100.000000 354
C 256.50 682 C 256.500000 682
F 233.70 512 F 233.700000 512

This approach no doubt allows you to store names, prices and number of pages. But as you must
have realized, it is an unwieldy approach that obscures the fact that you are dealing with a group
of characteristics related to a single entity—the book.
4

The program becomes more difficult to handle as the number of items relating to the book go
on increasing. For example, we would be required to use a number of arrays, if we also decide
to store name of the publisher, date of purchase of book, etc. To solve this problem, C provides
a special data type—the structure.

Defining Structure
Syntax of structure declaration:
struct structure name
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
……………
datatypen var1,var2,…;
};
➢ The struct keyword is used to declare structures.
➢ The keyword struct identifies the beginning of a structure definition.
➢ It's followed by a structure name or tag that is the name given to the structure.
➢ Following the tag are the structure members, enclosed in braces.
➢ A structure can contain any of C's data types, including arrays and other structures.
➢ Each variable within a structure is called a member of the structure.
➢ The above structure declaration is also known as template.
➢ The template is terminated with semicolon (;).

Examples:
1.Define a structure by name student which includes student name,roll number and marks.
struct student
{
char name [10];
int rno;
float marks ;
} ;
This statement defines a new data type called struct student.

2. Define a structure by name book which includes name of the book, price and number of
pages.
struct book
{
char name ;
float price ;
int pages ;} ;
This statement defines a new data type called struct book.
5

Declaring Structure Variable

After defining the structure, variables for that structure are to be declared to access the
members of structures.
Syntax for declaration of structure variable is
struct structurename var1,var2,var3,……varn;
Example: struct book b1, b2, b3 ;
The variables b1, b2, b3 are variables of the type struct book.

The memory is allocated for structures only after the declaration of structure variable. The
memory allocated is equal to the sum of memory required by all the members in structure
definition.
Example :
struct book b1, b2, b3 ;
This statement assigns space in memory for b1,b2,b3. It allocates space to hold all the
elements in the structure—in this case, 7 bytes—one for name, four for price and two for
pages. These bytes are always in adjacent memory locations.
Example:
struct student
{
char name [10];
int rno;
float marks ;
} ;
struct student s1,s2;

The above declaration allocates 16 bytes(10 bytes for name,2 bytes for roll number and 4
bytes for marks) for s1 and 16 bytes for s2.
The variables for structure can be declared in three different ways:
method 1:
struct structure name
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
……………
……………
datatypen var1,var2,…; };
struct structurename var1,var2,var3,……varn;

method 2:
struct structure name
6

{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
…………… .
……………
datatypen var1,var2,…;
}var1,var2,var3,…..varn;

method3:
struct
{
datatype1 var1,var2,…;
datatype2 var1,var2,…;
…………… .
……………
datatypen var1,var2,…;
}var1,var2,var3,…..varn;

The method 3 cannot be used for future declaration of variables as structure tag is not present.
Note: The use of structure tag is optional in C language.
For example,Variables for structure book are declared in 3 different ways

1. struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1, b2, b3 ;

2.struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

3. struct
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;
7

Accessing Members Of Structure

The members of structure are accessed by dot (.) operator.

Syntax for accessing members of structure are:

Structure varname.member name;

So to refer to pages of the structure defined in our structure book example we have to use,
b1.pages
Similarly, to refer to price we would use,
b1.price.

Structure Initialization

Like primary variables and arrays, structure variables can also be initialized where they are
declared.

Syntax for structure variable initialization:


struct structurename varname={list of values);

here the values should be assigned in the same order of declaration of the members in the
definition.
example:
struct book
{
char name[10] ;
float price ;
int pages ;
} ;
struct book b1 = { "Basic", 130.00, 550 } ;
struct book b2 = { "Physics", 150.80, 800 } ;

Examples:
1. Define a structure by name student which includes student name,roll number and marks.
struct student
{
char name[10];
int rno;
8

float marks ;
} ;
This statement defines a new data type called struct student.

2. Define a structure by name book which includes name of the book ,price and number of
pages.
struct book
{
char name[10];
float price;
int pages ;
} ;
This statement defines a new data type called struct book.

Memory allocation for structure

Whatever be the elements of a structure, they are always stored in contiguous memory locations.
The following program would illustrate this:
/* Memory map of structure elements */
main( )
{
struct book
{
char name ;
float price ;
int pages ;
} ;
struct book b1 = { 'B', 130.00, 550 } ;
printf ( "\nAddress of name = %u", &b1.name ) ;

printf ( "\nAddress of price = %u", &b1.price ) ;


printf ( "\nAddress of pages = %u", &b1.pages ) ;
}
Here is the output of the program...
Address of name = 65518
Address of price = 65519
Address of pages = 65523

Actually the structure elements are stored in memory as shown in the Figure below

b1.name b1.price b1.pages


9

B 130.00 550

65518 65519 65523

Difference between Arrays and Structures :

Array:
▪ Array is a derived data type.
▪ It allocates memory only for the elements of the subscripts. Array allocates static
memory and uses index / subscript for accessing elements of the array.
▪ It allocates memory of same files that is if we declare integer type array then it allocates
2 byte memory for each cell.
▪ It does not contain structure within itself.
▪ It can contain only homogeneous data types.
▪ Array is a pointer to the first element of it
▪ We can access the array by using index number.
▪ The elements of the array are contiguous in memory
▪ Array element access takes less time in comparison with structures.

Structure:
▪ Structure is a programmer or user - defined data type.
▪ It does not allocate memory till the elements of the structure are accessed. Structures
allocate dynamic memory and uses (.) operator for accessing the member of a structure.
▪ It allocates the memory for the highest data type.
▪ It contain array within itself.
▪ It can contain only non-homogeneous data types.
▪ Structure is not a pointer
▪ The elements of structure are accessed by using dot (.) operator with structure reference
name.
▪ The elements of a structure may not be contiguous.

Sample Program

Define a structure for student which include roll number ,name,age and marks .
Write a program to read and display the information of 3 students.

#include<stdio.h>
#include<string.h>
struct student
10

{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initialization
struct student s1={2,"Gandhi",89,18};
struct student s2,s3;
//assigning values to s2 using assignment operator.
s2.rno=5;
s2.marks=90;
s2.age=18;
strcpy(s2.name,"Ram ");
//reading values for s3 using standard input function.
printf("\n enter rno,name ,marks,age of student: ");
scanf("%d%s%d%d",&s3.rno,s3.name,&s3.marks,&s3.age);
printf("\n\n");
printf("Details of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
printf("\n\n");
printf("Details of student 3:\n");
printf("\n roll number: %d",s3.rno);
printf("\n name :%s",s3.name);
printf("\n marks: %d",s3.marks);
printf("\n age: %d",s3.age);
}

output :
enter rno,name,marks,age of student:1
Raju
92
18
11

Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18

Details of student 2:
roll number: 5
name :Ram
marks :90
age: 18

Details of student 3:
roll number: 1
name :Raju
marks :92
age: 18

Operations that can be performed on structure variable

The only operation that is allowed on structure variables is assignment operation. Two
variables of same structure can be copied similar to ordinary variables.
If P1 and P2 are variables of struct P, then P1 values can be assigned to P2 as
P2=P1;
where values of P1 will be assigned to P2 member by member.

Program illustrating operation on structure variables

#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initalization
struct student s1={2,"Gandhi",89,18};
struct student s2;
s2=s1;
printf("\nDetails of student 1:\n");
12

printf("\n roll number: %d",s1.rno);


printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
}
output:
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18

Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18

Note: C does not permit any logical operations on structure variables.

Operation On Individual Members Of Structures

All operations are valid on individual members of structures.

Program illustrating operations on structure members

#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
13

int marks,age;
};
void main()
{
int m;
//assigning values to structure variable s1 using initalization
struct student s1={2,"Gandhi",89,18};
struct student s2;
s2=s1;
printf("\nDetails of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);

//comparsion of two student details.


m=((s1.rno==s2.rno)&&(s1.marks==s2.marks))?1:0;
if(m==1)
printf("\n both the details are same");
else
printf("\n both the details are not same");
}

output:
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18

Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18
both the details are same
14

Array Of Structures

In array of structures, the variable of structure is array .


In our sample program, to store details of 100 students we would be required to use 100
different structure variables from s1 to s100,which is definitely not very convenient. A better
approach would be to use an array of structures.

Syntax for declaring structure array

struct struct-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};

struct struct-name obj [ size ];

Program:
Define a structure for student which include roll number ,name,age and marks .
Write a program to read and display the information of ‘n’ number of students where n is
value supplied by user.

#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
15

{
struct student s[10];//Declares array of 10 student.
int i,n;
printf("\n enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
//reading values for s3 using standard input function.
printf("\n enter rno,name ,marks,age of student %d: ",i+1);
scanf("%d%s%d%d",&s[i].rno,s[i].name,&s[i].marks,&s[i].age);
}
printf("\n\n");
printf("Details of students are :\n");
for(i=0;i<n;i++)
{
printf("\n Details of student %d:\n",i+1);
printf("\n roll number: %d",s[i].rno);
printf("\n name :%s",s[i].name);
printf("\n marks: %d",s[i].marks);
printf("\n age: %d",s[i].age);
}
}
Output:
enter number of students :3
enter rno,name,marks,age of student 1:2
Gandhi
89
18
enter rno,name,marks,age of student 2:5
Raj
76
18
enter rno,name,marks,age of student 3:6
Ram
86
18
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18

Details of student 2:
16

roll number: 5
name :Raj
marks :76
age: 18

Details of student 3:
roll number: 6
name :Ram
marks :86
age: 18

In the above program the memory allocated for structure variable is 160 bytes consecutively
in which first 16 bytes for 1st student 1(s[0]),next 16 bytes for
2nd student 2(s[1]) and so on last 16 bytes for 10 th student (s[9]).

The following figure shows the memory allocation for array of structures.
16bytes 16 16 16 16 16 16 16 16 16

s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]

Again in each 16 bytes (2 bytes-roll number,10 bytes-name,2 bytes-marks,2 bytes-age).

Array within Structure :

As we know, structure is collection of different data type. Like normal data type, It can also
store an array as well.
In arrays within structure the member of structure is array.
Syntax for array within structure

struct struct-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
17

struct struct-name obj;


Example for array within structure

struct Student
{
int Roll;
char Name[10];
int Marks[3]; //array of marks
int Total;
float Avg;
};

void main()
{
int i;
struct Student S;

printf("\n\nEnter Student Roll : ");


scanf("%d",&S.Roll);

printf("\n\nEnter Student Name : ");


scanf("%s",&S.Name);

S.Total = 0;

for(i=0;i<3;i++)
{
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);

S.Total = S.Total + S.Marks[i];


}

S.Avg = S.Total / 3;

printf("\nRoll : %d",S.Roll);
printf("\nName : %s",S.Name);
printf("\nTotal : %d",S.Total);
printf("\nAverage : %f",S.Avg);
}
Output :
Enter Student Roll : 4
Enter Student Name : GANDHI
18

Enter marks 1 : 80
Enter marks 2 : 90
Enter marks 3 : 75
Roll : 4
Name : GANDHI
Total : 245
Average : 81.000000
The memory allocated for structure variable s is 24 bytes(2-roll,10-name,6-marks,2-total,4-
avg).

Structure within a Structure


• Nested structure in C is nothing but structure within structure. One structure can be
declared inside other structure as we declare structure members inside a structure.
• The structure variables can be a normal structure variable or a pointer variable to access
the data.
Structure within Structure:
• This program explains how to use structure within structure in C using normal variable.
“student_college_detail’ structure is declared inside “student_detail” structure in this
program. Both structure variables are normal structure variables.
• Please note that members of “student_college_detail” structure are accessed by 2 dot(.)
operator and members of “student_detail” structure are accessed by single dot(.)
operator.

Program for Structure within Structure:


#include <stdio.h>
#include <string.h>

struct student_college_detail
{
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
19

int main()
{
struct student_detail stu_data = {1, "Raju",
90.5, 71145,"GITAM University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n",
stu_data.percentage);

printf(" College Id is: %d \n",


stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: GITAM University

Example for structure within structure or nested structure:


#include<stdio.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

void main()
20

{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployeeHouseNo : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployeeHouseNo : %s",E.Add.PinCode);

Output :

Enter Employee Id : 101


Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056

Details of Employees
Employee Id : 101
21

Employee Name : Suresh


Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056

UNIONS

A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.

Defining a Union:
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows –

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];
22

The union tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the union's definition, before
the final semicolon, you can specify one or more union variables but it is optional. Here is the
way you would define a union type named Data having three members i, f, and str –

union Data {
int i;
float f;
char str[20];
} d;

Now, a variable of ‘d’ type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.

The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string.

The following example displays the total memory size occupied by the above union −

Example Program:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data d;
printf( "Memory size occupied by data : %d\n", sizeof(d));
return 0;
}

When the above code is compiled and executed, it produces the following result −
Memory size occupied by d: 20

Example program for C union:


23

#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");

strcpy(record1.subject, "Maths");

record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);

printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
24

OUTPUT:

Union record1 values example


Name : ---------// Garbage Value will be printed
Subject :--------// Garbage Value will be printed
Percentage : 86.500000;

Union record2 values example


Name : Mani
Subject : Physics
Percentage : 99.500000

Explanation For Above C Union Program:


There are 2 union variables declared in this program to understand the difference in accessing
values of union members.

Record1 union variable:


• “Raju” is assigned to union member “record1.name” . The memory location name is
“record1.name” and the value stored in this location is “Raju”.
• Then, “Maths” is assigned to union member “record1.subject”. Now, memory location
name is changed to “record1.subject” with the value “Maths” (Union can hold only one
member at a time).
• Then, “86.50” is assigned to union member “record1.percentage”. Now, memory
location name is changed to “record1.percentage” with value “86.50”.
• Like this, name and value of union member is replaced every time on the common
storage space.
• So, we can always access only one union member for which value is assigned at last.
We can’t access other member values.
• So, only “record1.percentage” value is displayed in output. “record1.name” and
“record1.percentage” are empty.

Record2 union variable:


• If we want to access all member values using union, we have to access the member
before assigning values to other members as shown in record2 union variable in this
program.
• Each union members are accessed in record2 example immediately after assigning
values to them.
• If we don’t access them before assigning values to other member, member name and
value will be over written by other member as all members are using same memory.

We can’t access all members in union at same time but structure can do that.
25

Program for one member is being used at a time in union

#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

return 0;
}

When the above code is compiled and executed, it produces the


following result −
Output:
data.i : 10
data.f : 220.500000
data.str : C Programming

Here, all the members are getting printed very well because one member is being used at a time.

Difference between union and structure


Though unions are similar to structure in so many ways, the difference between them is crucial
to understand.

Structure Union

1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.
26

2. When a variable is associated with a 2. When a variable is associated with a union,


structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory.
greater than or equal to the sum of sizes of its So, size of union is equal to the size of largest
members. The smaller members may end member.
with unused slack bytes.

3. Each member within a structure is assigned 3. Memory allocated is shared by individual


unique storage area of location. members of union.

4. The address of each member will be in 4. The address is same for all the members of
ascending order This indicates that memory a union. This indicates that every member
for each member will start at different offset begins at the same offset value.
values.

5 Altering the value of a member will not 5. Altering the value of any of the member
affect other members of the structure. will alter other member values.

6. Individual Structure member can be 6. Only one Union member can be accessed
accessed at a time at a time.

7. Several members of a structure can 7. Only one member of a union can be


initialize at once. initialized.

The primary difference can be demonstrated by this example:

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;

struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
27

printf("size of union = %d", sizeof(uJob));


printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}
Output

size of union = 32
size of structure = 40

More memory is allocated to structures than union


As seen in the above example, there is a difference in memory allocation between union and
structure.
The amount of memory required to store a structure variable is the sum of memory size of all
members.

But, the memory required to store a union variable is the memory required for the largest
element of a union.

Sample Program with Structures & Union:

#include<stdio.h>
struct number1
{
int i;
float f;
char c;
}sn;
28

union number2
{
int i;
float f;
char c;
}un;
void main()
{
printf("Details of structure\n");
printf("size of structure number1=%d\n",sizeof(sn));
sn.i=10;
sn.f=89.00;
sn.c='X';
printf("sn.i=%d\n sn.f=%f\n sn.c=%c\n",sn.i,sn.f,sn.c);
printf("Details of Union\n");
printf("size of Union number2=%d\n",sizeof(un));
un.i=10;
un.f=89.00;
un.c='X';
printf("un.i=%d\n un.f=%f\n un.c=%c\n",un.i,un.f,un.c);
}

Output:
size of structure number1= 7
sn.i =10
sn.f =89.00
sn.c =X
size of Union number2 = 4
un.i =Garbage value
un.f = Garbage value
un.c =X

Example program 2: Define a union with two emp details: name,


ID, salary. Increment their salaries by 20K each and display the
final salaries.

#include <stdio.h>
#include <string.h>
union Data {
29

int ID;
float sal;
char name20];
};

int main( ) {
union Data d1,d2;
d1.sal=50000;
d2.sal=60000;

printf( "Increased salary of d1: %f\n", d1.sal+20000);


printf( "Increased salary of d2: %f\n", d2.sal+20000);
return 0;
}

FILES

Definition:
FILE is a predefined structure data type which is defined in library file called stdio.h.
30

(OR)
FILE is a set of records that can be accessed through a set of library functions.

Syntax:
FILE *filepointerobject;

Example:
FILE *fp; // where FILE is a keyword and “fp” is a file pointer object

C supports a number of functions that have the ability to perform basic file operations,
which include:

1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file

File operation functions in C:


Function Name Operation
fopen() Creates a new file for use
Opens a new existing file for use
Ex: fp=fopen(“gitam.txt”, “w”);
fclose() Closes a file which has been opened for use
Ex: fclose(fp);
fgetc() or Reads a character from a file
getc() Ex: ch=fgetc(fp);
or ch=getc(fp);
fputc() or Writes a character to a file
putc() Ex: fputc(ch,fp);
or putc(ch,fp);
fprintf() Writes a set of data values to a file
Ex: fprintf(fp,“%d”,n);
fscanf() Reads a set of data values from a file
Ex: fscanf(fp,“%d”,&n);
getw( ) Reads only integer from a file
// Its not fgetw() Ex: n=getw(fp);
putw() Writes only integer to the file
// Its not fputw() Ex: putw(n,fp);
fgets() Reads a string from the a file
Ex: fgets(ch,sizeof(string),fp);
fputs() Writes a string to a file
Ex: fputs(ch,fp);
31

fseek() Sets the position to a desired point in the file


Ex: fseek(fp,0,SEEK_SET);
ftell() Gives the current position in the file
Ex: n=ftell(fp);

Opening files: fopen( )

fopen() is a predefined file handling function which is used to open already existing file or to
create a file. It accepts two strings, the first is the name of the file, and the second is the mode
in which it should be opened. The general format of the function used for opening a file is as
follows:

Syntax:
FILE *filepointer;
filepointer=fopen(“filename.filetype”,”mode”);

Example: FILE *fp;


fp= fopen(“gitam.txt”,”w”);
where gitam.txt is file name.
where ‘w’ is write mode.

Note: The function fopen( ) is compulsory for the files to do any operations, without
fopen( ), we cannot perform operations on files.

S.No. Mode Description


1. “r” Open for reading. The precondition is file must exist. Otherwise
function returns Null Value.
2. “w” Open for writing. If file already exists, its contents are overwritten.
Otherwise a new file is created. The function returns NULL if it is
unable to create the file. File cannot created for the reasons such as not
having access permission, disk full, having write protect etc.,.
3. “a” Open for appending. If file already exist, the
new contents are appended. Otherwise, a new file is created. The
function return NULL if it is unable to create the file.
4. “r+” Open for both reading and writing. The file must exists.
5. “w+” Open for both reading and writing. Contents written over.
32

6. “a+” Open for reading and appending. If file is not existing the file is
created.

➢ Where will be file saved in computer?


A) If you didn’t mention the path, by default the file will be saved in TC folder, i.e., in
the drive where C-Lang is installed.
Example: fp=fopen(“hello.txt”, “w”);

B) If you mention the path in fopen( ) function, then the new file will be saved in that
particular path. Path should be mentioned as follows:
Example: fp=fopen(“d:\\gitam\\hello.txt”, “w”);
(Or)
fp=fopen(“d:/gitam/hello.txt”, “w”);

Writing to Files : fprintf( )


It is a predefined file handling function which is used to print the content in a file. The fprintf(
) function is identical to printf( ) function except that they work on files. The first argument of
this function is a file pointer which specifies the file to be used. The general form of fprintf is:

Syntax: fprintf(fp,”control string”, var_list);

Where fp id is a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.

Example: fprintf(fp, “%s%d%f”,name,age,weight);


Here, name is an array variable of type char and age is an int variable

Reading from Files : fscanf( )


It is a predefined file handling function which is used to read the content from a file. The fscanf(
) function is identical to scanf( ) function except that they work on files. The first argument of
this function is a file pointer which specifies the file to be used. The general format of fscanf is:

Syntax: fscanf(fp, “controlstring”,var_list);

This statement would cause the reading of items in the control string.

Example: fscanf(fp, “%s%d”,name,&quantity”);


33

Where fp id is a file pointer associated with a file that has been opened for reading. The control
string is file output specifications list may include variable, constant and string.

Closing the File : fclose( fp)

➢ When we have finished reading from the file, we need to close it. This is done using the
function fclose through the statement, fclose( fp );
➢ During a write to a file, the data written is not put on the disk immediately. It is stored
in a buffer. When the buffer is full, all its contents are actually written to the disk. The
process of emptying the buffer by writing its contents to disk is called flushing the
buffer.
➢ Closing the file flushes the buffer and releases the space taken by the FILE structure
which is returned by fopen. Operating System normally imposes a limit on the number
of files that can be opened by a process at a time. Hence, closing a file means that
another can be opened in its place. Hence, if a particular FILE pointer is not required
after a certain point in a program, pass it to fclose and close the file.

Syntax: fclose(filepointer);
Example: fclose(fp); // Where fp is a file pointer

Example Program1 using write mode to create new file and to write the data in
file:

#include<stdio.h>
void main(){
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","w");

printf("Input an integer");
scanf("%d",&i);
printf("Enter your name:");
scanf("%s",name);
fprintf(fp,"%d\n%s",i,name);
fclose(fp);
}

Output:
Input an intiger5
Enter ur name:gitam
34

Data1.txt
5
gitam

Example Program2 using read mode to read the data from file:

#include<stdio.h>
void main() {
int i;
char name[15];
FILE *fp;
fp=fopen("data1.txt","r");
fscanf(fp,"%d%s",&i,name);
printf("The integer in data1.txt is %d\n",i);
printf("The String in data1.txt is %s",name);
fclose(fp);
}

Output:
The integer in data1.txt is 5
The String in data1.txt is gitam

Example Program3 using append mode to add the data in the existing file:

#include<stdio.h>
void main() {
char name[15];
FILE *fp;
fp=fopen("data2.txt","a");
printf("Enter ur name:");
scanf("%s",name);
fprintf(fp,"%s",name);
fclose(fp);
fp=fopen("data2.txt","r");
if(fscanf(fp,"%s",name))
printf("%s",name);
fclose(fp);
}
35

Output:
Enter ur name:GITAM
GITAM
In data2.txt
GITAM

Again after appending:


Enter Ur name: University
GITAMUniversity
In data2.txt
GITAMUniversity

FILE STRUCTURE:
I/O functions available are similar to their console counterparts; scanf becomes fscanf, printf
becomes fprintf, etc., These functions read and write from file streams. As an example, the file
stream structure FILE defined in the header file stdio.h in DOS is shown below:

typedef struct
{
int level; /* fill/empty level of buffer */
usigned flags; /* File status flags */
char fd; /* File descriptor (handle) */
unsigned char hold; /* Ungetc char if no buffer */
int bsize; /* Buffer size */
unsigned char _FAR *buffer; /* Data transfer buffer */
unsigned char _FAR *curp;/* Current active pointer */
unsigned istemp; /* Temporary file indicator */
short token; /* Used for validity checking */
} FILE; /* This is the FILE Object *
NOTE: FILE is defined as New Structure Data Type in the stdio.h file as shown in above
method.

End Of File:

✓ EOF is a macro defined as an int with a negative value. It is normally returned by


functions that perform read operations to denote either an error or end of input. Input
from a terminal never really "ends" (unless the device is disconnected), but it is useful
36

to enter more than one "file" into a terminal, so a key sequence is reserved to indicate
end of input.
✓ Cntrl+Z is the key in DOS to end or terminate the input values.
✓ Cntrl+D is the key in UNIX to end or terminate the input values.

Example: /* A program to Write a file and read a file */


#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");
printf("Enter the Text:\n");
printf("Use Ctrl+z to stop entry \n");
while((scanf("%c",&ch))!=EOF)
fprintf(fp, “%c",ch);
fclose(fp);
printf("\n");
fp=fopen("DATA1.txt","r");
printf("Entered Text is:\n");
while((fscanf(fp,"%c",&ch))!=EOF)
printf("%c",ch);
fclose(fp);
}

Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi Raju...
how r u... how is ur studies...:-)
^Z // Cntrl+Z key terminated the input
values

Entered Text is:


Hi Raju...
how r u... how is ur studies...:-)

File Handling Functions:


37

We having various kinds of File Handling Functions, as some of them are discussed in previous
notes and remaining we can discuss now…

Reading Character from a file: fgetc( ) or getc( )

✓ fgetc( ) or getc( ) is a predefined file handling function which is used to read a single
character from a existing file opened in read(“r”) mode by fopen( ), which is same as
like getchar( ) function.

Syntax:
ch_var= fgetc(filepointer); (Or) ch_var=getc(filepointer);

Example: char ch;


ch=fgetc(fp); (Or) ch=getc(fp);

Where ‘ch’ is a character variable to be written to the file.


Where ‘fp’ is a file pointer object.

✓ getc( ) or fgetc( ) gets the next character from the input file to which the file pointer fp
points to. The function getc( ) will return an end-of-file(EOF) marker when the end of
the file has been reached or it if encounters an error.
✓ On Success the function fputc( ) or putc( ) will return the value that it has written to the
file, otherwise it returns EOF.

Example: /* A program to Read a file */


#include<stdio.h>
main( ){
FILE *fp;
char ch;

fp=fopen("DATA1.txt","r"); /* DATA1.txt is an already


existing file with content */
printf("Text from file is:\n");
while((ch=fgetc(fp))!=EOF)
/* (Or)
38

while((ch=getc(fp))!=EOF)*/
printf("%c",ch);
fclose(fp);
}

Output:
Text from file is:
Hi Raju... how r u... how is ur studies...:-)

Writing Or Printing Character in a file: fputc( ) or putc( )

✓ fputc( ) or putc( ) is a predefined file handling function which is used to print a single
character in a new file opened in write(“w”) mode by fopen( ), which is same as like
putchar( ) function.
Syntax:
fputc(ch_var , filepointer); (Or) putc(ch_var , filepointer);

Example: fputc(ch, fp); (Or) putc(ch, fp);


Where ‘ch’ is a character variable.
Where ‘fp’ is a file pointer object.

Example:
/* A program to Write a Character in a file and read a Character from a file */

#include<stdio.h>
main( ){
FILE *fp;
char ch;
fp=fopen("DATA1.txt","w");

printf("Enter the Text:\n");


39

printf("Use Ctrl+z to stop entry \n");


while((ch=getchar( ) )!=EOF) /*

fputc(ch,fp); /* (Or) putc(ch,fp); */


fclose(fp);
printf("\n");
fp=fopen("DATA1.txt","r");
printf("Entered Text is:\n");
while((ch=fgetc(fp))!=EOF)
putchar(ch);
fclose(fp);
}

Output:
Enter the Text:
Use Ctrl+z to stop entry
Hi ...
how are you... how is your studies...:-)
^Z // Cntrl+Z key terminated the input
values

Entered Text is:


Hi ...
how are you... how is your studies...:-)

Reading String from a file: fgets( )

✓ fgets( ) is a predefined file handling function which is used to read a line of text from an
existing file opened in read(“r”) mode by fopen( ), which is same as like gets( ) function.

General Format is:


char *fgets(char *s, int n,FILE *fp);
Syntax:
40

fgets(ch_var ,str_length, filepointer);

Example: char ch[10];


fgets(ch ,20, fp);
Where ‘ch’ is a string variable to be written to the file.
Where ‘fp’ is a file pointer object.
Where 20 is the string length in a file.

✓ The function fgets( ) read character from the stream fp into the character array ‘ch’ until a
newline character is read, or end-of-file is reached. It then appends the terminating null
character after the last character read and returns ‘ch’ if end-of-file occurs before reading
any character an error occurs during input fgets( ) returns NULL.

Writing Or Printing String in a file: fputs( )

✓ fputs( ) is a predefined file handling function which is used to print a string in a new file
opened in write(“w”) mode by fopen( ), which is same as like puts( ) function.
General Format:
Int fputs(const char *s, FILE *fp);
Syntax:
fputs(ch_var , filepointer);

Example:
char ch[10]=”gitam”;
fputs(ch, fp);
Where ‘ch’ is a string variable.
Where ‘fp’ is a file pointer object.
The function fputs( ) writes to the stream fp except the terminating null character of string s, it
returns EOF if an error occurs during output otherwise it returns a non negative value.

Example: /* A program to Write and Read a string in a file */


#include<stdio.h>
main()
{
char name[20];
char name1[20];
FILE *fp;
fp=fopen("dream.txt","w");
41

puts(“Enter any String\n”);


gets(name);
fputs(name,fp);
fclose(fp);
fp=fopen("dream.txt","r");
fgets(name1,10,fp); /* Here ‘10’ is nothing but String
Length, i.e., upto how-
puts(“String from file is:\n”); many characters u want
to access from a file. */
puts(name1);
fclose(fp);
}
Output:
Enter any String:
hi ram how r u
String from file is:
hi ram ho

Reading and Printing only integer value :getw() and putw():

The getw( ) and putw( ) are predefined file handling integer-oriented functions. They are
similar to the getc( ) and putc( ) functions and are used to read and write integer values.
These functions would be useful when we deal with only integer data. The general forms
of getw and putw are:

Syntax for getw( ):


integervariable=getw(filepointer);
Example:
int n;
n= getw(fp);
42

Syntax for putw( ):


putw(integervariable, filepointer);
Example:
putw(n,fp);

Example: /* A program to Write and Read only one Integer Value in a file */

#include<stdio.h>
main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts("Enter a number:");
scanf("%d",&n);
putw(n,fp); /* printing only integer value in a file */
fclose(fp);
fp=fopen("num.txt","r");
m=getw(fp); /* reading only integer value from a file */
printf("From File int val=%d",m);
}
Output1:
Enter a number: 16
From File int val=16

Output2:
Enter a number: 25 35 45
From File int val=25 /* here it take only one value,
basing on program requirement */
Output3:
Enter a number: 25.5
Frm File int val=25
Output4:
Enter a number: A
Frm File int val=28056 /* here it doesn’t print ASCII value
of ‘A’, it just print some-garbage value */

Example: /* A program to Write and Read more Integer Values in a file */


#include<stdio.h>
43

main()
{ int n,m;
FILE *fp=fopen("num.txt","w");
puts(“Press Cntl+Z to end the values”);
puts("Enter the numbers:");
while(scanf("%d",&n)!=EOF)
putw(n,fp);
fclose(fp);
fp=fopen("num.txt","r");
puts(“Entered values in file are:”);
while((m=getw(fp))!=EOF)
printf("%d\n",m);
}
Output:
Press Cntl+Z to end the values
Enter the numbers:
1 2 10 20 30 45
^Z
Entered values in file are:
1
2
10
20
30
45
/* File program to read a character file and encrypts it by
replacing each alphabet by its next alphabet cyclically i.e., z
is replaced by a. Non-alphabets in the file are retained as they
are. Write the encrypted text into another file */

#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fp1,*fp2;
char fname1[20],fname2[20];
char ch1,ch2;
printf("Enter the source file name ");
scanf("%s",fname1);
fp1=fopen(fname1,"r");
if(fp1==NULL)
44

printf("%s is not available",fname1);


else
{
printf("Enter the new file name ");
scanf("%s",fname2);

fp2=fopen(fname2,"w");
while((ch1=fgetc(fp1))!=EOF)
{
printf("%c",ch1);
if((ch1>=65 && ch1<=89) || (ch1>=97 && ch1<=121))
ch2=ch1+1;
else if(ch1==90 || ch1==122)
ch2=ch1-25;
else
ch2=ch1;

fputc(ch2,fp2);
}
printf("File copied into %s succesfull",fname2);
fclose(fp1);
fclose(fp2);
}
}

Output:

Enter the source file name apple.txt


Enter the new file name orange.txt
Vizag Zoo cell: 984822338File copied into orange.txt succesfull

Input text apple.txt Output text orange.txt


45

/*Program to read data from input file and place first 10


characters in an array and display on the monitor.*/
#include<stdio.h>
main()
{
FILE *fp;
int i=0;
char c,a[11];
fp=fopen(“INPUT”,”r”);
while(i<100)
{
c=getc(fp);
a[i]=c;
i++;
}
fclose(fp);
a[i]=’\0’;
puts(a);
}

Output

Computer i
46

/*Program to read a C program and count number of statement


terminators and number of opening braces.*/

#include<stdio.h>
main()
{
FILE *fp;
int s=0,b=0;
char c;
fp=fopen(“fib.c”,”r”);
while((c=getc(fp))!=EOF)
{
if(c==’;’)
s++;
if(c==’{‘)
b++;
}
fclose(fp);
printf(“\t\n number of statement terminators=%d”,s);
printf(“\t\n no of opening braces=%d”,b);
}

Output :
Number of Statements terminators=10
No.of Opening braces=3

/*Program to copy contents of one file into another file.*/

#include<stdio.h>
main()
{
FILE *fp1,*fp2;
47

char s;
fp1=fopen(“input.txt”,”r”);
fp2=fopen(“output.txt”,”w”);
while ((s=getc(fp1))!=EOF)
putc(s,fp2);
fclose(fp1);
fclose(fp2);
}

/*Program to append the contents to a file and display the


contents before and after appending.*/

#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp1,*fp2;
char s,c;
clrscr();
printf("\n\n\t one.txt contents are \n\n");
/*prints contents of file1 on monitor*/
fp1=fopen("one.txt","r");
while((c=getc(fp1))!=EOF)
printf("%c",c);
fclose(fp1);
printf("\n\n\t two.txt contents before appending are \n\n");
/*prints contents of file2 on monitor before appending*/
48

fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
/*appends contents of file1 to file2*/
fp1=fopen("one.txt","r");
fp2=fopen("two.txt","a");
while((c=getc(fp1))!=EOF)
putc(c,fp2);
fcloseall();
printf("\n\n\t two.txt contents after appending are \n\n");
/*prints contents of file2 on monitor after appending*/
fp2=fopen("two.txt","r");
while((c=getc(fp2))!=EOF)
printf("%c",c);
fclose(fp2);
}

Output:

one.txt contents are


C was developed by Denis Ritchie
two.txt contents befor appending are
C IS A MIDDLE LEVEL LANGUAGE.
two.txt contents after appending are
C IS A MIDDLE LEVEL LANGUAGE. C was developed by Denis Ritchie

/*Program to change all upper case letters in a file to lower


case letters and vice versa.*/

#include<stdio.h>
main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen("text.txt","r");
49

fp2=fopen("copy.txt","w");
while((c=getc(fp1))!=EOF)
{
if(c>=65&&c<=91)
c=c+32;
else
c=c-32;
putc(c,fp2);
}
fcloseall();
}

/*Program to read numbers from a file “data” which contains


a series of integer numbers and then write all odd numbers
to the file to be called “odd” and all even numbers to a file
called “even”.*/

#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp,*fp1,*fp2;
int c,i;
clrscr();
fp=fopen("data.txt","w");
printf("enter the numbers");
for(i=0;i<10;i++)
{
scanf("%d",&c);
putw(c,fp);
}
fclose(fp);
50

fp=fopen("data.txt","r");
fp1=fopen("even.txt","w");
fp2=fopen("odd.txt","w");
while((c=getw(fp))!=EOF)
{
if(c%2==0)
putw(c,fp1);
else
putw(c,fp2);
}
fclose(fp);
fclose(fp1);
fclose(fp2);
fp1=fopen("even.txt","r");
while((c=getw(fp1))!=EOF)
printf("%4d",c);
printf("\n\n");
fp2=fopen("odd.txt","r");
while((c=getw(fp2))!=EOF)
printf("%4d",c);
fcloseall();
}

Output:
Enter the numbers 1 2 3 4 5 6 7 8 9 10
Enter the numbers 1 2 3 4 5 6 7 8 9 10

2 4 6 8 10
1 3 5 7 9

You might also like