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

Module 5

The document provides an overview of structures, unions, enumerated data types, and file operations in C programming. It explains how to define and use structures, including initialization and accessing members, as well as the differences between structures and unions. Additionally, it covers file handling operations such as opening, reading, writing, and closing files, along with examples for better understanding.

Uploaded by

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

Module 5

The document provides an overview of structures, unions, enumerated data types, and file operations in C programming. It explains how to define and use structures, including initialization and accessing members, as well as the differences between structures and unions. Additionally, it covers file handling operations such as opening, reading, writing, and closing files, along with examples for better understanding.

Uploaded by

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

Module-5

Structure, Union, and Enumerated


Data Type and Files
• Structure :- Structure is a collection of one or
more variables of same or different data types
grouped to gather under a single name for easy
handling.

• Structure is a user defined data type that can store


related information together.
Defining a Structure –
• The keyword struct defines a structure.
• tag_name indicates name of the structure.
• The structure is enclosed within a pair of flower brackets and terminated with a semicolon.
• Each member is declared independently for its name and type.
• Syntax : -
struct tag_name
{
datatype member 1;
datatype member 2;
datatype member 3;
…………………..
…………………..
datatype member n;
};
• Example 1:-
struct employee
{
int emp_no;
char name[20];
int age;
float emp_sal;
};
Example 2-

struct bookbank
{
char author[50];
char title[50];
int year;
float price;
};
In the above example bookbank is structure name.
The title, author, price, year are structure members.
Declaring a structure variable-

• After defining a structure format we can declare variable for that type.

• Structure variable can be declared as-

struct tag_name variable_name;

• Example :-
struct employee emp1;

Here struct employee is user defined data type and emp1 is structure
variable.
Another Example-

• Declare a structure to store information of a particular


date.
struct date struct date
{ {
int day; OR
int day;
int month; int month;
int year; int year;
}; }dob;
struct date dob;
Typedef declarations
• The typedef keyword enables the programmer to create a
new data type from an existing data type.
• By using typedef no new data is created, rather an alternate
name is given to already existing data type.
• Syntax-
typedef existing_datatype new_datatype;
• Ex-
typedef int INTEGER;
Now, INTEGER is the new name of data type int.
INTEGER num=5;
Syntax and Example-

typedef struct typedef struct


{ {
datatype member 1; char title[50];
datatype member 2; char author[50];
- - - - - - -- int year;
- ------- float price;
datatype member n; }bookbank;
}NAME;
bookbank book1, book2;
NAME list_of_variables;
• Accessing structure members :- A structure
uses .(dot) [Member Access Operator] to
access any member of the structure.
• Example :-
emp1.emp_no =12345;
EX- C program to read & display information
about a employee.
#include<stdio.h>
struct employee
{
int emp_no;
char empname[20];
int age;
float emp_sal;
};
void main()
{
struct employee emp1;
printf("Enter Employee Number:");
scanf("%d",&emp1.emp_no);
printf("Enter Employee Name:");
scanf("%s",emp1.empname);
printf("Enter Employee age:");
scanf("%d",&emp1.age);
printf("Enter Employee salary:");
scanf("%f",&emp1.emp_sal);
printf("Employee Number=%d\n",emp1.emp_no);
printf("Employee Name=%s\n",emp1.empname);
printf("Employee Age=%d\n",emp1.age);
printf("Employee Salary=%f\n",emp1.emp_sal);
}
Initialization of structures
• Initializing structure means assigning some constants to
members of the structure.

• If user doesn’t initialize the structure then C automatically


initializes int and float members to 0 , character and string
members are initialized to ‘\0’ by default.
Method 1
Syntax- Example-
struct tag_name
struct bookbank
{ {
datatype member 1; char author[50];
datatype member 2; char title[50];
datatype member 3; int year;
………………….. float price;
………………….. };
datatype member n;
} struct bookbank book1 = {“Balaguruswamy”,
“CPPS”, 2021, 200.0};
struct tag_name structure_variable = { constant1,
constant2,….};
Method 2-
Syntax Example
struct tag_name struct bookbank
{ {
datatype member 1;
datatype member 2; char author[50];
datatype member 3; char title[50];
………………….. int year;
………………….. float price;
datatype member n; }book1 = {“Balaguruswamy”,
}structure_variable = { “CPPS”, 2021, 200.0};
constant1, constant2,….};
Copying and Comparing Structure Variables

Two variables of the same structure type can be copied the same
way as ordinary variables.
If emp1 and emp2 belong to the same type, then the following
statement is valid. emp1 = emp2, and emp2 = emp1;
However, the statements that are shown here:
e1 < e2; and e1 != e2; are not permitted.
Finding size of a structure
struct employee
{
int emp_no;
char empname[20];
int age;
float experience;
float emp_sal;
};
Method 1-
Size of structure= size of emp_no+size of empname+ size of age+ size
of experience+ size of emp_sal
= 2+ (20*1) + 2+ 4 +4=32 bytes.
Finding size of a structure
Method 2-Using sizeof() operator.
struct employee
{
int emp_no;
char empname[20];
int age;
float experience;
float emp_sal;
};

void main()
{
struct employee emp;
printf(“Size of structure= %d”, sizeof(emp));
}
• Nested Structures :- A nested structure is a structure that contains
another structure as its member.
Syntax :-
struct structure_name1
{
datatype member 1;
datatype member 2;
};
struct structure_name2
{
datatype member 1;
datatype member 2;
struct structure_name1 member3;
};
C program to read & display student information using nested structures.

#include<stdio.h>
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct DOB date;
};
void main()
{
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.name);
printf("Student DOB= %d-%d-%d\n", s.date.day, s.date.month, s.date.year);
}
Array of Structures :-
• If we want to store the data of 100 employees we
would require 100 structure variables from emp1
to emp100 which is definitely impractical.

• The better approach would be to use the array of


structures.
C program to read and display the information of
all employees of a company.
#include<stdio.h>
struct employee
{
int emp_no;
char empname[20];
int age;
float emp_sal;
};
void main()
{
struct employee emp[20];
int n,i;
printf("Enter the number of employee entries\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the details of employee”);
printf("Enter Employee Number:");
scanf("%d",&emp[i].emp_no);
printf("Enter Employee Name:");
scanf("%s",emp[i].empname);
printf("Enter Employee age:");
scanf("%d",&emp[i].age);
printf("Enter Employee salary:");
scanf("%f",&emp[i].emp_sal);
}
printf("\nEMP_NO\t EMP_NAME\t EMP_AGE\t\t EMP_SALARY \n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t%d\t%f\n",emp[i].emp_no,emp[i].empname,emp[i].age,emp[i].emp_sal);
}
}
Structures and Funtions :-
• Passing structures to functions can be done in
the following ways
– Passing individual members
– Passing entire structure or structure variable.
– Passing address of the structure.
1. Passing Individual Members :-

• While invoking the function from main( )in the place of actual arguments we
can pass the structure member as an argument.

#include<stdio.h>
void add(int x,int y);
struct addition
{
int a;
int b;
};
void main()
{
struct addition sum;
printf(" Enter two numbers\n");
scanf("%d%d",&sum.a,&sum.b);
add(sum.a,sum.b);
}

void add(int x,int y)


{
int res;
res=x+y;
printf("Resultant=%d\n",res);
}
2. Passing Entire structure or structure variable :-

• While invoking the function instead of passing the individual members the
entire structure, i.e. the structure variable is passed as a parameter to the
function.
#include<stdio.h>
struct addition
{
int a;
int b;
};
void add(struct addition sum);
void main()
{
struct addition sum;
printf(" Enter two numbers\n");
scanf("%d%d",&sum.a,&sum.b);
add(sum);
}
void add(struct addition sum)
{
int res;
res=sum.a+sum.b;
printf("Resultant=%d\n",res);
}
3. Passing Structures Through Pointers
Structure pointer is defined as the pointer which points to the address of the memory block
that stores a structure known as the structure pointer.
Ex-
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1;
struct Student* ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
printf("Roll Number: %d\n", (*ptr).roll_no);
printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch);
return 0;
}
Unions
• A union is a special data type available in C that allows to store different
data types in the same memory location.
• Union can be defined with many members, but only one member can contain
a value at any given time.
• Syntax:
union union_name
{
datatype field_name;
datatype field_name; // more variables
}union_variable;
Accessing Union Members
#include <stdio.h>
union Job {
float salary;
int workerNo; Output
} j;
void main() Salary = 0.0
{ Number of workers = 100
j.salary = 12.3;
j.workerNo = 100; // when j.workerNo is assigned a value, j.salary will no
longer hold 12.3 size of both the data type is 4byte

printf("Salary = %f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
}
Difference between structure and union
Difference between structure and union
Structure Union
Structure is a collection of one or more variables of same or A union is a special data type available in C that allows to store different
data types in the same memory location.
different data types grouped to gather under a single name
for easy handling.
Arrays of Union Variables
We can create array of unions similar to creating array of any primitive data type.
general form of declaration for array of union.
union <union_name> <array_name>[size];
Consider the following example,
union values {
int int_val;
float float_val;
};
union values arr[2];

Here, arr is an array of union which can hold two union elements.
Arrays of Union Variables
Array of union initialization:
union values arr[2] = {{1}, {2}};
Structures Inside Unions

• A structure can be nested inside a union and it is called


union of structures.
Enumerated Data Type
• Enumeration or Enum in C is a special kind of data type defined by
the user.
• Enumerated data consists of named integer constants as a list.
• Its value by default starts from zero and incremented by one
sequentially.
• Syntax: enum identifier{enumerated list};
Enumerated Data Type
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday};
void main(){
for(int i=Sunday ; i<=Saturday; i++) {
printf("%d, ",i);
}
}
Files
• A file is a collection of data stored on secondary storage device like hard
disk.
Types of Files: ASCII Text files 2. Binary files
1. ASCII Text files-
Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
2. Binary files-
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
File Operations
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
1. Creating a new file
When working with files, you need to declare a pointer of type FILE. This
declaration is needed for communication between the file and the program.

Syntax-
FILE * fptr;
2. Opening an existing file-
• A file must first be opened before reading/writing data to it.

• Opening a file is performed using the fopen() function


defined in the stdio.h header file.

• Syntax- FILE fptr;


fptr= fopen(“filename”, “mode”);

• Various modes- r : read mode, w: write mode , a: append to


text file
3. Closing a file-

The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
File Operations - open and close mode
File Operations – Write mode
Reading data from files-

• fscanf()- Used to read formatted data from file.


Syntax- fscanf(fptr,format_specifier,address_list);

• fgets()- Used to read a string from file.


Syntax-
fgets(string_name, n, fptr);
• fgetc()- Used to read a single character from file.
Syntax-
char ch= fgetc(fptr);
Writing data to files-
• fprintf()- Used to write formatted output to file.
Syntax- fprintf(fptr, format_specifier,variable_list);

• fputs()- Used to write a line/string to file.


Syntax- fputs(string_name, fptr);

• fputc()- Used to write a character to file.


Syntax- fputc(c,fptr);
Detecting the End of File

• "End of file" (EOF) is a term used in computer programming and


operating systems to indicate the point in a file where there is no more
data to be read.
• When a program reads data from a file, it typically keeps reading until it
encounters the end of file marker, at which point it knows that there is
no more data to be processed.
• The function eof() is used to check the end of file after EOF mark.
Detecting the End of File
Unions
• A union is a special data type available in C that allows to store different
data types in the same memory location.
• Union can be defined with many members, but only one member can contain
a value at any given time.
• Syntax:
union union_name
{
datatype field_name;
datatype field_name; // more variables
}union_variable;
Accessing Union Members
#include <stdio.h>
union Job {
float salary;
int workerNo; Output
} j;
void main() Salary = 0.0
{ Number of workers = 100
j.salary = 12.3;
j.workerNo = 100; // when j.workerNo is assigned a value, j.salary will no
longer hold 12.3 size of both the data type is 4byte

printf("Salary = %f\n", j.salary);


printf("Number of workers = %d", j.workerNo);
}
Difference between structure and union
Difference between structure and union
Structure Union
Structure is a collection of one or more variables of same or A union is a special data type available in C that allows to store different
data types in the same memory location.
different data types grouped to gather under a single name
for easy handling.
Arrays of Union Variables
We can create array of unions similar to creating array of any primitive data type.
general form of declaration for array of union.
union <union_name> <array_name>[size];
Consider the following example,
union values {
int int_val;
float float_val;
};
union values arr[2];

Here, arr is an array of union which can hold two union elements.
Arrays of Union Variables
Array of union initialization:
union values arr[2] = {{1}, {2}};
Structures Inside Unions

• A structure can be nested inside a union and it is called


union of structures.
Enumerated Data Type
• Enumeration or Enum in C is a special kind of data type defined by
the user.
• Enumerated data consists of named integer constants as a list.
• Its value by default starts from zero and incremented by one
sequentially.
• Syntax: enum identifier{enumerated list};
Enumerated Data Type
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday,
Thursday, Friday, Saturday};
void main(){
for(int i=Sunday ; i<=Saturday; i++) {
printf("%d, ",i);
}
}
Files
• A file is a collection of data stored on secondary storage device like hard
disk.
Types of Files: ASCII Text files 2. Binary files
1. ASCII Text files-
Text files are the normal .txt files. You can easily create text files using any
simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain
text. You can easily edit or delete the contents.
2. Binary files-
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
File Operations
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
1. Creating a new file
When working with files, you need to declare a pointer of type FILE. This
declaration is needed for communication between the file and the program.

Syntax-
FILE * fptr;
2. Opening an existing file-
• A file must first be opened before reading/writing data to it.

• Opening a file is performed using the fopen() function


defined in the stdio.h header file.

• Syntax- FILE fptr;


fptr= fopen(“filename”, “mode”);

• Various modes- r : read mode, w: write mode , a: append to


text file
3. Closing a file-

The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
File Operations - open and close mode
File Operations – Write mode
Reading data from files-

• fscanf()- Used to read formatted data from file.


Syntax- fscanf(fptr,format_specifier,address_list);

• fgets()- Used to read a string from file.


Syntax-
fgets(string_name, n, fptr);
• fgetc()- Used to read a single character from file.
Syntax-
char ch= fgetc(fptr);
Writing data to files-
• fprintf()- Used to write formatted output to file.
Syntax- fprintf(fptr, format_specifier,variable_list);

• fputs()- Used to write a line/string to file.


Syntax- fputs(string_name, fptr);

• fputc()- Used to write a character to file.


Syntax- fputc(c,fptr);
Detecting the End of File

• "End of file" (EOF) is a term used in computer programming and


operating systems to indicate the point in a file where there is no more
data to be read.
• When a program reads data from a file, it typically keeps reading until it
encounters the end of file marker, at which point it knows that there is
no more data to be processed.
• The function eof() is used to check the end of file after EOF mark.
Detecting the End of File

You might also like