Module 05
Module 05
Unlike an array, a structure can contain many different data types (int, float, char, etc.).
❖ A structure is a user-defined data type that can store related information (even of different data
types) together. The major difference between the structure and the array is that an array
contains related information of the same data type.
❖ A structure is, therefore, a collection of variables under a single name. The variables within a
structure are of different data types and each has a name that is used to select it from the
structure.
Structure Declaration:
❖ A structure is declared using the keyword struct followed by the structure name. All the
variables of the structure are declared within the structure. A structure type is generally declared
by using the following syntax:
struct struct-name
};
Example:
struct student
int r_no;
};
Now, the structure has become a user-defined data-type
• Create a Structure:
create a structure by using the struct keyword and declare each of its members inside curly braces:
struct MyStructure
{ // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; /
Use the struct keyword inside the main() method, followed by the name of the structure and then
the name of the structure variable:
{
int myNum;
char myLetter;
};
int main()
{
struct myStructure s1;
return 0;
}
❖ Here, we declare two variables stud1 and stud2 of the type student.
❖ When we declare variables of the structure, separate memory is allocated for each variable.
✓ 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, no new data is created, rather an alternate name is given to a known data
type.
❖ Note: typedef statement does not occupy any memory, it simply defines a new type.
❖ INTEGER is the new name of data type int. To declare variables using the new data type
name, precede the variable name with the data type name(new). Therefore, to define an
integer variable, we may now write
INTEGER num=5;
❖ When we precede a struct name with typedef keyword, then the struct becomes a new type.
❖ It is used to make the construct shorter with more meaningful names for types already defined
by C or for types that we have declared.
❖ A typedef declaration is a synonym for the type.
typedef struct student
{
int r_no;
char name [20];
float fees;
};
❖ Here, we have preadded the structure’s name with the keyword typedef, student becomes a
new data type.
❖ Therefore, now we can straightaway declare variables of this new data type as we declare
variables of type int, float, char, etc. To declare a variable of structure we will just write:
student stud1;
✓ Initialization of Structure:
❖ A structure can be initialized in the same way as other data types are initialized. Initializing a
structure means assigning some constants to the members of the structure.
❖ When the user does not explicitly initialize the structure, then C automatically does that. For int
and float members the values are initialized to zero and character and string members are
initialized to ‘\0’ by default (in the absence of any initialization done by the user).
❖ The initializers are enclosed in braces and are separated by commas. However, care must be
taken to see that the initializers match their corresponding types in the structure definition.
int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);
return 0;
}
Output: My number: 13
❖ Example: If we have two structure variables stud1 and stud2 of type struct student as
below:
❖ stud2 = stud1;
❖ This statement initializes the members of stud2 with the values of members of stud1.
Therefore, now the values of stud1 and stud2 can be given as shown as below.
❖ C does not permit comparison of one structure variable with another. However, individual
members of one structure can be compared with individual members of another structure.
❖ When we compare one structure member with another structure’s member, the comparison will
behave like any other ordinary variable comparison.
Simple Addition: In this technique, we will make a list of all data types and add the memory
required by each.
Example:
struct Employee
{
int emp_ID;
char name[20]; double salary;
char designation[20]; float experience;
};
❖ Now, Size = size of emp_ID + size of name + size of salary + size of designation + size of
experience
❖ Size of emp_ID = 2
❖ Size of name = 20 * size of character
❖ Size of salary = 8
❖ Size of designation = 20 * size of character
❖ Size of experience = 4
❖ Therefore, size =
• = 2+20*1+8+20*1+4
• =2+20+8+20+4
• =54 Bytes
Using sizeof operator: This operator is used to calculate the size of a data type, variable, or an
expression.
❖ To use this operator simply write, sizeof (struct_name);
Example: The code below prints the size of the structure Employee.
#include<stdio.h>
typedef struct Employee
{
int emp_ID;
char name[20]; double salary;
char designation[20]; float experience;
};
void main()
{
struct Employee e; printf(“\n %d”, sizeof(e));
}
Output:
54
✓ Structures and functions:
There is a mechanism to pass structures to functions and return them. A function may access the
members of a structure in three ways:
int main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y); return 0;
}
void display(int a, int b)
{
printf(" The coordinates of the point are:%d %d", a, b);
}
Output:
The coordinates of the point are: 2 3
It is preferred to pass structures through pointers. It is possible to create a pointer to almost any
type in C, including user-defined types.
struct struct_name
}*ptr;
OR
The next thing to do is to assign the address of stud to the pointer using the address operator
(&) as we would do in case of any other pointer. So, to assign a address:
ptr_stud = &stud;
❖ union:
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];
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.
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data 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 −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
return 0;
}
Accessing Union Members:
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish
to access. You would use the keyword union to define variables of union type.
The following example shows how to use unions in a program –
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
return 0;
}
File:
In the C programming language, files are essential for reading and writing data to and from external
storage devices like hard drives, USB drives, and more. Understanding how to work with files is
crucial for tasks like data input/output, file manipulation, and data persistence. C provides a set of
standard library functions and data types to facilitate file handling.
❖ File Pointers:
In C, you interact with files using file pointers. A file pointer is a variable that stores the address of
the current position in the file. The most commonly used file pointers are FILE*, which is defined
in the <stdio.h> header.
#include <stdio.h>
FILE *file_ptr;
❖ Opening a File:
Before you can read from or write to a file, you need to open it. C provides the fopen() function
to do this. It takes two arguments: the filename and the mode (read, write, append, etc.).
Modes include:
"r": Read
"w": Write (creates a new file or truncates an existing one)
"a": Append (creates a new file or appends to an existing one)
"rb", "wb", "ab": Binary mode (for reading or writing binary files)
❖ Error Handling:
Always handle errors gracefully by checking the return values of file operations and using
perror() or custom error messages to provide useful information.
Here's a complete example that demonstrates reading from a file and writing to a file:
#include <stdio.h>
int main() {
FILE *inputFile;
FILE *outputFile;
char buffer[256];
if (inputFile == NULL) {
perror("Error opening input file");
return 1;
}
if (outputFile == NULL) {
perror("Error opening output file");
return 1;
}
// Read from the input file and write to the output file
while (fgets(buffer, sizeof(buffer), inputFile) != NULL) {
fprintf(outputFile, "%s", buffer);
}
return 0;
}
In C programming, you can detect the end of a file using functions provided by the standard C
library, typically when working with file I/O (input/output). The most common way to check for the
end of a file is by using the feof() function in conjunction with file pointers.
In this example, the feof() function is used to check if the end of the file has been reached
after reading each character. The loop continues reading characters until it reaches the end
of the file, as indicated by EOF (End of File). Remember to close the file using fclose()
when you're done with it to release system resources. Note that detecting the end of a file is
important to avoid reading beyond the end of the file, which could result in undefined
behavior or errors.
❖ Write a C program to copy a text file to another, read both the input file name and target
file name.
#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char ch, fname1[20], fname2[20];
printf("\n\n Copy a file in another name :\n");
printf("----------------------------------\n");
printf(" Input the source file name : ");
scanf("%s",fname1);
fptr1=fopen(fname1, "r");
if(fptr1==NULL)
{
printf(" File does not found or error in opening.!!");
exit(1);
}
printf(" Input the new file name : ");
scanf("%s",fname2);
fptr2=fopen(fname2, "w");
if(fptr2==NULL)
{
printf(" File does not found or error in opening.!!");
fclose(fptr1);
exit(2);
}
while(1)
{
ch=fgetc(fptr1);
if(ch==EOF)
{
break;
}
else
{
fputc(ch, fptr2);
}
}
printf(" The file %s copied successfully in the file %s. \n\n",fname1,fname2);
fclose(fptr1);
fclose(fptr2);
getchar();
}
Output:
Copy a file in another name :
----------------------------------
Input the source file name : 1.c
File does not found or error in opening.!