0% found this document useful (0 votes)
25 views

new UNIT-V

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)
25 views

new UNIT-V

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/ 75

UNIT-V STRUCTURES, UNION AND FILES

Structure - Nested structures – Pointer and Structures – Array of structures – Self-referential structures – Dynamic
memory allocation - Singly linked list – typedef – Union - Storage classes and Visibility. Files – Types of file
processing: Sequential access, Random access – Sequential access file - Random access file - Command line
arguments

5.1 INTRODUCTION
● As we know that, Array is a collection of elements of same type, but many times we have to store the
elements of different data types.
● The structure is a convenient way of grouping several pieces of related information together.
● Structure is a collection of different variables under single name.

5.2 NEED FOR STRUCTURE DATA TYPE


● A variable stores a single value of a data type.
● Arrays can store many values of similar data type.
● In real life, we need to have different data types.
Example: To maintain employees information we should have information such as their name, age,
qualification, salary etc.
● Here, to maintain the information of employees, dissimilar data types are required.
● For tackling such mixed data types, a special data type provided by C called structure is needed.

5.3 STRUCTURE DEFINITION


Definition:
A Structure is a user defined data types.
A structure is a collection of one or more variables of different data types, grouped together under
a single name.(OR)
Structure is a collection of variables under the single name, which can be of different data type.
Consider the data of student mark analysis: name,rollno marks, and
struct student
average. A structure data type called student can hold all this
{
information:
char name[20];int
rollno;
int marks[8];
float avg;
};

Consider the another examples for structures type


struct employee struct address struct date struct book
{ { { {
char name[20]; char name[20]; int day; char name[30];
int empno; int doorno; int pageno;
char month[10];
char desgn[8]; char street[8]; int year float price;
float salary; char city[8]; };
int exp ; };

};
5.4 STRUCTURE DECLARATION
The structure can be declared with the keyword struct following the name and opening brace with data
elements of different type, and then closing brace with semicolon. Structure can be declared as follows:
Syntax:

struct structure_name struct structure_name


{ {
data_type variable1; data_type variable1;
data_type variable2; data_type variable2;
. .
. .
(OR) .
.
data_type variablen; data_type variablen;
}v1,v2,….,vn; };
where v1,v2,….,vn are struct structure_name v1,v2,….,vn;
structure variables.
4.4.1 Rules for declaring a structure:
● A structure must end with a semicolon
● The structure appears at the top of the source program
● Each structure element must be terminated
● The structure variable must be accessed with dot(.) operator
Example: Declaring a structure for date
● The structure can be declared with the keyword struct following the name and opening brace with
data elements of different type, then closing brace with semicolon.
● The individual structure elements are called as members.
● Name given to structure is called tag. Example: date
● Declaration of Structure reserves no space.
● It is nothing but the “ Template / Map / Shape ” of the structure .
● Memory is created , very first time when the variable is created / Instance is created.

4.4.2 Accessing structure elements:


● After declaring the structure type, variables, and members, the member of the structure can be
accessed by using the structure variable along with the dot (.) operator
Different Ways of Declaring Structure Variable and Accessing structure elements:

//Way 1 : Declaring structure variable


within the structure definition itself
struct date
{
int day;
}
// For accessing the structure members for
the above example
Structure name = date
Structure members are day,month,year
Structure variable=today
Syntax: structure_variable.memeber_name
i.e.,
today.day ,today.month , today.year
Read: scanf(“%d”, &today.day)
//Way 2 : Declare Variables within the
scanf(“%s”,today.month)
main function scanf(“%d”, &today.year)
struct date Write: printf(“%d”, today.day)
{ printf(“%s”,today.month)
int day; printf(“%d”, today.year)
char month[20];
int year;
};

main()
{
struct date today;
}

/*where “date” is name of structure & “today”


is name of the structure variable.*/

//Way
. 3 : Declaring Multiple Structure Variables
struct date
{
int day;
char month[20];
int year;
}yesterday,today,tomorrow;

//where “date” is name of structure &


“yesterday,today
4.4.3 & tomorrow”
Initialization of structure:
are name of the
structure variable.
Note: Structure variable can be any of three types: normal variable, array_variable,
pointer_variable.
4.4.3 Initialization of Structure members:
1: Structure variable is a normal variable
A structure variable, like a normal variable can be initialized in to multiple ways:
Within structure definition

1.Declare and Initializing 2.Declaring and Initializing Multiple Variables


Single Variables
struct student
struct student {
{ char name [80];
char name [80]; int roll_no;
int roll_no; float marks ;
float marks ; } s1={“Saravana”,54,469},
} s1={“Saravana”,54,469}; s2={“kumar”,39,437};

Within main function


struct student
struct student
{
{
char name [80];
char name [80]; int roll_no;
int roll_no; float marks ;
float marks ; } s1,s2;
} s1;

void main() void main()


[OR]
{ {
struct student s1= struct student s1=
{“Saravana”,54,469}; {“Saravana”,54,469};
struct student
-- s2={“kumar”,39,437};
-- --
} }

4.4.4 Rules for initializing structure:


The individual data members of structure cannot be initialized.
The structure variables can be initialized at compile time only.
The order of data members in a structure must match the order of values in enclosed brackets.
We can initialize only some of the data members of the structure. The uninitialized data members can
be initialized by default with zero (0) for int and float, ‘\0’ for character and strings.
Program: To print the vehicle details using structure
#include<stdio.h>
struct Vehicle
{
int wheels;
char vname[20];
char color[10];
}v1 = {4,"Nano","Red"};

void main() Output


{ Vehicle No of Wheels : 4 Vehicle
printf("Vehicle No of Wheels : %d",v1.wheels); Name : Nano
printf("Vehicle Name : %s",v1.vname); Vehicle Color : Red
printf("Vehicle Color : %s",v1.color);
}
Program: To print student number, name, and marks using structures
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int eng,phy,mat,chem,pc;
float avg;

}s;
void main()
{
int total;
clrscr();
printf("Enter student details:\n");
printf("Enter student name:");
scanf(" %s”,s.name);
printf("Enter student rollno:");
scanf(" %d ",&s.rollno);
printf("Enter subject mark:");
scanf(" %d%d %d %d %d %d",&s.maths,&s.eng,&s.phy,&s.chem,&s.pc);
total=s.maths+s.eng+s.phy+s.chem+s.pc ;
s.avg=total/5;
printf("\nAverage of %s,RollNo:%d is %d and %0.2f", s.name,s.rollno,s.avg);
getch();
}
Output:
Enter student details:
Enter student name, rollno, mark1, mark2, mark3: Banu 6 99 98 97 98 97
Average of Banu,RollNo.6 is 98.00

ARRAY OF STRUCTURES [array variable]


Structure is used to store the information of One particular object but if we need to store such
100 objects then Array of Structure is used.
Example :

struct Bookinfo
{
char Name[20];
int Pages;
float Price;
}Book[100];

Explanation :
1. Here Book structure is used to Store the information of one Book.
2. In case if we need to store the Information of 100 books then Array of Structure is used.
3. Book[0] stores the Information of 1st Book ,B[1] stores the information of 2nd Book and So on
We can store the information of 100 books.
Book[3] is shown Below

Accessing member of Array of Structure:


The use of the period operator can be extended to arrays of structure by writing:
array [expression].member_name
for example Accessing Pages field of Second Book : Book[1].pages
//Source Code
#include <stdio.h>
#include<conio.h>
struct Bookinfo
{
char bname[20];
int pages;
float price;
};
void main()
{
int i;
struct Bookinfo book[3];
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
scanf("%s",book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",&book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",&book[i].price);
}
printf("\n--------- Book Details ");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
getch();
}
Output
Enter the Name of Book : ABC
Enter the Number of Pages : 100
Enter the Price of Book 200
Enter the Name of Book : EFG
Enter the Number of Pages : 200
Enter the Price of Book 300
Enter the Name of Book : HIJ
Enter the Number of Pages :
300 Enter the Price of Book
500
Book Details
Name of Book : ABC
Number of Pages : 100
Price of Book 200
Name of Book : EFG
Number of Pages : 200
Price of Book : 300
Name of Book : HIJ
Number of Pages : 300
Price of Book : 500
//Lab Program
Program :To generate student mark sheets with subject details and the grades using structure
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
int m1,m2,m3,tot;
float avg;
char grade;
}s[30];
void main()
{
int i,n;
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Student %d details",i+1);
printf("\nEnter name:");
scanf("%s",s[i].name);
printf("Enter Rollno:");
scanf("%d",&s[i].rollno);
printf("Enter 3 subject marks:");
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].tot=0,s[i].avg=0.0; s[i].tot=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].tot/3;
if(s[i].avg>=90)
s[i].grade='S';
else if(s[i].avg>=80)
s[i].grade='A';
else if(s[i].avg>=70)
s[i].grade='B';
else if(s[i].avg>=60)
s[i].grade='C';
else if(s[i].avg>=55)
s[i].grade='D';
else if(s[i].avg>=50)
s[i].grade='E';
else
s[i].grade='U';
}
printf("\t\t\tSTUDENTS MARK SHEET");
printf("\n\t\t ");
printf("\nName\tRollno\tMark1\tMrak2\tMark3\tTotal\tAvg\tGrade");

for(i=0;i<n;i++)
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%f\t%c",s[i].name,s[i].rollno,s[i].m1,s[i].m2,s[i].m3,s[i].tot,s[i].avg,
s[i].grade);
getch();
}
OUTPUT
Enter number of students:
3 Enter Student 1 details
Enter name:abi
Enter Rollno:1
Enter 3 subject marks:90
89
98
Enter Student 2 details
Enter name:meena
Enter Rollno:6
Enter 3 subject marks:78
90
89
Enter Student 3 details
Enter name:priya
Enter Rollno:6
Enter 3 subject marks:56
78
76
STUDENTS MARK SHEET

Name Rollno Mark1 Mrak2 Mark3 Total Avg Grade


abi 1 90 89 98 277 92.000000 S
meena 6 78 90 89 257 85.000000 A
priya 6 56 78 76 210 70.000000 B
POINTER TO STRUCTURES[Pointer variable]
Pointer which stores address of structure is called as “Pointer to Structure“.
A pointer which is pointing to a structure is known as pointer to structure.
Explanation :
1. sptr is pointer to structure
address.
2. -> and (*). both represents the
same.
3. These operators are used to access
data member of structure by using
structure’s pointer.
The use of the arrow operator can be
extended to pointer of structure by writing:
structure_variable member_name
//Source Code
#include<stdio.h>
struct team
{
char *name;
int totmembs;
char captain [20];
}t1 = {"India",11,"Dhoni"}, *sptr = &t1; void
main()
{
printf("\nTeam : %s",(*sptr).name); Output
printf("\nTotalMemebers : %d",sptr-> totmembs); Team : India
printf("\nCaptain : %s",sptr->captain); TotalMemebers : 11
} Captain : Dhoni

EXAMPLE PROGRAM FOR SALARY SLIP GENERATION

#include <stdio.h>
struct employee
{
char name[10];
int basic, da, hra, ta, others;
int pf,it;
int net_salary,gross_salary,detection;
}e[10];
//main program
void main()
{
int i,n;
struct employee *ptr[10];
clrscr();
printf("enter the number of employee");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr[i]=&e[i]; printf("enter
the name");
scanf("%s",ptr[i]->name);
printf("Enter Basic Salary (RS): ");
scanf("%d",&ptr[i]->basic);
ptr[i]->hra=(ptr[i]->basic*15)/100; ptr[i]->ta=(ptr[i]->basic*20)/100;
ptr[i]->others=(ptr[i]->basic*10)/100;
//calculate DA 12% of Basic Salary
ptr[i]->da = (ptr[i]->basic*30)/100;
//calculate PF 14% of Basic salary
ptr[i]->pf = (ptr[i]->basic*2)/100;
//calculate IT, 15% of Basic salary
ptr[i]->it = (ptr[i]->basic*2)/100;
//calculate net salary
ptr[i]->gross_salary = ptr[i]->basic + ptr[i]->da + ptr[i]->hra + ptr[i]->ta + ptr[i]->others;
ptr[i]->deduction=ptr[i]->pf+ptr[i]->it;
ptr[i]->net_salary=ptr[i]->gross_salary-ptr[i]-> deduction;
}
//printing Net salary
for(i=0;i<n;i++)
{
printf("\n Name is %s",ptr[i]->name);
printf("\t Net Salary is:RS %d\n",ptr[i]->net_salary);
}
getch(); }
EXAMPLE PROGRAM FOR STUDENT DATABASE PROGRAM
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int roll_no, i;
int marks;
}a[10];
void main()
{
int i,n;
struct student *arr_student[10];
clrscr();
printf("enter the number of Student");
scanf("%d",&n);
printf("enter the Student Details one by one");
for(i=0;i<n;i++)
{
arr_student[i]= &a[i];
printf("\nEnter details of student" );
printf("Enter name: ");
scanf("%s", arr_student[i]->name);
printf("Enter roll no: ");
scanf("%d", &arr_student[i]->roll_no);
printf("Enter marks: ");
scanf("%d", &arr_student[i]->marks);
}
for(i=0;i<n;i++)
{
printf("\n");
printf("Name\tRoll no\tMarks\n");
printf("%s\t%d\t%d\n",arr_student[i]->name, arr_student[i]->roll_no, arr_student[i]->marks);
getch();
}
OUTPUT

Example program for structure to function – Student Details


#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
char grade[10];
int roll_no, i;
int marks1,marks2,marks3,percentage;
}s[10];
void internal(struct student s[],int);
void main()
{
int n,i;
clrscr();
printf("\n enter the number of student");
scanf("%d",&n);
printf("\n enter the Details one by one");
for(i=0;i<n;i++)
{
printf("\n Enter name: ");
scanf("%s", s[i].name);
14
printf("\n Enter roll no: ");
scanf("%d", &s[i].roll_no);
printf("\n Enter marks1: ");
scanf("%d", &s[i].marks1);
printf("\n Enter marks2: ");
scanf("%d", &s[i].marks2);
printf("\n Enter marks3: ");
scanf("%d", &s[i].marks3);
printf("\n Enter Attendance percentage:");
scanf("%d", &s[i].percentage);
}
internal(s,n);
getch();
}
void internal(struct student s[],int n)
{ int i;
float inter[10],atten[10];
for(i=0;i<n;i++)
{
if(s[i].percentage>95)
atten[i]=5;
else if(s[i].percentage>90)
atten[i]=4;
else if(s[i].percentage>85)
atten[i]=3;
else if(s[i].percentage>80)
atten[i]=2;
else if(s[i].percentage>75)
atten[i]=1;
else
atten[i]=0;
inter[i]=(((s[i].marks1/100)*5)+((s[i].marks2/100)*5)+((s[i].marks3/100)*5)+atten[i]);
printf("\n The student name is %s,\t internal mark is %f",s[i].name,inter[i]);
}}
OUTPUT
STRUCTURE AND FUNCTION
1. Passing as arguments
● Structure members as arguments
● Structure variable (entire structure) as argument
● Pointers to structure
2. Returning from a function
● Structure variable (entire structure)
● Pointers to structure

STRUCTURE MEMBERS AS ARGUMENTS:


#include<stdio.h>
void printstr(char[],int,int);
int main()
{
struct student
{
char name[50];
int rollno;
int mark;
};
struct student s1={“xyz”,7,92};
printstr(s1.name,s1.rollno,s1.mark);
return 0;
}
void printstr(char name[],int rollno,int mark)
{
printf(“Name=%s”,name);
printf(“Rollno=%d”,rollno);
printf(“Mark=%d”,mark);
}
STRUCTURE VARIABLE AS ARGUMENTS:

#include<stdio.h>
struct student
{
char name[50];
int rollno;
int mark;
};
void printstr(char[],int,int);
int main()
{
struct student s1={“xyz”,7,92};
printstr(s1);
return 0;
}
void printstr(struct student s)
{
printf(“Name=%s”,s.name);
printf(“Rollno=%d”,s.rollno);
printf(“Mark=%d”,s.mark);
}
POINTER TO STRUCTURE AS ARGUMENTS:

#include<stdio.h>
struct student
{
char name[50];
int rollno;
int mark;
};
void printstr(struct student *);
int main()
{
struct student s1={“xyz”,7,92};
struct student *sp;
sp=&s1;
printstr(sp);
return 0;
}
void printstr(struct student *p)
{
printf(“Name=%s”,p->name); //p->name ==(*p).name
printf(“Rollno=%d”,p->.rollno);
printf(“Mark=%d”,p>mark);
}
RETURNING STRUCTURE VARIABLE FROM FUNCTION:
#include<stdio.h>
struct student createstr(char[],int,int);
int main()
{
struct student s;
s=createstr(“xyz”,7,92);
printf(“Name=%s”,s.name);
printf(“Rollno=%d”,s.rollno);
printf(“Mark=%d”,s.mark);
}
struct student createstr(char name[],int rollno,int mark)
{
struct student s1;
strcpy(s1.name,name);
s1.rollno=rollno;
s1.mark=mark;
return s1;
}
RETURNING POINTER FROM A STRUCTURE:
#include<stdio.h>
struct student *createstr(char[],int,int);
int main()
{
struct student *p;
p=createstr(“xyz”,7,92);
printf(“Name=%s”,p->name); //p->name ==(*p).name
printf(“Rollno=%d”,p->.rollno);
printf(“Mark=%d”,p>mark);
}
struct student *createstr(char name[],int rollno,int mark)
{
static struct student s1; //without static it will print nothing
strcpy(s1.name,name);
s1.rollno=rollno;
s1.mark=mark;
return &s1;
}

STRUCTURE WITHIN A STRUCTURE (OR) NESTED STRUCTURE


Structure written inside another structure is called as nesting of two structures.
Nested Structures are allowed in C Programming Language.
We can write one Structure inside another structure as member of another structure.

Way 1 : Declare two separate structures


struct date
{
int date;
int month;
int year;
};
struct Employee
{
char
ename[20];
int idno;
float salary;
struct date
doj;
}emp1;

Accessing Nested Elements :


Structure members are accessed using dot operator.
‘date‘ structure is nested within Employee Structure.
Members of the ‘date‘ can be accessed using ’employee’
emp1 & doj are two structure names (Variables)
Explanation Of Nested Structure :
Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
Way 2 : Declare Embedded structures
struct Employee
{
char
ename[20];
int idno;
float
salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp1;

Accessing Nested Members :


Accessing Month Field : emp1.doj.month
Accessing day Field : emp1.doj.day
Accessing year Field : emp1.doj.year
//Program:
#include
<stdio.h>
struct Employee
{
char
ename[20];
int idno;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
void main()
{
printf("\nEmployee Name : %s",emp.ename);
printf("\nEmployee IDNo : %d",emp.idno);
printf("\nEmployee Salary : %f",emp.salary);
printf("\nEmployee DOJ : %d/%d/%d", emp.doj.date,emp.doj.month,emp.doj.year);
}
Output
Employee Name : Pritesh
Employee IDNo : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
//Lab program:To print the given employee personal details using nested structure
#include<stdio.h>
#include<conio.h>
struct dob
{
int dd;
int mm;
int yy;
}dt;

struct address
{
char st[20];
char city[20];
long int pin;
}add;

struct employee
{
int empid;
char name[20];
struct dob dt;
char pan[10];
long int phone;
struct address add;
char dept[10];
int exp;
}emp;
void main()
{
clrscr();
printf("Enter the Emplyee details:\n");
printf("\nEnter name and emplyid:");
scanf("%s%d",emp.name,&emp.empid);
printf("\nEnter Emplyee's date of
birth:");
scanf("%d%d%d",&emp.dt.dd,&emp.dt.mm,&emp.dt.yy);
printf("\nEnter pan number and phone number:");
scanf("%s%ld",emp.pan,&emp.phone);
printf("Enter Emplyee's address details");
printf("\nEnter state, city and pin number:");
scanf("%s%s%ld",emp.add.st,emp.add.city,&emp.add.pin);
printf("\nEnter department and year of experience detail:");
scanf("%s%d",emp.dept,&emp.exp);
printf("\n");
printf("The Employee details are:\n");
printf("\nEmpluee Name:\t%s",emp.name);
printf("\nEmployee Id:\t%d",emp.empid);
printf("\nEmpluee DOB:\t%d\%d\%d",emp.dt.dd,emp.dt.mm,emp.dt.yy);
printf("\nEmployee Pan no:\t%s",emp.pan);
printf("\nEmpluee Phone number:\t%ld",emp.phone);
printf("\nEmployee Address:\t%s\t%s\t%ld",emp.add.st,emp.add.city,emp.add.pin);
printf("\nEmployee Department:\t%s",emp.dept);
printf("\nEmpluee Year of Experience:\t%d",emp.exp);
getch();
}
OUTPUT
Enter name and emplyid:abi
1
Enter Emplyee's date of birth:11 05 88
Enter pan number and phone
number:123456789 04422423567
Enter Emplyee's address details
Enter state, city and pin
number:tamilnadu chennai
600042
Enter department and year of experience
detail:cse 08
The Employee details are:
Empluee Name:
abi Employee
Id:1
Empluee DOB: 11588
Employee Pan no:
123456789
Empluee Phone number: 2147483647
Employee Address: tamilnadu chennai
600042 Employee Department: cse
Empluee Year of Experience: 8

Difference between structures and arrays


Array Structure
Single name that contains a collection of Single name that contains a collection of data
data items of same data type. items of different data types.
An array is derived data type Structure is a user defined data type
Individual entries in a array are called Individual entries in a structure are called
elements. members.
Array elements are accessed by their Structure members are accessed by their
position or subscript object as ‘.’ operator
No Keyword Keyword: struct
Elements of an array are stored in Members of a structure are not stored in
sequence of memory locations. sequence of memory locations.

DYNAMIC MEMORY ALLOCATION


The process of allocating memory during program execution is called dynamic memory allocation.
C language offers 4 dynamic memory allocation functions. They are,
1. malloc()-simple memory allocation without initialization
2. calloc()- Used when you need to allocate and initialize memory to zero.
3. realloc()-resize previously allocated memory bloack
4. free()
Function Syntax

malloc () malloc (number *sizeof(int));

calloc () calloc (number, sizeof(int));

realloc () realloc (pointer_name, number * sizeof(int));

free () free (pointer_name);


1. malloc() FUNCTION IN C:
● malloc () function is used to allocate space in memory during the execution of the program.
● malloc () does not initialize the memory allocated during execution. It carries garbage value.
● malloc () function returns null pointer if it couldn’t able to allocate requested amount of
memory.
EXAMPLE PROGRAM FOR malloc() FUNCTION IN C:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"Hello world");
}
printf("Dynamically allocated memory content : " \"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT
Dynamically allocated memory content : Hello world

2. calloc() FUNCTION IN C:
calloc () function is also like malloc () function. But calloc () initializes the allocated
memory to zero. But, malloc() doesn’t.
EXAMPLE PROGRAM FOR calloc() FUNCTION

#include <stdio.h>
#include <stdlib.h>

int main () {
int i, n;
int *a;

printf("Number of elements to be entered:");


scanf("%d",&n);

a = (int*)calloc(n, sizeof(int));
printf("Enter %d numbers:\n",n);
for( i=0 ; i < n ; i++ ) {
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");

for( i=0 ; i < n ; i++ ) {


printf("%d ",a[i]);
}
free( a );
return(0);
}
OUTPUT
3. realloc() FUNCTION IN C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size.
If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full
size of reallocation, then copies the existing data to new block and then frees the old block.

4. free() FUNCTION IN C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the
memory to the system.

EXAMPLE PROGRAM FOR REALLOC() AND FREE() FUNCTIONS IN C:

#include<stdio.h>
void main()
{
char *p;

p=(char*)malloc(6);
strcpy(p,"MADRAS");
printf("memory contains %s",p);
p=(char*)realloc(p,7);
strcpy(p,"CHENNAI");
printf("memory now contains %s",p);
free(p);
}
OUTPUT

Singly Linked List in C


● Singly Linked List in C is one of the simplest linear data structures, that we use for storing our data
in an easy and efficient way. Linked List in C comprises nodes like structures, which can further be
divided into 2 parts in the case of a singly linked list. These two parts are-:
● Node – for storing the data.
● Pointer – for storing the address of the next node.
● In a Singly linked list there is only one pointer type variable, that contains the address of the next
node.
● Singly linked list can be defined as the collection of ordered set of elements. The number of
elements may vary according to need of the program. A node in the singly linked list consist of two
parts: data part and link part. Data part of the node stores actual information that is to be represented
by the node while the link part of the node stores the address of its immediate successor.

Linked List can be defined as collection of objects called nodes that are randomly stored in the memory.
A node contains two fields i.e. data stored at that particular address and the pointer which contains the
address of the next node in the memory.
The last node of the list contains pointer to the null.

Uses of Linked List


● The list is not required to be contiguously present in the memory.
● The node can reside any where in the memory and linked together to make a list.
● This achieves optimized utilization of space.
● List size is limited to the memory size and doesn't need to be declared in advance.
● Empty node can not be present in the linked list.
● We can store values of primitive types or objects in the singly linked list.
Why use linked list over array?
Till now, we were using array data structure to organize the group of elements that are to be stored
individually in the memory. However, Array has several advantages and disadvantages which must be
known in order to decide the data structure which will be used throughout the program.

Array contains following limitations:


● The size of array must be known in advance before using it in the program.
● Increasing size of the array is a time taking process. It is almost impossible to expand the size of the
array at run time.
● All the elements in the array need to be contiguously stored in the memory. Inserting any element in
the array needs shifting of all its predecessors.
Linked list is the data structure which can overcome all the limitations of an array. Using linked list is
useful because,
It allocates the memory dynamically. All the nodes of linked list are non-contiguously stored in the
memory and linked together with the help of pointers.
Sizing is no longer a problem since we do not need to define its size at the time of declaration. List
grows as per the program's demand and limited to the available memory space.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;

void beginsert ();


void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();

void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random location\n4.Delete from
Beginning\n 5.Delete from last\n6.Delete node after specified location\n7.Search for an
element\n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;

default:
printf("Please enter valid choice..");
}}}

void beginsert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}

else
{
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}

}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;

head = ptr;
printf("\nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted"); }}}

void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}

ptr ->next = temp ->next;


temp ->next = ptr;
printf("\nNode inserted");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{

ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}

else
{
ptr = head;
while(ptr->next != NULL)
{

ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)

{
ptr1 = ptr;
ptr = ptr->next;

if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}

else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}

if(flag==1)
{
printf("Item not found\n");
}
}

void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values . . . . .\n");
while (ptr!=NULL)
{

printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
Output:

*********Main Menu*********

Choose one option from the following list ...

===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit

Enter your choice?


1
Enter value
1
Node inserted
Enter your choice?
2
Enter value?
2
Node inserted
Enter your choice?
3
Enter element value1
Enter the location after which you want to insert 1
Node inserted
Enter your choice?
8
printing values . . . . .
1
2
1
Enter your choice?
4
Node deleted from the begining ...
Enter your choice?
5
Deleted Node from the last ...
Enter your choice?
6
Enter the location of the node after which you want to perform deletion
1
Deleted node 2
Enter your choice?
8
printing values . . . . .
1
1

typedef:
● typedef is a keyword used in C language to assign alternative names to existing datatypes.
● Its mostly used with user defined datatypes, when names of the datatypes become slightly
complicated to use in programs. Following is the general syntax for using typedef,

typedef <existing_name> <alias_name>


Lets take an example and see how typedef actually works.

typedef unsigned long ulong;


The above statement define a term ulong for an unsigned long datatype. Now this ulong identifier can
be used to define unsigned long type variables.
ulong i, j;

Application of typedef
Typedef can be used to give a name to user defined data type as well. Lets see its use with structures.

typedef struct
{
type member1;
type member2;
type member3;
} type_name;
Here type_name represents the stucture definition associated with it. Now this type_name can be used to
declare a variable of this stucture type.

type_name t1, t2;

Structure definition using typedef


Let's take a simple code example to understand how we can define a structure in C using typedef
keyword.

#include<stdio.h>
#include<string.h>

typedef struct employee


{
char name[50];
int salary;
}emp;

void main( )
{
emp e1;
printf("\nEnter Employee record:\n");
printf("\nEmployee name:\t");
scanf("%s", e1.name);
printf("\nEnter Employee salary: \t");
scanf("%d", &e1.salary);
printf("\nstudent name is %s", e1.name);
printf("\nroll is %d", e1.salary);
}

typedef and Pointers


typedef can be used to give an alias name to pointers also. Here we have a case in which use of typedef is
beneficial during pointer declaration.

In Pointers * binds to the right and not on the left.

int* x, y;
By this declaration statement, we are actually declaring x as a pointer of type int, whereas y will be declared
as a plain int variable.

typedef int* IntPtr;


IntPtr x, y, z;
But if we use typedef like we have used in the example above, we can declare any number of pointers in a
single statement.

SELF REFERENTIAL STRUCTURE IN C


A self referential data structure is essentially a structure definition which includes at least one member
that is a pointer to the structure of its own kind. A chain of such structures can thus be expressed as
follows.

struct name {

member 1;
member 2;
...
struct name *pointer;

};

The above illustrated structure prototype describes one node that comprises of two logical segments. One
of them stores data/information and the other one is a pointer indicating where the next component can
be found. .Several such inter-connected nodes create a chain of structures.

The following figure depicts the composition of such a node. The figure is a simplified illustration of
nodes that collectively form a chain of structures or linked list.

Such self-referential structures are very useful in applications that involve linked data structures,
such as lists and trees. Unlike a static data structure such as array where the number of elements that
can be inserted in the array is limited by the size of the array, a self-referential structure can
dynamically be expanded or contracted. Operations like insertion or deletion of nodes in a self-
referential structure involve simple and straight forward alteration of pointers.

EXAMPLE PROGRAM
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
void main() //Create function
{
char ch;
clrscr();
struct node *current,*new_node;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to create : ");
scanf("%d",&new_node->data);
new_node-next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else{
current->next=new_node;
current=new_node;}

printf("\nDo you want to creat another: ");


ch=getche();
}while(ch!='n'
);
current=start;
printf("\n the linked list is");
do
{
printf("%d ->",current->data);
current=current->next;
}while(current!=NULL);
printf(" NULL");
getch();
}

OUTPUT
Union in C
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 −

Memory size occupied by data : 20

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

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 −

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

FILES
● A file represents a sequence of bytes on the disk where a group of related data is stored.
● File is created for permanent storage of data. It is a readymade structure.
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.
● 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 few commands in C.
● You can easily move your data from one computer to another without any changes.

Basics of File Handling in C


File handing in C is the process in which we create, open, read, write, and close
operations on a file. C language provides different functions such as fopen(), fwrite(), fread(),
fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our
program.
Why do we need File Handling in C?
So far the operations using the C program are done on a prompt/terminal which is
not stored anywhere. The output is deleted when the program is closed. But in the software
industry, most programs are written to store the information fetched from the program. The use
of file handling is exactly what the situation calls for.

In order to understand why file handling is important, let us look at a few features of using
files:
Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and
anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the computer
system. The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File handling allows
you to easily access a part of a file using few instructions which saves a lot of time and reduces
the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.

Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
Text Files
Binary Files

1. Text Files
● A text file contains data in the form of ASCII characters and is generally used to store
a stream of characters.
● Each line in a text file ends with a new line character (‘\n’).
● It can be read or written by any text editor.
● They are generally stored with .txt file extension.
● Text files can also be used to store the source code.
2. Binary Files
● A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.
They contain data that is stored in a similar manner to how it is stored in the main
memory.
● The binary files can be created only from within a program and their contents can only
be read by a program.
● More secure as they are not easily readable.
● They are generally stored with .bin file extension.

C File Operations
C file operations refer to the different possible operations that we can perform on a
file in C such as:
Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
Opening an existing file – fopen()
Reading from file – fscanf() or fgets()
Writing to a file – fprintf() or fputs()
Moving to a specific location in a file – fseek(), rewind()
Closing a file – fclose()

Functions for C File Operations


File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling
to perform all file operations such as read, write, close, etc. We use the FILE macro to declare
the file pointer variable. The FILE macro is defined inside <stdio.h> header file.
Syntax of File Pointer
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.

Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise,
full path.
access_mode: Specifies for what operation the file is being opened.

Return Value
If the file is opened successfully, returns a file pointer to it.
If the file is not opened, then returns NULL.

File opening modes in C


File opening modes or access modes specify the allowed operations on the file to be opened.
They are passed as an argument to the fopen() function. Some of the commonly used file access
modes are listed below:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
r a pointer that points to the first character in it. If the file cannot be opened fopen( ) returns
NULL.

rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.

Open for reading in text mode. If the file exists, its contents are overwritten. If the file
w
doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
Opening
Modes Description

Open for writing in binary mode. If the file exists, its contents are overwritten. If the file
wb
does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a a pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the file. If the file does not
ab
exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer
r+
that points to the first character in it. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file does not exist, fopen( )
rb+
returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new
w+
file is created. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file exists, its contents are
wb+
overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up
a+ a pointer that points to the last character in it. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open the file.

Open for both reading and appending in binary mode. If the file does not exist, it will be
ab+
created.
As given above, if you want to perform operations on a binary file, then you have to append
‘b’ at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to
use “a+b”.
Example of Opening a File

// C Program to illustrate file opening


#include <stdio.h>
#include <stdlib.h>

int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;

// opening the file in read mode


fptr = fopen("filename.txt", "r");

// checking if the file is opened successfully


if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}
return 0;
}

Output
The file is not opened. The program will now exit.
The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist already.
For that, we have to use the modes that allow the creation of a file if not found such as w, w+,
wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File

// C Program to create a file


#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}

Output
The file is created Successfully.

Reading From a File


The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:

Function Description

fscanf() Use formatted string and variable arguments list to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.

Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.

Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible arguments list to
fprintf()
print output to the file.

fputs() Prints the whole line in the file and a newline at the end.

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Writing File : fprintf() function


The fprintf() function is used to write set of characters into file. It sends formatted output to a
stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:
#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
}
Reading File : fscanf() function
The fscanf() function is used to read set of characters from file. It reads a word from the file
and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello file by fprintf...
C File Example: Storing employee information
Let's see a file handling example to store employee information as entered by user from
console. We are going to store id, name and salary of the employee.

#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
Now open file from current directory. For windows operating system, go to TC\bin directory,
you will see emp.txt file. It will have following information.

emp.txt
Id= 1
Name= sonoo
Salary= 120000

C fputc() and fgetc()


Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a
stream.
Syntax:
int fputc(int c, FILE *stream)

Example:

#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
}

file1.txt
a
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.
Syntax:
int fgetc(FILE *stream)
Example:
#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();
}
myfile.txt
this is simple text message

C fputs() and fgets()


The fputs() and fgets() in C programming are used to write and read string from stream. Let's
see examples of writing and reading file using fgets() and fgets() functions.
Writing File : fputs() function
The fputs() function writes a line of characters into file. It outputs string to a stream.
Syntax:
int fputs(const char *s, FILE *stream)
Example:
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
myfile2.txt
hello c programming
Reading File : fgets() function
The fgets() function reads a line of characters from file. It gets string from a stream.
Syntax:
char* fgets(char *s, int n, FILE *stream)
Example:
#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();
}
Output:
hello c programming

Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);

---------- Some file Operations -------


fclose(fptr);

C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data
into file at desired location.
Syntax:
int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.

Example:
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fputs("This is javatpoint", fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
myfile.txt
This is sonoo jaiswal
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have
to use stream many times.
Syntax:
void rewind(FILE *stream)
Example:
File: file.txt
this is a simple text
File: rewind.c
#include<stdio.h>
#include<conio.h>
void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}

rewind(fp);//moves the file pointer at beginning of the file


while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
getch();
}
Output:
this is a simple textthis is a simple text
As you can see, rewind() function moves the file pointer at beginning of the file that is why
"this is simple text" is printed 2 times. If you don't call rewind() function, "this is simple text"
will be printed only once.
C ftell() function
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int n;
FILE *fp;
clrscr();
fp=fopen("demo.txt","r");
if(fp==NULL)
{
printf("error");
exit(1);
}
n=ftell(fp);
printf("position=%d",n); //0
fseek(fp,4,SEEK_SET);
n=ftell(fp);
printf("Position=%d",n); //4
fseek(fp,3,SEEK_CUR);
n=ftell(fp);
printf("Position=%d",n); //7
fclose(fp);
getch();
}

Examples of File Handing in C


Example 1: Program to Create a File, Write in it, And Close the File
// C program to Open a File,
// Write in it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
// Declare the file pointer
FILE* filePointer;
// Get the data to be written in file
char dataToBeWritten[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {
printf("The file is now opened.\n");
// Write the dataToBeWritten into the file
if (strlen(dataToBeWritten) > 0) {
// writing in the file using fputs()
fputs(dataToBeWritten, filePointer);
fputs("\n", filePointer);
}
// Closing the file using fclose()
fclose(filePointer);
printf("Data successfully written in file "
"GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}

Output
The file is now opened.
Data successfully written in file GfgTest.c
The file is now closed.
This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.

Example 2: Program to Open a File, Read from it, And Close the File

// C program to Open a File,


// Read from it, And Close the File
#include <stdio.h>
#include <string.h>
int main()
{
// Declare the file pointer
FILE* filePointer;
// Declare the variable for the data to be read from
// file
char dataToBeRead[50];
// Open the existing file GfgTest.c using fopen()
// in read mode using "r" attribute
filePointer = fopen("GfgTest.c", "r");
// Check if this filePointer is null
// which maybe if the file does not exist
if (filePointer == NULL) {
printf("GfgTest.c file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the dataToBeRead from the file
// using fgets() method
while (fgets(dataToBeRead, 50, filePointer)!= NULL) {
// Print the dataToBeRead
printf("%s", dataToBeRead);
}
// Closing the file using fclose()
fclose(filePointer);
printf(
"Data successfully read from file GfgTest.c\n");
printf("The file is now closed.");
}
return 0;
}

Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.

Read and Write in a Binary File


Till now, we have only discussed text file operations. The operations on a binary file are similar
to text file operations with little difference.
Opening a Binary File
To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the
fopen() function. We also use the .bin file extension in the binary filename.
Example
fptr = fopen("filename.bin", "rb");
Write to a Binary File
We use fwrite() function to write data to a binary file. The data is written to the binary file in
the from of bits (0’s and 1’s).
Syntax of fwrite()
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters:
ptr: pointer to the block of memory to be written.
size: size of each element to be written (in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the output file stream.
Return Value:
Number of objects written.
Example: Program to write to a Binary file using fwrite()

// C program to write to a Binary file using fwrite()


#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
// Structure variable declared here.
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("C:\\program.bin", "wb")) == NULL) {
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
int flag = 0;
// else it will return a pointer to the file.
for (n = 1; n < 5; ++n) {
num.n1 = n;
num.n2 = 5 * n;
num.n3 = 5 * n + 1;
flag = fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
// checking if the data is written
if (!flag) {
printf("Write Operation Failure");
}
else {
printf("Write Operation Successful");
}

fclose(fptr);

return 0;
}

Output
Write Operation Successful

Reading from Binary File


The fread() function can be used to read data from a binary file in C. The data is read from the
file in the same form as it is stored i.e. binary form.
Syntax of fread()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *file_pointer);
Parameters:
ptr: pointer to the block of memory to read.
size: the size of each element to read(in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the input file stream.
Return Value:
Number of objects written.
Example: Program to Read from a binary file using fread()

// C Program to Read from a binary file using fread()


#include <stdio.h>
#include <stdlib.h>
struct threeNum {
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE* fptr;
if ((fptr = fopen("C:\\program.bin", "rb")) == NULL) {
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
// else it will return a pointer to the file.
for (n = 1; n < 5; ++n) {
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2,num.n3);
}
fclose(fptr);

return 0;
}

Output
n1: 1 n2: 5 n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21
More Functions for C File Operations
The following table lists some more functions that can be used to perform file operations or
assist in performing them.

Functions Description

fopen() It is used to create a file or to open a file.

fclose() It is used to close a file.

fgets() It is used to read a file.

fprintf() It is used to write blocks of data into a file.

fscanf() It is used to read blocks of data from a file.

getc() It is used to read a single character to a file.

putc() It is used to write a single character to a file.

fseek() It is used to set the position of a file pointer to a mentioned location.

ftell() It is used to return the current position of a file pointer.

rewind() It is used to set the file pointer to the beginning of a file.


Functions Description

putw() It is used to write an integer to a file.

getw() It is used to read an integer from a file.

Sequential and Random Access File Handling in C


In computer programming, the two main types of file handling are:

• Sequential
• Random access.
Sequential files are generally used in cases where the program processes the data in a sequential
fashion – i.e. counting words in a text file – although in some cases, random access can be
feigned by moving backwards and forwards over a sequential file.

True random access file handling, however, only accesses the file at the point at which the data
should be read or written, rather than having to process it sequentially. A hybrid approach is
also possible whereby a part of the file is used for sequential access to locate something in the
random access portion of the file, in much the same way that a File Allocation Table (FAT)
works.

Example: Finding average of numbers stored in sequential access file


#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int num[10],avg,sum=0,i,n;
fp=fopen("num.txt","w");
printf("\n Enter the total numbers\n\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Num:");
scanf("%d",&num[i]);
fwrite(&i,sizeof(int),1,fp);
}
fclose(fp);
fp=fopen("num.txt","r");
for(i=0;i<n;i++)
{

fread(&i,sizeof(int),1,fp);
sum=num[i]+sum;
}
avg=sum/n;
printf("\n the average of numbers is is %d", avg);
fclose(fp);
getch();
}

Example For sequential access:


Write A Program To Count The Number Of Account Holders Whose Balance Is Less
Than The Minimum Balance
Using Sequential Access File. Program
#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust[10];
void main()
{
FILE *fp; int i,n;
int min=5000;
clrscr();
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
printf("enter total number of account information");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Name:");
scanf("%s",cust[i].name);
printf("Acct Num:");
scanf("%d",&cust[i].acct_num);
printf("Balance:");
scanf("%d",&cust[i].acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
}
fclose(fp);
fp=fopen("accounts.txt","r");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
else
{
printf("\n File opened for reading: accounts.txt\n\n");
}
for(i=0;i<n;i++)
{
fread(&cust,sizeof(struct customer),1,fp);
if(cust[i].acct_balance<=min)
{
printf("\nName=%10s AcctNum=%8d Balance=%8d\n",
cust[i].name,cust[i].acct_num,cust[i].acct_balance);
}}
getch();
fclose(fp);
}
OUTPUT:
Enter accounts information
Enter total number of account information 2 Name: Neha
Acct Num : 1 Balance: 10000 Name : Atul Acct Num: 2
Balance: 4500
File opened for reading : accounts.txt
Name= Atul Acct Num=2 Balance=4500.00
Random Access To File
There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer It is the pointer which points to the file.
displacement It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached with
L because this is a long integer.

Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
The origin parameter can be one of three values:
• SEEK_SET – from the start;
• SEEK_CUR – from the current position;
• SEEK_END – from the end of the file. So, the equivalent of rewind() would be:
fseek( f, 0, SEEK_SET);
Example:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.
2) fseek( p,5L,1)
1 means current position of the pointer position.From this statement pointer position is skipped
5 bytes forward from the current position.
3) fseek(p,-5L,1)

ftell()
This function returns the value of the current pointer position in the file.The value is count from
the beginning of the file.
Syntax: ftell(fptr); Where fptr is a file pointer.
rewind() This function is used to move the file pointer to the beginning of the given
file.
Syntax: rewind( fptr); Where fptr is a file pointer.
Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate file functions(Here we
need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}}
fclose(fp); getch();
}
OUTPUT: It depends on the content in the file.

RANDOM ACCESS EXAMPLE PROGRAM


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("test.txt", "r");
fseek(fp, 3, SEEK_SET);
ch=fgetc(fp);
printf("%c",ch);
fseek(fp, 3, SEEK_CUR);
ch=fgetc(fp);
printf("%c",ch);
fseek(fp, -3, SEEK_END);
ch=fgetc(fp);
printf("%c",ch);
getch();
}
Example: Transaction processing using random access files
#include<stdio.h>
#include<stdlib.h>
struct customer
{
char name[20];
int acct_num;
int acct_balance;
}cust;
void main()
{
FILE *fp;
int choice=1,n;
fp=fopen("accounts.txt","w");
if(fp==NULL)
{
printf("\n Error opening accounts.txt\n\n");
exit(1);
}
printf("\n Enter accounts information\n\n");
do{
printf("\n Name:");
scanf("%s",cust.name);
printf("Acct Num:");
scanf("%d",&cust.acct_num);
printf("Balance:");
scanf("%d",&cust.acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
printf("Press 1 to enter one more entry:\n");
scanf("%d",&choice);
}while(choice==1);
fclose(fp);
fp=fopen("accounts.txt","r");
printf("\n File opened for reading: accounts.txt\n\n");
printf("\n Enter which customer detail has to be printed");
scanf("%d",&n);
fseek(fp,n*sizeof(struct customer),0);
fread(&cust,sizeof(struct customer),1,fp);
printf("\nName=%10s AcctNum=%8d Balance=%d\n",
cust.name,cust.acct_num,cust.acct_balance);
getch();
}

Basic C- Files Examples:-


1. Write a C program to read name and marks of n number of students from user and store
them in a file.
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","w"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;}
2. Write a C program to read name and marks of n number of students from user and store
them in a file. If the file previously exits, add the information of n students.
#include<stdio.h>
#include<conio.h>
int main()
{
char name[50];
int marks,i,n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL)
{
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
getch();
return 0;
}
3.Write a C program to write all the members of an array of structures to a file using fwrite().
Read the array from the file and display on the screen.
#include<stdio.h>
#include<conio.h>
struct s
{
char name[50];
int height;
};
int main()
{
struct s a[5],b[5];
FILE *fptr;
int i; clrscr();
fptr=fopen("file.txt","wb");
for(i=0;i<5;++i)
{
fflush(stdin); printf("Enter name: ");
gets(a[i].name); printf("Enter height: ");
scanf("%d",&a[i].height);
}
fwrite(a,sizeof(a),1,fptr);
fclose(fptr);
fptr=fopen("file.txt","rb");
fread(b,sizeof(b),1,fptr);
for(i=0;i<5;++i)
{
printf("Name: %s\nHeight: %d",b[i].name,b[i].height);
}
fclose(fptr);
getch();}
Command line arguments
It is possible to pass some values from the command line to your C programs when
they are executed. These values are called command line arguments and many times they are
important for your program especially when you want to control your program from outside
instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc
refers to the number of arguments passed, and argv[] is a pointer array which points to each
argument passed to the program. Following is a simple example which checks if there is any
argument supplied from the command line and take action accordingly −

#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to
the first command line argument supplied, and *argv[n] is the last argument. If no arguments
are supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes "" or single
quotes ''.

Let us re-write above example once again where we will print program name and we also pass
a command line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but
inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
Program name ./a.out
The argument supplied is testing1 testing2
Example:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \ "not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0;
}

OUTPUT:
Program name : test.c 1st arg : this
2nd arg : is
3rd arg : a
4th arg : program 5th arg : (null)

Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
OUTPUT:
One argument expected C:\TURBOC3>BIN\cd.. C:\TURBOC3>cd SOURCE
C:\TURBOc3\SOURCE>cmd.exe testing The argument supplied is testing
C:\TURBOc3\SOURCE>cmd.exe testing testing1 Too many arguments supplied

You might also like