Module 5
Introduction to Structures
• Structures (also called structs) are a way to group
related variables into one place. several
•Each variable in the structure is known as a member of the
structure.
•Unlike an array, a structure can many different data
(int, float, char, etc.).
contain
types
•Definition:
Structure is a user-defined data type in C which allows to
combine different data types to store a particular type of
record.
The general format of a structure definition is as
follows:
struct tag_name {
data_type member1;
data_type member2;
–––––––––
–––––––
};
• Consider a book database consisting of book name, author, number of
pages, and price. We can define a structure to hold this information
as follows:
struct book_bank {
char title[20];
char author[15];
int pages;
float price;
};
• The keyword struct declares a structure to hold the details of four data
fields, namely title, author, pages, and price.
• These fields are called structure elements or members.
• Each member may belong to a different type of data
DECLARING STRUCTURE
VARIABLES
• After defining a structure format we can declare variables of that type.
• A structure variable declaration is similar to the declaration
of variables of any other data types.
• It includes the following elements:
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by commas.
4. A terminating semicolon.
1) Declaring Structure variables separately:
• For example, the statement
struct book_bank, book1, book2, book3;
-> declares book1, book2, and book3 as variables of type struct book_bank.
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
struct book_bank book1, book2, book3;
2) Declaring Structure variables with Structure definition
• It is also allowed to combine both the structure definition
and variables declaration in one statement.
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
} book1, book2, book3;
Typedef Declarations
• The typedef (derived from type definition) keyword enables the
programmer to create a new data type name from an existing data type.
• By using typedef, new data type is created
• Syntax:
typedef existing data_type new data_type
• Example:
typedef struct student
{
int r_no;
char name[20];
char course[20];
};
student stud1; // Structure declaration using variable
STRUCTURE
• A structure variable can be initialized at compile
INITIALIZATION
time. main()
{
struct student
{ /* This assigns the value 60 to student.weight and
180.75 to student.height. There is a one-to-one
int weight;
correspondence between the members and their
float height; initializing values. */
}
struct student s1 = {60,
struct student s2 = { 53, 170.60
180.75};
};
.....
.....
}
ACCESSING STRUCTURE MEMBERS
• The link between a member and a variable is established using the
member operator ‘.’ which is also known as ‘dot operator’ or
‘period operator’
• For example:
book1.price
This is the variable representing the price of book1 and can be treated
like any other ordinary variable
•To assign values to the members of book1:
book1.pages = 250;
book1.price = 120.50;
strcpy(book1.title, “BASIC”);
strcpy(book1.author, “Balagurusamy”);
•Using scanf to give the values through the keyboard.
scanf(“%s\n”, book1.title);
scanf(“%d\n”, &book1.pages);
//Ex: Write a Program using Structures to Read and Display the Information about a Student
#include<stdio.h>
int main()
{
struct student
{
int roll_no;
char name[80];
char DOB[80];
};
struct student stud1;
printf(“\n Enter the roll number : ”);
scanf(“%d”, &stud1.roll_no);
printf(“\n Enter the name : ”);
scanf(“%s”, stud1.name);
printf(“\n Enter the DOB : ”);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT’S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.roll_no);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n DOB. = %s”, stud1.DOB);
}
Structures and Functions
1. Passing individual members
2. Passing the entire structure
3. Passing Structures through Pointers
Passing Individual Structure Members to a Function
#include<stdio.h>
To pass any individual member typedef struct
of the structure to a function, {
• use the direct selection int x;
int y;
operator or dot operator to }POINT;
refer to the individual
void display(int, int);
members for the actual void display( int a, int b)
parameters. {
printf("%d %d", a, b);
}
main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
return 0;
}
Passing a Structure to a Function
• When a structure is passed as an #include<stdio.h>
typedef struct {
argument, it is passed using call by
int x;
value method.
int y;
That is a copy of each member of the }POINT;
structure is made. void display(POINT);
•Syntax: void display( POINT p)
struct struct_name func_name(struct struct_name struct_var);
{
printf("%d %d", p.x, p.y);
}
main() {
POINT p1 = {2, 3};
display(p1);
return 0;
}
Passing Structures through Pointers
• This is more efficient way than call by value method
• When passing a structure to a function by pointer, the
function operates on the original structure, not a copy.
• Inside a function, use the ->tooperator
access structure members
when working with pointers.
WAP using Pointer to Structure to Initialize the Members in the Structure
#include<stdio.h> main()
{
struct student struct student stud1, *ptr_stud1;
{
int r_no; ptr_stud1 = &stud1;
char name[20]; ptr_stud1->r_no = 01;
char strcpy(ptr_stud1->name, "Rahul");
course[20]; strcpy(ptr_stud1->course, "BE");
}; printf("\n DETAILS OF STUDENT");
printf("\n ");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME = ", puts(ptr_stud1->name));
printf("\n COURSE = ", puts(ptr_stud1->course));
}
End of Structures topic
Accessing Member of a
Union• A member of a union can be accessed using the same
syntax as that of a structure.
• To access the fields of a union, use the dot operator(.).
• That is the union variable name followed by the
dot operator followed by the member name.
Difference between Structure and Union
Unions inside Structures
Unions inside structures are useful:
• To store multiple types of data, but only one at a time (e.g., int, float,
char).
• To save memory by reusing the same memory location for
different types of data.
• To work with a structure that contains optional or variable data types
(e.g., parsing different formats of data).
This technique is often seen in low-level programming, such as operating
systems or embedded systems, where memory efficiency is critical.
End of Unions
Enumeration (or enum)
Enumerated Data
Type
• Enumeration (or enum) in C is a user defined datatype similar to
structures but consists ofand eachconstants
integral of them is
assigned with a specific name by the
user.integral constants are also known as enumeration
• The
constants
• Each integer value is assigned an identifier
• The value of an enumerator constant is always of the type
int.
•enum keyword is used to create the enumerated data type
and elements/identifiers are separated by commas.
• Syntax:
enum enum_name {
identifier1,
identifier2,
….
identifierN
};
• Example:
enum Season {
Summer
, Spring,
Winter,
Autumn
};
// C program to create enumerated data type for 7
days and display their values in integer constants.
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday,
Wednesday, Thursday, Friday, Saturday};
void main()
{
// printing the values of
weekdays for(int
i=Sunday;i<=Saturday;i++)
{
printf("%d, ",i);
}
}
// C program to create enumerated data type for 7 days. When you provide an enumerator as input to switch
case,
switch(day) {
it should<stdio.h>
#include display like "Today is Monday". case Sunday:
printf("Today is Sunday\n");
enum Day {Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; break;
case Monday:
int main() { printf("Today is Monday\n");
break;
case Tuesday:
enum Day day; printf("Today is
int input; Tuesday\n"); break;
case Wednesday:
printf("Enter a number (1 for Sunday, 2 for Monday, ..., "); printf("Today is Wednesday\n");
scanf("%d", &input); break;
case Thursday:
printf("Today is Thursday\n");
if (input < 1 || input > 7) {
break;
printf("Invalid input. Please enter a number between 1 and 7.\n"); case Friday:
return 1; printf("Today is Friday\n");
} break;
case Saturday:
// Assign the input value to the 'day' variable printf("Today is Saturday\n");
day = input; break;
default:
printf("Invalid input\n");
}
return 0;
}
Uses of enum
• Enum are frequently used in switch case statements
• Enums in C are a useful tool for creating more expressive and
maintainable code when you need to represent a fixed set of
values.
• To increase the readability of program instead of directly calling
value name can be used
• When a variable can have only set of values then enum can be used
End of Enumeration (or enum)
Files
Files
• A file is a container in computer storage devices used for storing
data.
Why files are needed?
•When a program is terminated, the entire data is lost. Storing in a
file will preserve your data even if the program terminates.
Types of Files
•When dealing with files, there are two types of files:
1. Text files
2. Binary files
1. Text files
• Text files are the normal .txt files. It is easy to create text files using
any simple text editors such as Notepad.
• Opening such files, the contents are seen within the file as plain text.
It is easy to edit or delete the contents.
2. Binary files
• Binary files are mostly the .bin files in computers.
• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
• 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 data from a file,
4. writing data to a file, and
5. closing a file.
Function name Operation
fopen() • Creates a new file for use or Opens an existing file for use
fclose() • Closes a file which has been opened for use
getc() • Reads a character from a file.
putc() • Writes a character to a file
fprintf() • Writes a set of data values to a file.
fscanf() • Reads a set of data values from a file.
getw() • Reads an integer from a file.
putw() • Writes an integer to a file.
• Filename is a string of characters that make up a valid filename for the
operating system. It may contain two parts, a primary name and an
optional period with the extension.
• Examples:
• Student.c
• store
• Text.out
• Data structure of a file is defined as FILE in the library of standard I/O
function definitions.
• Therefore, all files should be declared as type FILE before they are used.
• The FILE type in C is a structure, defined in stdio. h, representing a file
stream. It's an opaque data type, so users interact with it using
pointers, while the library manages its internal details.
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.
FILE *fptr;
2. Opening an existing file
• Opening a file is performed using the fopen() function defined in the
stdio.h header file.
• Format :
fptr= fopen(“file open”, “mode”);
Example:
fptr=fopen(“C:\\Desktop\a.txt”, “w”);
• writing as per the mode 'w’.
• Following is the general format for declaring and opening a file:
FILE *fp;
fp = fopen(“p1.c”, “mode”);
• The first statement declares the variable fp as a “pointer to the data
type FILE” and FILE is a structure that is defined in the I/O library.
• The second statement opens the file named p1.c and assigns an
identifier to the FILE type pointer fp.
• This pointer, which contains all the information about the file is
subsequently used as a communication link between the system and the
program.
• The second statement also specifies the purpose of opening this file.
The mode does this job.
Ex: Consider the following statements:
FILE *p1, *p2;
p1 = fopen(“data”, “r”);
p2 = fopen(“results”, “w”);
• The file ‘data’ is opened for reading and file ‘results’ is opened for
writing.
• In case, the results file already exists, its contents are deleted and the
file is opened as a new file.
• If data file does not exist, an error will occur
3. Closing a file
• The file (both text and binary) should be closed after reading/writing.
• This ensures that all outstanding information associated with the file
is flushed out from the buffers and all links to the file are broken.
• Another instance where we have to close a file is when we want to
reopen the same file in a different mode
• Closing a file is performed using the fclose() function.
• fclose(fptr);
• Example:
• The I/O library supports a function to do this for us. It takes the following
form:
fclose(file_pointer);
• This would close the file associated with the FILE pointer file_pointer. Look
at the following segment of a program.
..... .....
FILE *p1, *p2;
p1 = fopen(“a.txt”, “w”);
p2 = fopen(“b.txt”, “r”);
..... .....
fclose(p1);
fclose(p2);
.....
Example: The program opens myfile.txt for reading, reads it line by line into a buffer, and prints
each line to the screen. If the file can't be opened, it will print an error message using perror().
#include <stdio.h>
int main() { // Open for reading
FILE *file = fopen("myfile.txt", “r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
INPUT/OUTPUT OPERATIONS ON FILES
4. Reading and writing to a text file
• For reading and writing to a text file, we use the functions fprintf()
and fscanf().
fprintf
• The functions fprintf and fscanf works on files to
perform I/O operations i.e, to write and read from the files.
• The first argument of these functions is a file pointer
which specifies the file to be used.
• The general form of fprintf is
fprintf(fp, “control string”, list);
where fp is a file pointer associated with a file that
has been opened for writing
• Example: fprintf(f1, “%s %d %f”, name, age, 7.5);
// Demo the use of fprintf using " w "
mode
#include <stdio.h>
int main() {
FILE *file = fopen("myfile1.txt", "w");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
fprintf(file, "Hello, File!\n");
fputs("Another line.\n", file);
fclose(file);
return 0;
}
// Demo the use of fprintf using " r " mode
#include <stdio.h>
int main()
{
FILE *file = fopen("myfile1.txt", "r");
if (file == NULL)
{
perror("Error opening file");
return 1;
}
fprintf(file, "Hello, File!\n");
fputs("Another line.\n", file);
fclose(file);
return 0;
}
// Demo the use of fprintf using " a "
mode
#include <stdio.h>
int main()
{
FILE *file = fopen("myfile.txt", "a"); // Open for appending
if (file == NULL) {
perror("Error opening file");
return 1;
}
fprintf(file, "Appended line.\n");
fclose(file);
return 0;
}
fscanf Function
• fscanf - Reads a set of data values from a file
• Example: fscanf(f2, “%s %d”, item, &quantity);
• Like scanf,fscanf also returns the number of items that
are successfully read.
• When the end of file is reached, it returns the value EOF.
// Demo the use of
fscanf<stdio.h>
#include
int main() {
FILE *file = fopen("myfile1.txt", "r");
if (file == NULL)
{
perror("Error opening file for reading");
return 1;
}
char name[50];
fscanf(file, "%s", name);
printf("Name read from file: %s\n", name);
fclose(file);
return 0;
}
getc and putc Functions
• The simplest file I/O functions are getc and putc.
• These are analogous to getchar and putchar functions and handle one
character at a time.
• Assume that a file is opened with mode ‘w’ and file
pointerfp1. Then, the statement :
putc(c, fp1);
• This writes the character contained in the character variable c to the
file associated with FILE pointer fp1.
• Similarly, getc is used to read a character from a file that has been
opened in read mode.
• For example, the statement
c = getc(fp2);
• would read a character from the file whose file pointer is fp2.
• The file pointer moves by one character position for every operation of
getc or putc.
• The getc will return an end-of-file marker EOF, when end
of the file has been reached.
• Therefore, the reading should be terminated when EOF is encountered.
// Demo the use of getc and
#include
putc
<stdio.h> void
main() {
FILE *f1;
char c;
printf("Data Input:\n\n");
f1 = fopen("input.txt", "w");
while((c=getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf("\nData
Output:\n\n"); f1 =
fopen("input.txt","r");
while((c=getc(f1)) !=
EOF) printf("%c",c);
getw and putw Functions
• The getw and putw are integer-oriented functions.
• They are used to read and write integer values.
• These functions would be useful when using only integer data.
• The general forms of getw and putw are as follows:
putw(integer, fp);
getw(fp);
// Demo the use of getw and f1 = fopen("number.txt", "r");
putw
#include <stdio.h> if (f1 == NULL) {
int main() { perror("Error opening file for reading");
FILE *f1; int num; return 1;
}
f1 = fopen("number.txt", "w");
num = getw(f1);
if (f1 == NULL) {
if (num == EOF) {
perror("Error opening file for writing");
perror("Error reading integer from file");
return 1; fclose(f1);
} return 1;
}
printf("Enter a number to write to the file: ");
scanf("%d", &num); printf("The number read from the file is: %d\n", num)
putw(num, f1); fclose(f1);
fclose(f1); return 0;
}
Detecting the End of File
• The function feof() is used to check the end of file after EOF.
• It tests the end of file indicator. It returns non-zero value if successful
otherwise, zero.
// A simple program that demonstrates the use of feof()
#include <stdio.h> printf("Reading the file
int main() { content:\n"); while (!feof(f1)) {
FILE *f1; char c; c = fgetc(f1);
if (c != EOF) {
f1 = fopen("myfile1.txt", "r"); putchar(c);
if (f1 == NULL) { }
perror("Error opening file"); }
return 1; printf("\nEnd of file reached.\n");
} fclose(f1);
return 0;
}
End of Files
Completes Module
5