You are on page 1of 22

UNIT V : STRUCTURE, UNION AND FILES

Structure – Structure Definition - Structure Declaration - Nested structures –Array of


structures – Union — Storage classes – Files – Types of file processing : Sequential access,
Random access – Sequential access file – Random access file — Command line arguments.
Structure:
A Structure is a collection of variables of different data types under a single name. (i.e.
Structure is a collection of dissimilar data items.)
It is a user defined data type. There are three aspects of working with Structures:
1. Defining a Structure. ( Creating a new type)
2. Declaring variables and constants of the newly created type.
3. Using and performing operations on the objects of the structured type.

Array Structure
Array is a collection of same datatype Structure is a collection of different datatype
elements. elements.
An array is a derived datatype. Structure is a programmer defined one.
Array elements are referred by subscript. Structure elements are referred by their unique
name.
Array elements are accessed by their position Structure elements are accessed by their object
or subscript. as ‘.’ operator.
Does not have bit fields. May contain bit fields.
It is not a keyword. It is a keyword.

Defining a Structure:
● The general form of structure definition is
Syntax:
Struct Structure_name
{
datatype element1;
datatype element2;
datatype element n;
}; StructStructure_name var1, var2;
Struct Structure_name
{
datatype element1;
datatype element2;
datatype element n;
} var1, var2;

Example:
Struct Student{
char grade; floatavg; intrno;
};
intrno;
Struct Student S1; floatavg;
} S1;
Struct Student
{
char grade;

Initialization of a Structure:
● Structure elements can be initialized as follows,
Example:
Struct Student Struct Student
{ {
intrno; intrno;
int tot; int tot;
floatavg; floatavg;
} } S1={101, 486, 97.26};
Struct Student S1={101, 486,97.26};
● The amount of the memory space allocated to it is equal to the sum of the memory
space required by all of its members.
Example:
Struct Student Struct Student
{ {
char grade; 1 char name[20]; 20
int tot; 2 int tot; 2
floatavg; 4 floatavg; 4
} S1; } S1;
Size of the Structure = 7 bytes Size of the Structure = 26 bytes
(1+2+4 bytes) (20+ 2+4 bytes)

● printf(“%d”, Sizeof (Struct Student));


● A Structure object declaration can optionally have a storage class specifier (like auto,
static, extern, typedef, register….)
● The name of a structure member can be the same as the structure tag name.
Example:
Struct book
{
char book[20];
float price;
} b1;
● It is important to note that a structure definition does not reserve any space in the memory.
● It is not possible to initialize the structure definition.
Example: (It is not valid)
Struct book
{
char name[20] =” Computer programming”;
float price =430.50;
};
Anonymous Structure type:
● If a Structure definition does not contain a structure name, the created structure
type is un-named.
● The unnamed structure type is also known as anonymous structure type.
Example:
struct
{
int x;
int y;
};
Declaring Structure Objects:
● Declaring Structure variables.
● Structure variables are declared at the time of
At the time of Structure Defintion: After the Structure Defintion:
struct student struct student
{ {
intrno; intrno;
floatavg; floatavg;
}s1,s2; };
struct student s1, s2;
Pointers to structures:
● It is possible to create a pointer to a structure type.
● It can store the address of a structure variable.
● A pointer which is pointing to a structure is known as pointer to structure.
● To declare pointers to structures ,bt using the variable name with a asterisk in the
declaration.
● We can also declare two pointers to a structure.

Example:
struct stud
{
…………
…………
}s1,* s2;
s2 = &s1;
s1 Structure Variable
s2 Structure Pointer
Advantages of pointer to structure:
1. It is easier to manipulate the pointers to structure than manipulating structures
themselves.
2. Some data structures (linked list, trees…) use the structures containing pointers to
structures.
3. Passing a pointer to a structure as any argument to a function is afficient as compared
to passing a structure to a function.
Example Program: Student details using pointers to structures:
#include<stdio.h>
struct student
{
intrno;
int m1, m2, m3;
floatavg;
};
void main()
{
struct student s1={ 101,80,90,90,86.66}
struct student *s2 = &s1;
clrscr();
printf(“details are”);
printf(“%d %d %d %d %f”, s2rno, s2m1, s2m2, s2m3,s2avg);
getch();
}
Output:
details are
101 80 90 90 86.66
Array of structures:
● It is possible to create an array whose elements are of structure type, such an array is
known as an array of structure. (i.e) If there is a need to access more no. of structure
variables, then they can use structure variable as arrays.
Example:
struct student
{
intrno;
floatavg;
}s[50];
● Here the structure variable ‘s’ can store 50 student details.
● In such cases the structure elements are accessed with for loop as s[i].rno, s[i].avg.
(i.e) for (i=0;i<50;i++)
{
scanf(“%d %f”, &s[i].rno, &s[j].avg);
}
Example Program: Student details using structures
#include<stdio.h>
#include<conio.h>
struct student
{
char name[10];
intrno, m1, m2, m3, tot;
floatavg;
}s[50];
void main()
{
int n, i;
clrscr();
printf(“Enter the number of students \n”);
scanf(“%d”, &n);
printf(“Enter Name, Regno., 3 Marks \n”);
for(i=0;i<n;i++)
scanf(“%s %d %d %d %d”, &s[i].rno, &s[i].m1, &s[i].m2, &s[i].m3);
s[i].tot= s[i].m1+s[i].m2+s[i].m3;
s[i].avg= s[i].tot/3;
}
printf(“\n \n Student Mark List \n”);
printf(“********************************\n ”);
printf(“\n Name \t Regno \t Total \t Average \n”);
for(i=0;i<n;i++)
{
printf(“\n %s \t %d \t %d\t %0.2f”, s[i].name, s[i].rno, s[i].tot, s[i].avg);
}
getch();
}
Output:
Enter the number of students 2
Enter Name, Regno., 3 Marks
abc 101 90 90 90
xyz 102 80 80 80
Student Mark List
******************
Name Regno Total Average
abc 101 270 90.00
xyz 102 260 80.00

Structures within a Structure: (Nested Structure)


● A Structure can be nested within another Structure.
● Nested Structures are used to create complete data types.
● A nested Structure contain the members of other Structure types.
● It is possible to define a structure type within the declaration list of another Structure
type definition.
Example:
structnamelist
{
……….
………..
};
struct phonebook //nested structure
{
structnamelist name
………………….
…………………..
};
Program for Structure within a Structure. (nested structure)
#include<stdio.h>
#include<conio.h>
structnamelist
{
charfname[20];
charlname[10];
};
struct phonebook
{
structnamelist name;
char mobile[15];
};
void main()
{
struct phonebook p1,p2;
clrscr();
printf(“\n Enter person 1 details”);
printf(“\n Enter first name of p1”);
scanf(“%s”, p1.name.fname);
printf(“\n Enter last name of p1”);
scanf(“%s”, p1.name.lname);
printf(“\n Enter mobile number”);
scanf(“%s”, p1.mobile);
printf(“\n Enter person 2 details”);
printf(“\n Enter first name of p2”);
scanf(“%s”, p2.name.fname);
printf(“\n Enter last name of p2”);
scanf(“%s”, p2.name.lname);
printf(“\n Enter mobile number”);
scanf(“%s”, p2.mobile);
printf(“\n Records in phonebook \n”);printf(“ Name \t Mobile no. \n”):
printf(“\n %s %s \t %s”, p1.name.fname, p1.name.lname, p1.mobile);
printf(“\n %s %s \t %s”, p2.name.fname, p2.name.lname, p2.mobile);
getch();
}
Output:
Enter person1 details
Enter first name of p1 abc
Enter last name of p1 d
Enter mobile number 123456890
Enter person 2 details
Enter first name of p2 abcd
Enter last name of p2 e
Enter mobile number 56789012
Records in phonebook
Name mobileno.
abc d 1234567890
abcd e 56789012
Unions:
● A union is a collection of variable of different data types under a single name.
● (i.e) union is a collection of dissimilar data items.
● It is a user defined data type.
● All the aspects and the operations of union are same that of structure.
● The only difference between them is in the terms of storage of their members.
● In structure a separate memory is allocated to each member, while in unions, all
the member of an object share the same memory.
● Union type uses the keyword ‘union’.
● The size of a union is equal to the size of the largest data member.
Syntax:
unionunion_name
{ unionunion_name
data type element 1; {
data type element 2; data type element 1;
data type element n; data type element 2;
}; data type element n;
union union_nameunion_variable; } union variables;
Example:
union student
{
char grade;
intrno;
floatavg;
}s;
Size of the union student is 4 bytes
Maximum sized data member is avg(i.e float)
Address of union object:
● The members of a union objects are stored in the memory in such a way that they
overlap each other. (i.e) all the members of a union object start from the same
memory location, which in fact is the same as the starting address of the union
object.For example in the previous example the address of the elements grade,
rno, avg is the same.
Initialization of a union object:
● While initializing a union object it is allowed to initialize its first member only.
Example:
union student
{
intrno;
int m1, m2, m3;
floatavg;
};
union student s={101};
Example Program:
PROGRAM:
#include <stdio.h>
#include <string.h>
union student
{
int id;
char name[20];
float percentage;
};
int main()
{
union student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
// printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}

OUTPUT:
Name is:
Percentage is: 86.500000

S.No Structure Union


1. Structure is a collection of elements/ Union is a collection of variables of
variables of different data types. different data types.
2. It is a user defined data type. It is a user defined data type.
3. Keyword ‘struct’ is used Keyword ‘union’ is used
4. Each member has its own storage space. All the member use the same memory space
to store the values.
5. It can handle all the members at the same It can handle only one member at a time.
time.
6. Example: Example:
struct student union student
{ {
char grade; char grade;
intrno; intrno;
float avg; float avg;
}s; }s;

7. Size of the above structure is 7 bytes. Size of the above union is 4


bytes.(Maximum sized element)
8. More storage space is required. Less storage space is required.
9. It may be initialized with all its members Only its first member may be initialized.
Example: Example:
struct student union student
{ {
intrno; intrno;
float avg; float avg;
}; };
struct student s={101,95.50}; union student s={101};
Storage Classes:
The storage classes define the visibility (scope) and the lifetime of any function/
variable within a C program. Every identifier should be declared with data type as well as
storage class. If the storage class is not specified in a declaration statement, the compiler
assumes default storage class depending upon the scope in which the declaration is made.
The different types of storage classes in the C language are:
● Automatic Storage Class
● External Storage Class
● Static Storage Class
● Register Storage Class
● typedef
Class Name of Class Place of Scope Default Lifetime
Storage Value
auto Automatic RAM Local Garbage Within a function
Value
extern External RAM Global Zero Till the main program ends.
One can declare it
anywhere in a program.

static Static RAM Local Zero Till the main program ends.
It retains the available value
between various function
calls.

register Register Register Local Garbage Within the function


Value
Automatic Storage Class
It is also known as the auto storage class, and it acts as the default storage class for all
the variables that are local in nature.
For example,
{
int mount;
auto int month;
}

Features of automatic variables:


1. The allocation of memory for these variables occurs automatically during the
runtime.Variables without any storage class specification are called as auto
variables.They are called automatic variables because, their memory space is
automatically allocated as the variable is created.
2. The scope of an automatic variable is limited to that block in which we are defining
them.
3. The visibility of these variables is also limited to that block in which we are defining
them.Stored in main memory.scope of auto variable is local.
4. The initialization of these variables is, by default, a garbage value.Auto variables will
have garbage value.
5. The memory that is assigned to an automatic variable gets free when it exits from a
block.
6. The keyword auto is used to define the automatic variables.
7. Any local variable that exists in the C language is, by default, automatic in nature.
Syntax: auto datatype var1, var2,…..varn;
Example: auto float x,y;
Example Program using auto:
#include<stdio.h>
#include<conio.h>
void main()
{
autointa=10;
clrscr();
printf(“a is %d”, a);
getch();
}
Output:
a is 10
External Storage Class:
It is also known as the extern storage class, and we use it for giving a reference of any
global variable which is visible to all the files present in a program. When using the extern
storage class, we cannot initialize the variable.
The features of external variables:
● The external storage class can be used for conveying to the compiler that the variable
that has been defined as the extern has been declared using an external linkage that
exists elsewhere in any program.
● One can only perform the initialization of an external variable globally. Variables have
global scope.
The variables that are declared as extern have no allocation of memory.
● An external integral type’s default initial value is going to be 0, or else it is null.
● The external variable can be initialized multiple times, but we can only initialize it a
single time.
● External variables are declared out of main() function.
● The variables can be accessed in main function and inside the user defined functions.
Syntax: extern datatype var1, var2,…varn;
Example: extern int a;
Example Program:
#include<stdio.h>
#include<conio.h>
externint a=100;
void main()
{
printf(“a is %d”, a);
}
Output:
a is 100
Static Storage Class:
This type of storage class gives an instruction to a compiler to keep the given local
variable around during the program’s lifetime- instead of creating it and then destroying it
every time it comes into a scope and goes out of it. Thus, when a local variable is made
static, it allows the variable to maintain the values that are available between various function
calls.
Features of static variables:
1. Those variables that we define as static specifiers are capable of holding their
assigned value that exists between various function calls.
2. The static local variables are only visible to the block or the function in which we
have defined them.
3. We can declare the very same static variable multiple times, but we can only assign it
a single time.
4. The initial value of a static integral variable, by default, is 0. Else, it is null.
5. We use the static keyword in the case of a static variable.
6. The visibility of any static global variable stays limited to that file in which we have
declared it.
● Contents of static variables are permanent. (i.e) the contents of the variables remain
unchanged throughout the program.
● Stored in main memory.
● Scope of static variable is local and global scope.
● Static variables are initialized only once. It will not be reinitialized.
● Default value of static variable is zero.
Syntax: static datatype var1, var2,……varn;
Example: static inta,b;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
staticint a;
printf(“a is %d”, a);
}
Output:
a is 0

Register Storage Class:


The register storage class is used for defining the local variables that must be stored in
any register, and not in RAM. It means that the maximum size of this variable is equal to that
of the register size.
Features of register variables:
● Those variables that we define as the register have their memory allocation into the
CPU registers. It depends totally upon the size of the memory that remains in the
CPU.
● Its access time is comparatively much faster than that of the automatic variables.
● The default initial value of any given register local value will always be 0.
● We use the register keyword for the variable that must be stored in a CPU register.

Syntax:
storage class specifier data type variables;

Register:
● Are special storage classes within a computer’s CPU instead of storing in RAM or
main memory.
● Register specifies local scope.
Syntax: register datatype var1, var2,….varn;
Example: register int a=10;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
registerint a=10;
printf(“a is %d”, a);
}
Output:
a is 10

Typedef Storage class:


● Used to create a new mame for existing datatype.
Syntax:
typedefexisting_datatypenew_datatype_name;
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
typedefint number;
number a=10;
printf(“a is %d”, a);
}
Output:
a is 10
Advantages:
● Provides a meaningful way of declaring the variables.
● Increases the readability of the program.
● A complex declaration can be reduced to short and meaningful declaration.
● typedef is widely used while dealing with structures.
BASIC FILE OPERATIONS
File:
A file refers to a source in which a program stores the information/data in the
form of bytes of sequence on a disk (permanently). The content available on a file isn’t
volatile like the compiler memory in C. But the program can perform various operations,
such as creating, opening, reading a file, or even manipulating the data present inside the file.
This process is known as file handling in C.
Types of Files in a C Program
When referring to file handling, we refer to files in the form of data files. Now, these data
files are available in 2 distinct forms in the C language, namely:
1. Text Files
2. Binary Files
1. Text Files
The text files are the most basic/simplest types of files that a user can create in a C
program. We create the text files using an extension .txt with the help of a simple text editor.
2. Binary Files
The binary files store info and data in the binary format of 0’s and 1’s (the binary
number system). Thus, the files occupy comparatively lesser space in the storage.

Here’s a list of functions that allow you to do so:


Description of Function Function in Use
used to open an existing file or a new file fopen()
writing data into an available file fprintf()
reading the data available in a file fscanf()
writing any character into the program file fputc()
reading the character from an available file fgetc()
used to close the program file fclose()
used to set the file pointer to the intended file position fseek()
writing an integer into an available file fputw()
used to read an integer from the given file fgetw()
used for reading the current position of a file ftell()
sets an intended file pointer to the file’s beginning itself rewind()

File is a structure defined in ‘stdio.h’ to handle file operations. Various operations like
opening the file reading/writing in a file and closing the file can be done.
The operations that can be carried out on files in C language are as follows −
● Naming the file.
● Opening the file.
● Reading from the file.
● Writing into the file.
● Closing the file.

There are several naming conventions that are more or less in widespread use. This
includes prefixing or suffixing ptr or p to the name of the variable identifier.
Syntax
The syntax for opening and naming file is as follows −
FILE *File pointer;
For example, FILE * fptr;
File pointer = fopen ("File name”, "mode”);
To Open a File:
● The syntax for opening the file is: File* fopen(char* name, char* mode);
● Opens the file ‘name’ and returns the FILE pointer.
● Values for ‘mode’ are ‘r’,’w’and ‘a’.
● fopen returns NULL if its unable to open file.
● If file does not exist, fopen will create file, if mode is ‘w’ or ‘a’. We can use one of
the following modes in the fopen() function.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
Eg :
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}

Read/ Write to a File:


The syntax for reading or writing a character is shown below:
● Read a single character – int getc(FILE* fp);
● Write a single character – int putc(intc, FILE* fp);
Eg: #include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}
Output:
Enter the id
1
Enter the name
sonoo
Enter the salary
120000

Eg:
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("myfile.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
fclose(fp);
getch();
}
Eg:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char text[300];
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
getch();
}
Close a File – int fclose(FILE* fp);
The fclose() function is used to close a file. The file must be closed after performing all the
operations on it.
Eg:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Sequential File
A sequential file is a type of file structure used in computer systems to organize and store
data in a sequential order. In a sequential file, records are stored one after another, with each
new record being appended to the end of the file. This means that the records are stored in the
order they are added, and accessing the data follows a sequential pattern from the beginning
to the end of the file. In a sequential file, the records have a fixed length or are
variable-length with a marker indicating the end of each record. When reading or writing data
in a sequential file, the file pointer moves sequentially through the file, starting from the first
record and progressing through each subsequent record.

Random Access File:


A random access file is a type of file structure that allows direct access to any record within
the file, enabling efficient searching, updating, and retrieval of individual records. Unlike
sequential access files where data is organized and accessed sequentially, random access files
provide the ability to access records in any order based on their position or key. In a random
access file, records are stored with a unique identifier or a specific position within the file.
This identifier or position allows for direct access to a particular record without the need to
traverse through the entire file. The file system maintains an index or data structure that
facilitates efficient retrieval of records based on their identifiers or positions. Random access
files are advantageous in scenarios where frequent direct access or modification of specific
records is required. They are commonly used in applications that involve searching for
specific data, updating specific records, or retrieving data based on specific criteria.
Examples of applications that benefit from random access files include databases, file
systems, and data storage systems.

Difference between Sequential and Random Access File in Tabular Form


Parameter Sequential Access Random Access

Access Speed Sequential access files are Random access files, on the
slower compared to random other hand, allow direct
access files since accessing a access to specific records,
specific record requires resulting in faster access
reading through all the times.
previous records in the file

Access Method Sequential access files allow Random access files allow
access to records in a direct access to specific
sequential manner records using an index,
record number, or key.

Record Ordering Sequential access files store Random access files do not
records in a specific order, have any specific order of
usually the order in which storing records.
they were added to the file.

Insertion of new records Inserting a new record in a Random access files may
sequential access file is require relocating other
relatively easy since new records to maintain the order
records are added to the end so insertion becomes hard as
of the file. compared to sequential
access.

Memory Requirements Sequential access files Random access files require


require less memory than more memory because of
random access files since indexing information
they do not need to store any
indexing information.

Search Flexibility Search flexibility is limited Random access files offer


in sequential access higher search flexibility than
sequential access files since
they allow for direct access
to specific records based on
various search criteria
File Organisation Sequential access files are Random access files are
typically organized in a typically indexed.
linear fashion

Record Sizes In sequential access Random access files,


files, record sizes are record sizes can be
usually uniform variable

Examples Text files, Logs Database, Spreadsheet

Command Line Arguments in C:


The arguments passed from command line are called command line arguments. These
arguments are handled by main() function. To support command line argument, the structure
of main() function is to be changed as given below:
1. int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument. The
argv[] contains the total number of arguments. The first argument is the file name
always.Forward Skip 10s
Example:
Example of command line arguments where we are passing one argument with file name.
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
Run this program as follows in Linux:
1. ./program hello
Run this program as follows in Windows from command line:
1. program.exe hello
Output:
Program name is: program
First argument is: hello
If you pass many arguments, it will print only one.
1. ./program hello c how r u
Output:
Program name is: program
First argument is: hello
But if many arguments are passed within a double quote, all arguments will be treated as a
single argument only.
1. ./program "hello c how r u"
Output:
Program name is: program
First argument is: hello c how r u

You might also like