0% found this document useful (0 votes)
1 views20 pages

Module 05

Module-5 covers structures, unions, enumerated data types, and file handling in C programming. It explains how to define and use structures and unions, including their memory allocation and member access, as well as file operations such as opening, reading, writing, and closing files. Additionally, it discusses error handling and detecting the end of a file during file I/O operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views20 pages

Module 05

Module-5 covers structures, unions, enumerated data types, and file handling in C programming. It explains how to define and use structures and unions, including their memory allocation and member access, as well as file operations such as opening, reading, writing, and closing files. Additionally, it discusses error handling and detecting the end of a file during file I/O operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Module-5

Structure, Union, and Enumerated Data Type:

Introduction, structures and functions, Unions, unions

inside structures, Enumerated data type. Files:

Introduction to files, using files in C, reading and

writing data files. , Detecting end of file.


✓ Structure:
Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure.

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

data_type var-name; data_type var-name;

};

Example:

struct student

int r_no;

char name[20]; char course[20]; float fees;

};
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)
}; /

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and then
the name of the structure variable:

Create a struct variable with the name "s1":


struct myStructure

{
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.

Syntax: typedef existing data_type new data_type;

❖ Note: typedef statement does not occupy any memory, it simply defines a new type.

Example: typedef int INTEGER;

❖ 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.

Syntax to initialize a structure variable is:


struct struct_name
{
data_type member_name1; data_type member_name2; data_type member_name3;

}struct_var = {constant1, constant2, constant3, …};
struct struct_name
{
data_type member_name1; data_type member_name2; data_type member_name3;

};
struct struct_name struct_var = {constant1, constant2, constant3, …};
Example:
struct student
{
int r_no;
char name[20];
char course[20]; float fees;
}stud1 = {01, “Rahul”, “BCA”, 45000};

✓ Access Structure Members:


To access members of a structure, use the dot syntax (.):
Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

return 0;
}

Output: My number: 13

Copying and Comparing Structures:


❖ We can assign a structure to another structure of the same type.

❖ Example: If we have two structure variables stud1 and stud2 of type struct student as
below:

❖ struct student stud1 = {01, “Rahul”, “BCA”, 45000};

❖ struct student stud2;

❖ Then to assign one structure variable to another we will write:

❖ 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.

❖ Example: To compare the fees of two students, we will write:

if(stud1.fees > stud2.fees)

✓ Finding the size of a structure:


There are three different ways through which we can find the number of bytes a structure will
occupy in the memory.

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:

Passing Individual Members:


• To pass any individual member of the structure to a function we must use the direct
selection operator to refer to the individual members for the actual parameters.
• The called program does not know if the two variables are ordinary variables or structure
members.
#include <stdio.h>
typedef struct
{
int x; int y;
}POINT;
void display(int, int);

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

Passing the Entire Structure:


• Like any other variable, we can pass an entire structure as a function argument. When
structure is passed as an argument, it is passed using the call by value method, i.e., a copy
of each member of the structure is made.
• Syntax:
struct struct_name func_name(struct struct_name struct_var);
#include<stdio.h>
typedef struct
{
int x; int y;
}POINT;
void display(POINT);
int main()
{
POINT p1 = {2, 3};
display(p1); return 0;
}
void display(POINT P)
{
printf(“%d %d”, p1.x, p1.y);
}

Passing Structure Through Pointers:


Passing large structures to functions using the call-by-value method is very inefficient.

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.

It is extremely common to create pointers to structures. As in other cases, a pointer to a structure


is never itself a structure, but merely a variable that holds the address of a structure.
Syntax:

struct struct_name

data_type member_name1; data_type member_name2; data_type member_name3;

}*ptr;

OR

struct struct_name *ptr;

For student structure, we can declare a pointer variable by writing

struct student *ptr_stud, stud;

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( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

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( ) {

union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


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

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.).

file_ptr = fopen("example.txt", "r"); // Open for reading


if (file_ptr == NULL) {
perror("Error opening file");
return 1;
}

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)

❖ Reading from a File:


Use functions like fscanf() or fgets() to read data from the file.
char buffer[100];
while (fgets(buffer, sizeof(buffer), file_ptr) != NULL) {
printf("%s", buffer);
}
❖ Writing to a File:
To write data to a file, can use functions like fprintf() or fputs().
fprintf(file_ptr, "Hello, World!\n");
❖ Closing a File:
close the file using the fclose() function.
fclose(filePointer);

❖ 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];

// Open the input file for reading


inputFile = fopen("input.txt", "r");

if (inputFile == NULL) {
perror("Error opening input file");
return 1;
}

// Open the output file for writing


outputFile = fopen("output.txt", "w");

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);
}

// Close both files


fclose(inputFile);
fclose(outputFile);

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.

1. Include the necessary header file:


#include <stdio.h>
2. Open the file using fopen() and get a file pointer:
FILE *file = fopen("example.txt", "r"); // Open the file in read mode ("r")
if (file == NULL) {
perror("Error opening the file");
return 1;
}
3. Read data from the file using functions like fscanf() or fgets().
4. Check for the end of the file using feof():
int ch;
while ((ch = fgetc(file)) != EOF) {
// Process the character 'ch'
putchar(ch);
}
if (feof(file)) {
printf("\nEnd of file reached.\n");
} else {
printf("\nFile read error occurred.\n");
}

// Close the file when done


fclose(file);

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.!

You might also like