0% found this document useful (0 votes)
27 views13 pages

Unit 5

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

Unit 5

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

B.

TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV


UNIT-V
UNIT-V Structures, Unions, Bit Fields: Introduction, Nested Structures, Arrays of Structures,
Structures and Functions, Self- Referential Structures, Unions, Enumerated Data Type —Enum
variables, Using Type def keyword, Bit Fields. Data Files: Introduction to Files, Using Files in C,
Reading from Text Files, Writing to Text Files, Random File Access.

TOPIC - 1
I) STRUCTURE: In C programming, a structure is a user-defined data type that allows grouping related
variables of heterogeneous data types under a single name. Each item within a structure is called a
"member," and it can be of any valid C data type, such as integer, float, character, or even another
structure.
Structures in C provide a convenient way to handle more complex data by bundling different
types of information into one unit. For example, if you need to store a student’s name, age, and grade,
you can use a structure called Student with members for each of these values. Structures make it easier
to manage and organize data logically, especially when dealing with multiple records of mixed data
types.
Using the struct keyword, structures are defined only once but can be used to create multiple
variables (instances) with the same structure, making them powerful tools for organizing and handling
data in C programs.

a) C Structure Definition: To use a structure in a program, you need to create variables of that
structure type, which are known as instances. You can define these structure variables either right
after declaring the structure or separately later in the program. This allows you to allocate
memory and work with specific data values for each instance, making it possible to organize and
manage different sets of structured information efficiently.
i) Structure Variable Declaration with Structure Template: To declare structure
variables immediately after defining the structure template. This approach combines the
structure definition and variable declaration in a single line. After listing the structure
members with their data types, you specify the variables directly after the closing brace.
Syntax: Example:
struct structure_name { struct str1
data_type member_name1; {
............................................. int i; char c; float f; char s[30];
............................................. }s1,s2,s3;
} variable1, variable2, ...;

ii) Structure Variable Declaration after Structure Template: To create variables for a
structure after defining it separately. Once you've declared the structure template, you can
then use the structure's name followed by the variable names to create as many instances
as you need. This allows you to set up the structure first and then create variables for it
later in the code.
Syntax:
struct structure_name variable1, variable2, .......;
Example:
struct str1 s1,s2,s3;

b) Access Structure Members: You can access the members of a structure by using the dot (`.`)
operator. This operator connects the structure variable to its specific member, allowing you to
read or modify the member's value. For example, if you have a structure variable called `student`
and a member `age`, you would access it with `student.age`. This method helps you work with
individual parts of the structure's data.
Syntax:
structure_name.member1; structure_name.member2;

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
Example:
s1.i = 10; s1.c = 'A'; s1.f = 5.5; s1.s = "Hello";
Example of Structure in C
#include <stdio.h>
struct str1
{
int i; char c; float f;
};
void main() {
struct str1 var1 = { 1, 'A', 1.00};
printf("Struct 1:\n\ti = %d, c = %c, f = %f, s = %s\n", var1.i, var1.c, var1.f;
}

II. NESTED STRUCTURES: Nested structures in C refer to structures within other structures. This
setup allows grouping related data more effectively by embedding one structure inside another, enabling
complex data relationships within a single structure type.
In C programming, nested structures offer a way to organize hierarchical or multi-layered data by
allowing one structure to contain another structure as a member. This is useful when dealing with data
that has a natural "parent-child" relationship. For example, if you’re designing a structure for a "Person,"
you might want to include an "Address" structure as a part of it. Using nested structures makes the code
more modular and organized by keeping related data together, making it easier to understand and
manage.
There are two primary methods for nesting structures:
a) Embedded Structure Nesting
b) Separate Structure Nesting.
a) Embedded Structure Nesting: In embedded structure nesting, the nested structure is directly
defined within the parent structure. This means that the nested structure only exists within the
context of the parent and cannot be used separately in other parts of the program.
Syntax: Example:
struct Parent { struct Parent {
data_type parent_member1; int parent_member1;
data_type parent_member2; float parent_member1;
struct Nested { struct Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
} nested_variable_name; } child;
}; };
b) Separate Structure Nesting: In separate structure nesting, the nested structure is declared
independently and then used as a member within the parent structure.
Syntax: Example:
struct Nested { struct Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
}; };
struct Parent { struct Parent {
data_type parent_member; int parent_member;
struct Nested child_member; struct Nested child;
}; };
Accessing Nested Members: To access members of a nested structure, the dot operator (.) is used twice
in succession: once for the parent structure variable and then for the nested structure’s member. This
allows you to drill down into the structure hierarchy to reach the desired member.
Syntax:
struct Parent parent_variable;
COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM
B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
parent_variable.nested_structure_variable.member_name = value;
Example:
struct Parent p; p.child.nested_member1 = 10;
III. ARRAYS OF STRUCTURES: In C programming, an "array of structures" is an effective way to
organize and handle large sets of data that include multiple types. An array is a collection of elements of
the same type, while a structure groups different data types together. By combining them, you create an
array in which each element is a structure containing various data fields.
This method is highly useful when dealing with complex, large-scale data because it allows for
easy storage, access, and modification of grouped information. Instead of managing each data item
individually, an array of structures keeps all related data in an organized, single format. This makes the
code simpler, more readable, and much easier to maintain, especially when handling extensive datasets
with multiple fields.
By defining a structure (e.g., Student) and creating an array of that structure, you can efficiently
manage large datasets, such as student records with names, roll numbers, and grades. This approach
simplifies data organization and access, making the code easier to maintain.
Declaration:
struct structure_name array_name[number_of_elements];
Initialization:
struct structure_name array_name[number_of_elements] = {v11, v12, ...}, {v21,
v22, ...}, .... };

For instance, imagine we have to store data for 50 students, including information like name, roll
number, and grades. If we were to declare each student individually, like struct Student student1,
student2, ..., student50;, it would be tedious and difficult to manage. Now, imagine an even larger
scenario with hundreds of students—this approach becomes unmanageable.
Example Code:
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int rollNumber;
};
void main() {
struct Student students[3];
strcpy(students[0].name, "Raj");
students[0].rollNumber = 1;
strcpy(students[1].name, "Ram");
students[1].rollNumber = 2;
strcpy(students[2].name, "Shyam");
students[2].rollNumber = 3;
for (int i = 0; i < 3; i++)
printf("Roll Number: %d, Name: %s\n", students[i].rollNumber, students[i].name);
}

IV. STRUCTURES AND FUNCTIONS: In C programming, structures are used to define custom data
types, which can hold multiple pieces of information of different types. Functions, on the other hand, are
blocks of code that perform specific tasks, and they can be used with structures to manipulate data more
effectively.
1. Passing Structures to Functions: Structures can be passed to functions in two ways. In pass
by value, a copy of the structure is passed, and changes inside the function don’t affect the
original structure. In pass by reference, a pointer to the structure is passed, allowing the function
to modify the original structure directly, making it more efficient. There are two primary ways to
pass structures to functions:

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
a) Pass by Value: When a structure is passed by value, a copy of the structure is passed to the
function. The original structure is not affected by any changes made inside the function.
Example:
void modifyStudent(struct Student s) {
s.marks = 90.0;
}
b) Pass by Reference: When a structure is passed by reference (using pointers), the function can
directly modify the original structure. This is more efficient than passing large structures by
value because it avoids copying data.
Example:
void modifyStudent(struct Student *s) {
s->marks = 90.0;
}
2. Returning Structures from Functions: In C, functions can return structures, which means a
function can create a new structure, populate it with data, and send it back to the caller. This
allows for better organization of complex data types. By returning structures, you can efficiently
pass and manipulate related data between functions, improving code clarity. This method is
especially useful when you need to create or modify data in a function and return it for further
use.
Example:
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int rollNumber;
float marks;
};
struct Student createStudent(char name[], int rollNumber, float marks) {
struct Student s;
strcpy(s.name, name);
s.rollNumber = rollNumber;
s.marks = marks;
return s;
}
void modifyStudent(struct Student s) {
s.marks = 90.0;
}
void modifyStudentPtr(struct Student *s) {
s->marks = 90.0;
}
void main() {
struct Student student1 = createStudent("Raj", 1, 85.5);
printf("Name: %s\n", student1.name);
printf("Roll Number: %d\n", student1.rollNumber);
printf("Marks: %.2f\n", student1.marks);
modifyStudent(student1);
printf("Marks after modifyStudent: %.2f\n", student1.marks);
modifyStudentPtr(&student1);
printf("Marks after modifyStudentPtr: %.2f\n", student1.marks);
}

V. SELF- REFERENTIAL STRUCTURES: A self-referential structure in C is a structure that


contains a pointer to itself. This allows the structure to reference another instance of the same structure

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
type, enabling the creation of linked lists or other data structures that require elements to point to one
another.

Self-referential structures are a powerful concept in C programming. They allow a structure to


hold a pointer to itself, which is useful for building complex data structures like linked lists, trees, or
graphs. The pointer can be used to connect multiple instances of the structure, making it possible to
navigate through data dynamically.
Syntax:
struct structure_name {
data_type member;
struct structure_name *next; // pointer to the same structure
};
Example Program:
#include <stdio.h>
struct Node {
int data;
struct Node *next; // pointer to the next node
};
void main() {
struct Node n1, n2;
n1.data = 10; n1.next = &n2; // n1 points to n2
n2.data = 20; n2.next = NULL; // n2 is the last node
printf("Node 1 data: %d\n", n1.data);
printf("Node 2 data: %d\n", n2.data);
}
In this example, the structure Node contains a pointer to another instance of the same structure, creating
a self-referential link between n1 and n2.

TOPIC - 2
VI) UNION: In C programming, a union is a user-defined data type that allows storing different types of
data in the same memory location. Unlike a structure, where each member has its own memory space, all
members of a union share the same memory space. This means only one member can hold a value at a
time. Unions in C provide a way to efficiently use memory when different types of data are needed, but
only one of them will be used at any given moment.
Unions are typically used when you need to store different data types, but only one type of data
will be needed at a time. For example, you might store an integer, a float, or a character in a union, but
only one of these values will be used at a time. This makes unions an efficient way to manage memory,
especially in systems with limited resources.
Using the union keyword, unions are defined only once, but multiple variables (instances) of the
same union can be created, making unions an efficient tool for managing memory when different types
of data are required.
a) C Union Definition: To use a union in a program, you need to create variables of that union
type, which are known as instances. You can define these union variables either right after
declaring the union or separately later in the program. This allows you to allocate memory and
work with specific data values for each instance, making it possible to organize and manage
different types of data efficiently.
i) Union Variable Declaration with Union Template: To declare union variables
immediately after defining the union template. This approach combines the union
definition and variable declaration in a single line. After listing the union members with
their data types, you specify the variables directly after the closing brace.
Syntax:
union union_name {
data_type member_name1;

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
.............................................
.............................................
} variable1, variable2, ...;
Example:
union Data {
int i; float f; char str[20];
} data1, data2, data3;
ii) Union Variable Declaration after Union Template: To create variables for a union
after defining it separately. Once you've declared the union template, you can then use the
union's name followed by the variable names to create as many instances as you need.
This allows you to set up the union first and then create variables for it later in the code.
Syntax:
union union_name variable1, variable2, .......;
Example:
union Data data1, data2, data3;
b) Access Union Members: You can access the members of a union by using the dot (.) operator.
This operator connects the union variable to its specific member, allowing you to read or modify
the member's value. However, since all members of a union share the same memory, modifying
one member will affect all the other members of the union.
Syntax:
union_name.member1;
union_name.member2;
Example:
data1.i = 10;
data1.f = 220.5;
Example of Union in C:
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
void main() {
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 220.5;
printf("data.f: %.2f\n", data.f);
printf("data.i (after assigning float): %d\n", data.i);
}
In this example, the union Data holds an integer, a float, and a string. Since all members share
the same memory space, when the float is assigned to data.f, it overwrites the integer value
stored in data.i. Only the last assigned member can be accessed at any given time.

VII. NESTED UNIONS: Nested unions in C refer to unions defined within other unions or structures.
This allows grouping related data efficiently by embedding one union inside another, enabling more
complex data relationships. Nested unions are useful in scenarios where different types of data, but only
one at a time, need to be grouped together within a structure or another union.
In C programming, nested unions allow you to organize hierarchical or multi-layered data by
allowing one union to be contained as a member of another union or structure. This is particularly useful
when dealing with complex data structures that involve mutually exclusive data types, but need to be
grouped together under a single name.

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
There are two primary methods for nesting unions:
a) Embedded Union Nesting
b) Separate Union Nesting

a) Embedded Union Nesting: In embedded union nesting, the nested union is directly defined
within the parent union or structure. This means the nested union exists only in the context of the
parent and cannot be used separately in other parts of the program.
Syntax: Example:
union Parent { union Parent {
data_type parent_member1; int parent_member1;
data_type parent_member2; float parent_member2;
union Nested { union Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
} nested_variable_name; } child;
}; };

b) Separate Union Nesting:


In separate union nesting, the nested union is declared independently and then used as a member
within the parent union or structure. This allows the nested union to be used in multiple places in
the program, outside of the parent union.
Syntax: Example:
union Nested { union Nested {
data_type nested_member1; int nested_member1;
data_type nested_member2; char nested_member2;
}; };
union Parent { union Parent {
data_type parent_member; int parent_member;
union Nested child_member; union Nested child;
}; };

Accessing Nested Union Members: To access members of a nested union, you use the dot operator (.)
twice in succession: once for the parent union or structure variable and once for the nested union's
member. This allows you to drill down into the nested structure or union hierarchy to reach the desired
member.
Syntax:
union Parent parent_variable;
parent_variable.nested_union_variable.member_name = value;
Example:
union Parent p;
p.child.nested_member1 = 10;

VIII. ARRAYS OF UNIONS: In C programming, an "array of unions" is an effective way to organize


and handle multiple sets of data, especially when you want each set to contain different data types, but
only one type at a time. An array is a collection of elements of the same type, while a union allows
different data types to share the same memory space. By combining them, you create an array where
each element is a union containing various data fields.
This method is highly useful when dealing with complex, large-scale data that involves mutually
exclusive data types. Instead of managing each individual item separately, an array of unions organizes
the data into a single, manageable structure. This makes the code simpler, more readable, and much
easier to maintain, especially when handling large datasets with diverse types of information.

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
By defining a union (e.g., `Data`) and creating an array of that union, you can efficiently manage
multiple records, such as storing various types of data (integer, float, character) within each array
element. This approach simplifies the organization and access of the data.

Declaration:
union union_name array_name[number_of_elements];
Initialization:
union union_name array_name[number_of_elements] = { {v11, v12, ...}, {v21, v22, ...}, ... };

For instance, imagine you need to store information like different types of values (integers, floats,
characters) for 50 entries. Declaring each value individually would be cumbersome and difficult to
manage. However, using an array of unions, you can efficiently store this data.
Example Code:
#include <stdio.h>
union Data {
int i; float f; char c;
};
void main() {
union Data values[3];
values[0].i = 10; values[1].f = 3.14; values[2].c = 'A';
for (int i = 0; i < 3; i++)
printf("Data[%d] - Integer: %d, Float: %.2f, Char: %c\n", i, values[i].i, values[i].f, values[i].c);
}

IX. UNIONS AND FUNCTIONS: In C programming, unions are used to define custom data types that
can hold multiple pieces of information of different types, but only one type at a time. Functions, on the
other hand, are blocks of code designed to perform specific tasks. Unions can be used with functions to
manipulate data more effectively.
1. Passing Unions to Functions: Unions can be passed to functions in two ways. In pass by value, a
copy of the union is passed, and changes made inside the function don’t affect the original union. In pass
by reference, a pointer to the union is passed, allowing the function to modify the original union
directly. Passing by reference is more efficient, especially for large unions, because it avoids copying the
data.
a) Pass by Value: When a union is passed by value, a copy of the union is passed to the function.
Any modifications made to the union inside the function will not affect the original union.
Example:
void modifyData(union Data d) {
d.i = 100; // Modifying the copy of the union
}
b) Pass by Reference: When a union is passed by reference (using pointers), the function can
directly modify the original union. This is more efficient than passing large unions by value
because it avoids unnecessary copying of data.
Example:
void modifyData(union Data *d) {
d->i = 100; // Modifying the original union using pointer
}
2. Returning Unions from Functions: In C, functions can return unions, allowing a function to create a
new union, populate it with data, and send it back to the caller. This is useful for returning complex or
modified data from a function. By returning unions, you can effectively manage and organize related
data types across different parts of the program.
Example:
#include <stdio.h>
union Data {

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
int i; float f; char c;
};
union Data createData(int type) {
union Data d;
if (type == 1) {
d.i = 10;
} else if (type == 2) {
d.f = 3.14;
} else {
d.c = 'A';
}
return d;
}
void main() {
union Data data1 = createData(1); // Pass 1 to store an integer
printf("Integer value: %d\n", data1.i);
union Data data2 = createData(2); // Pass 2 to store a float
printf("Float value: %.2f\n", data2.f);
union Data data3 = createData(3); // Pass 3 to store a char
printf("Char value: %c\n", data3.c);
}

X. SELF-REFERENTIAL UNIONS: A self-referential union in C is a union that contains a pointer to


itself. This allows the union to reference another instance of the same union type, enabling the creation
of data structures like linked lists or other structures that require elements to point to one another. Self-
referential unions are particularly useful when working with complex, dynamically structured data.
Self-referential unions allow you to build data structures that need to contain multiple instances
of the same type in a dynamic way. By using pointers within a union, you can efficiently manage and
organize data, especially in scenarios such as linked lists where each node points to the next node in the
list. However, since a union can hold only one member at a time, the same union might store either a
piece of data or a pointer to the next union instance, but not both simultaneously.
Syntax:
union union_name {
data_type member;
union union_name *next;
};
Example Program:
#include <stdio.h>
union Node {
int data;
union Node *next;
};
void main() {
union Node n1, n2;
n1.data = 10;
n1.next = &n2; // n1 points to n2
n2.data = 20;
n2.next = NULL; // n2 is the last node
printf("Node 1 data: %d\n", n1.data);
printf("Node 2 data: %d\n", n2.data);
}
TOPIC - 3

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
XI. BIT FIELDS: In C programming, bit fields allow you to allocate a specific number of bits for a
variable within a structure or union. A bit field is used to store data in a compact way, typically for flags
or small integers, where only a small number of bits are needed. This can save memory and optimize the
program, especially when dealing with hardware or embedded systems where memory is limited.
Bit fields in C programming allow you to allocate a specific number of bits to individual
members of a structure or union. This is particularly useful when you want to store data in a compact
form, especially when dealing with flags or other small-sized data types, reducing memory usage.
Bit fields provide a way to define variables that use less than the normal amount of storage space.
Instead of using the default size for an integer (typically 4 bytes), you can allocate only as many bits as
needed for each variable, which can significantly reduce the memory footprint of your program.

Bit Fields in Structures: When using bit fields in structures, you can define a structure that allocates
only a specified number of bits to each member, making it possible to store small pieces of data more
efficiently. This is especially useful in cases where each member represents a flag (like a true/false
value) or a small range of values.
Syntax:
struct structure_name {
data_type member_name : number_of_bits;
};

Example of Bit Fields in a Structure:


#include <stdio.h>
struct Flags {
unsigned int flag1 : 1; // 1 bit for flag1
unsigned int flag2 : 1; // 1 bit for flag2
unsigned int flag3 : 2; // 2 bits for flag3
unsigned int flag4 : 4; // 4 bits for flag4
};
void main() {
struct Flags f1;
f1.flag1 = 1;
f1.flag2 = 0;
f1.flag3 = 3; // Max value that can be stored in 2 bits (11)
f1.flag4 = 7; // Max value that can be stored in 4 bits (1111)
printf("flag1: %u, flag2: %u, flag3: %u, flag4: %u\n", f1.flag1, f1.flag2, f1.flag3, f1.flag4);
}
In this example, the Flags structure has four members, with each member using a specified number of
bits:
flag1 and flag2 each use 1 bit. flag3 uses 2 bits.flag4 uses 4 bits.

Bit Fields in Unions: Bit fields can also be used in unions, where the members share the same memory
location. In a union, all members share the same starting memory address, but with bit fields, you can
still allocate different amounts of memory for each member (in terms of bits), even though the actual
data will overlap in the union.
Syntax:
union union_name {
data_type member_name : number_of_bits;
};

Example of Bit Fields in a Union:


#include <stdio.h>
union BitUnion {
unsigned int num1 : 4; // 4 bits for num1

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
unsigned int num2 : 6; // 6 bits for num2
};
void main() {
union BitUnion u1;
u1.num1 = 15; // Maximum value that can be stored in 4 bits (1111)
printf("num1: %u\n", u1.num1);
u1.num2 = 22; // Maximum value that can be stored in 6 bits (111110)
printf("num2: %u\n", u1.num2);
}
In this example, the BitUnion union has two bit fields, num1 and num2. Both fields share the same
memory space, but num1 occupies 4 bits, and num2 occupies 6 bits. Since bit fields in unions share
memory, modifying num1 will overwrite num2 if both are accessed at the same time.
TOPIC - 4
X. ENUMERATED DATA TYPE: An enumerated data type (enum) in C is a user-defined data type
that consists of a set of named integer constants. It provides a way to associate meaningful names with
integer values, making code more readable and maintainable.
Enums are particularly useful when you need to represent a fixed set of values. For instance, you
can define an enum to represent the days of the week, the months of the year, or the different states of a
program.

Syntax: enum enum_name { constant1, constant2, constant3, // ...};


Example: enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
In this example, we've defined an enum named Weekday with seven constants: Monday, Tuesday, and so
on. By default, the compiler assigns integer values to these constants, starting from 0. So, Monday will
have the value 0, Tuesday will have 1, and so on.
Program with Explanation:

#include <stdio.h>
enum Weekday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
int main() {
enum Weekday today = Wednesday;
printf("Today is %d\n", today); // Output: 2
return 0;
}
We've declared an enum named Weekday. We've declared a variable today of type Weekday and
assigned it the value Wednesday. The printf statement prints the integer value associated with
Wednesday, which is 2. By using enums, we can make our code more readable and less error-prone, as
we can use meaningful names for integer constants instead of raw numbers.

TOPIC – 5

INTRODUCTION TO FILES & TYPES:


A file is a collection of related data structure pertaining to a single entity. A file having payroll
data processes the information of pay elements and not about the personal and educational information
of an employee. So we can say file has mainly two basic elements: information and a single entity. In C
the word stream is used in place of a file.
A stream may be device like printer or monitor or file containing stream of bytes. So stream is
finite continuous flow of bytes (read, write storage is the flow of bytes) that go either as an output to a
file or come as an input the file. Types of Files:

i) Text Mode: All the text streams consist of lines of characters (string of characters) and
each line is terminated by a combination of carriage return (CR) and linefeed {LF}. When Enter

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
key is pressed. It is the pair, which is translated into a single new line character ('\n') as input and
the new line is translated back to a combination of two characters carriage return and linefeed.

ii) Binary Mode: No such types of translation take place. All characters are processed without
change. Binary files store floating point data more accurately and stored in compact way as
compared to the text files. In binary mode characters are stored and processed as in the main
memory.

DIFFERENT OPERATIONS ON A FILE: The processing of files has number of operation


according to the user's requirement and the problem definition. But some of the commonly used file
operations are as follows:
i. Naming or creating a file
ii. Opening a file
iii. Reading data from a file
iv. Writing data to a file
v. Closing a file
vi. Updating a file
i) Naming a file: File name (data file name) should not be more than eight characters and three
characters for extension. File name can be defined and enclosed by using the fopen( ) high-level I/O
function. The general Syntax is as follows:
fopen ("filename", "mode");
For example, "Student.dat" is a data file name, which is defined and enclosed in the fopen function as:
fopen ("Student.dat", "mode");
To define a file three things must be required. These are:
(i) Filename
(ii) Data Structure or creating the Buffer area for files.
(iii) Purpose

ii) Opening a file: A file is opened by using fopen (),in-built high-level input/output function. The
general format for declaring and opening a file is as:
FILE *fp;
fp =fopen("filename", "mode");
Where FILE is the data structure and is the low level reserve word of C Language for the creating a
buffer area as discussed already. Here fp is the file pointer tells us beginning of the buffer area for
storing the data, filename is the name of the data file having less than eight characters, mode is the
way file is opening and there are three modes in opening the files. These are as follows:
1. w Open the file for writing only
2. r Open the file for reading only
3. a Open the file for appending only.
Note that when you use "w" mode, new file will be created, If the file is already created, then it
will overwrite the data. For example, some valid file opening statements are as:
FILE *pl, *p2, *p3;
P1 = fopen("Raja", "r"); /* file opened for reading the data from
"Raja" file p2 = fopen ("Sunny", "w"); /* file opened for wring the data
to "Sunny" file
p3 = fopen ("MONA", "a"); /* file opened to insert more data to "MONA" already created data file */
Note that some compiler use "r+", "w+" and "a+" mode, which have meaning as:
r+ : both for reading and writing. The stream will be position at the start of the file.
w+ : both for reading and writing. The stream will be created if it does not exist.
a+ : both for reading and appending. The stream will be position at the end of the file.

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM


B.TECH (SEMESTER-1) : INTRODUCTION TO PROGRAMMING (IP) – JNTUGV
iii) Closing a file: A file, which is opened in any mode, should be closed. For this purpose fclose()
high-level input/output function is used. The general syntax is as:
fclose (file-pointer);
For example,
FILE *fl;
fl = fopen ("Raj","w");
fclose(fl);

Files Program :
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
fp = fopen("my_file.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "This is a line of text.\n");
fprintf(fp, "This is another line.\n");
fclose(fp);
fp = fopen("my_file.txt", "r");
if (fp == NULL) return 1;
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}

COMPUTER SCIENCE AND ENGINEERING DEPARTMENT (CSE), SITAM - VZM

You might also like