C-Structures, Unions, File Handiling
C-Structures, Unions, File Handiling
C-Structures, Unions, File Handiling
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.).
Create a Structure
1. struct structure_name
2. {
3.
4. data_type member1;
5. data_type member2;
6. .
7. .
8. data_type memeberN;
9. };
Let's see the example to define a structure for an entity employee in c.
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
Declaring structure variable
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring a variable at the time of defining the structure.
1st way:
Let's see the example to declare the structure variable by struct keyword. It
should be declared within the main function.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. };
Now write given code inside the main() function.
1. struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the
structure. Here, e1 and e2 can be treated in the same way as the objects in C+
+ and Java.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
1. struct employee
2. { int id;
3. char name[50];
4. float salary;
5. }e1,e2;
#include <stdio.h>
// 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;
}
1. #include<stdio.h>
2. #include <string.h>
3. struct employee
4. { int id;
5. char name[50];
6. float salary;
7. }e1,e2; //declaring e1 and e2 variables for structure
8. int main( )
9. {
10. //store first employee information
11. e1.id=101;
12. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
13. e1.salary=56000;
14. //store second employee information
15. e2.id=102;
16. strcpy(e2.name, "James Bond");
17. e2.salary=126000;
18. //printing first employee information
19. printf( "employee 1 id : %d\n", e1.id);
20. printf( "employee 1 name : %s\n", e1.name);
21. printf( "employee 1 salary : %f\n", e1.salary);
22.
23. //printing second employee information
24.
25. printf( "employee 2 id : %d\n", e2.id);
26. printf( "employee 2 name : %s\n", e2.name);
27. printf( "employee 2 salary : %f\n", e2.salary);
28. return 0;
29.}
Output:
employee 1 id : 101
employee 1 name : Sonoo Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000
typedef in C
Syntax of typedef
1. typedef <existing_name> <alias_name>
For example, suppose we want to create a variable of type unsigned int, then
it becomes a tedious task if we want to declare multiple variables of this type.
To overcome the problem, we use a typedef keyword.
Output
Value of i is :10
Value of j is :20
Output
Consider a case, where we need to store the data of 5 students. We can store
it by using the structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25.}
Output
Structure Pointer in C
A 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. Complex
data structures like Linked lists, trees, graphs, etc. are created with the help of
structure pointers. The structure pointer tells the address of a structure in
memory by pointing the variable to the structure variable.
Example:
C
// C program to demonstrate structure pointer
#include <stdio.h>
struct point {
int value;
};
int main()
{
struct point s;
// Initialization of the structure pointer
struct point* ptr = &s;
return 0;
}
In the above code s is an instance of struct point and ptr is the struct pointer
because it is storing the address of struct point.
There are two ways to access the members of the structure with the help of a
structure pointer:
1. With the help of (*) asterisk or indirection operator and (.) dot operator.
2. With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure
pointer with the help of the dot operator.
struct Student {
int roll_no; guv
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;
return 0;
}
int main() {
struct student s1;
C - Unions
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. Here is the way you would define a
union type named Data having three members i, f, and str −
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;
}
When the above code is compiled and executed, it produces the following
result −
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;
}
When the above code is compiled and executed, it produces the following
result −
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted
because the final value assigned to the variable has occupied the memory
location and this is the reason that the value of str member is getting printed
very well.
Now let's look into the same example once again where we will use one
variable at a time which is the main purpose of having unions −
Live Demo
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
}
When the above code is compiled and executed, it produces the following
result −
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is
being used at a time.
Enum in C
In the above declaration, we define the enum named as flag containing 'N'
integer constants. The default value of integer_const1 is 0, integer_const2 is 1,
and so on. We can also change the default value of the integer constants at the
time of the declaration.
For example:
1. enum fruits{
2. mango=2,
3. apple=1,
4. strawberry=5,
5. papaya=7,
6. };
Enumerated type declaration
1. enum status{false,true};
In the above statement, we have declared the 's' variable of type status.
1. enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true
will be equal to 1.
Output
The enum is also used in a switch case statement in which we pass the enum
variable in a switch parenthesis. It ensures that the value of the case block
should be defined in an enum.
1. #include <stdio.h>
2. enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday
};
3. int main()
4. {
5. enum days d;
6. d=monday;
7. switch(d)
8. {
9. case sunday:
10. printf("Today is sunday");
11. break;
12. case monday:
13. printf("Today is monday");
14. break;
15. case tuesday:
16. printf("Today is tuesday");
17. break;
18. case wednesday:
19. printf("Today is wednesday");
20. break;
21. case thursday:
22. printf("Today is thursday");
23. break;
24. case friday:
25. printf("Today is friday");
26. break;
27. case saturday:
28. printf("Today is saturday");
29. break;
30. }
31. return 0;
32.}
Output
C File Handling
When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
You can easily move your data from one computer to another without any
changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. 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.
They take minimum effort to maintain, are easily readable, and provide the
least security and takes bigger storage space.
2. Binary files
They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
File Operations
In C, you can perform four major operations on files, either text or binary:
4. Closing a 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;
Open for reading If the file does not exist, fopen() returns
rb
in binary mode. NULL.
rb+ Open for both If the file does not exist, fopen() returns
reading and NULL.
writing in binary
Opening Modes in Standard I/O
mode.
ptr = fopen("fileopen","mode");
For example,
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\
cprogram. The first function creates a new file named newprogram.txt and
opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the
file.
Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram. The second function opens the existing file for reading in
binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the
file.
Closing a File
The file (both text and binary) should be closed after reading/writing.
int main()
{
int num;
FILE *fptr;
// use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
Example 2: Read from a text file
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num
);
fclose(fptr);
return 0;
}
Functions fread() and fwrite() are used for reading from and writing to a file on
the disk respectively in case of binary files.
Writing to a binary file
To write into a binary file, you need to use the fwrite() function. The functions
take four arguments:
1. address of data to be written in the disk
2. size of data to be written in the disk
3. number of such type of data
4. pointer to the file where you want to write.
fwrite(addressData, sizeData, numbersData, pointerToFile);
In programming languages, files are utilized for long-term data storage or data
transfer purposes. The method of accessing a file varies depending on the type
of file system employed to retrieve data stored within the file.
Types of Files
Sequential files and random access files are two common ways of organizing
data in computer systems.
Sequential file:
In C language, a random access file allows us to read or write any data in our
disc file without reading or writing every piece of data before it. We can quickly
search for data, edit it, or even delete it in a random-access file. We can open
and close random access files in C using the same opening mode as sequential
files, but we need a few new functions to access files randomly.
Thus, the following three functions assist in accessing the random access file
in C:
1. ftell()
2. fseek()
3. rewind()
1. ftell():
It is a standard C library function used to get the current position of the file
pointer in a random access file. The function takes a file pointer as its
argument and returns the current position of the file pointer, representing the
number of bytes from the beginning of the file.
pos=ftell(FILE *fp)
include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n") ;
return 0;
}
printf("Position pointer in the beginning : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
printf("\nSize of file in bytes is : %ld\n",ftell(fp));
fclose(fp);
return 0;
}
Output:
prepbytes
2. fseek():
When fseek() is called, it sets the file position indicator to the specified position
in the file associated with the stream pointer. The offset argument specifies
the number of bytes to offset from the origin specified by whence.This
function is typically used in programs that need to read or write data from a
specific position in a file, such as when searching for a particular piece of data
in a large file or when appending data to the end of a file.
c
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error: File cannot be opened\n");
return 0;
}
fseek(fp, 4, 0);
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output:
bytes
rewind(FILE *fp);
#include<stdio.h>
int main()
{
FILE *fp;
fp = fopen("prepbytes.txt","r");
if(!fp)
{
printf("Error in opening file\n");
return 0;
}
printf("Position of the pointer : %ld\n",ftell(fp));
char ch;
while(fread(&ch,sizeof(ch),1,fp)==1)
{ printf("%c",ch);
}
printf("Position of the pointer : %ld\n",ftell(fp));
rewind(fp);
printf("Position of the pointer : %ld\n",ftell(fp));
fclose(fp);
return 0;
}
Output:
prepbytes
Explanation of rewind():
First, let us create a file – prepbytes.txt which contains the data: prepbytes.
We can observe that firstly when ftell is called, it returns 0 as the position of
the pointer is at the beginning, and then after traversing the file, when ftell is
called, 9 is returned, which is the size of the file. Now when rewind(fp) is
called, the pointer will move to its original position, which is 0. So the last ftell
returns 0