PSPC Unit-6
PSPC Unit-6
6.0 Introduction
A simple variable can store one value at a time. An array can store a number of variables
of the same type. For example, marks obtained by a student in five subjects can be stored in an
array marks[5]. marks[0], marks[1], etc, will store student information like the marks obtained in
various subjects. Suppose we want to store student information in array name, htno, address,
marks obtained. We cannot store this information in an array because name, htno, address are of
character type and marks obtained is of integer type. So arrays are used to store homogeneous
data. To store heterogeneous data elements in a single group, C language provides a facility
called the structure.
struct structure_name
{
data_type member_variable1;
data_type member_variable2;
……
data_type member_variableN;
};
The variables declared inside the structure are known as members of the structure.
For Example
Datatype
Struct student
{
char name[20];
char ht_no[10];
char gender;
float marks;
long int phone_no;
};
Points remember
The members of the structure may be any of the common data type, pointers, arrays or
even the other structures.
Member names with in a structure must be different.
Structure definition starts with the open brace({) and ends with closing brace(}) followed
by a semicolon.
struct date
{
int dat;
int month;
int year;
}dob, doj;
Here date is the structure tag, while dob and doj are variables type date.
struct date
{
int dat;
int month;
int year;
};
There is a one-to-one correspondence between the members and their initializing values.
C does not allow the initialization of individual structure members within the
structure definition template.
struct date
{
int dat;
int month;
Output
Student Name: XYZ
Roll No: 581
Gender: M
Marks obtained:79.5
Address: Nuzvid
Syntax:
structure_variable.membername
Here, structure_variable refers to the name of a structure type variable and member refers
to the name of a member within the structure.
int main()
{
struct date dob;
printf("Enter your birthday details\n");
printf("Enter the day:");
scanf("%d",&dob.day);
printf("Enter the month:");
scanf("%d",&dob.month);
printf("Enter the year:");
scanf("%d",&dob.year);
printf("Your date of birth is:");
printf("%d-%d-%d\n",dob.day,dob.month,dob.year); return
0;
}
Output
Enter your birthday details
Enter the day:12
Enter the month:7
Enter the year:1998
Your date of birth is: 12-7-1998
} printf("%.1f",st.cgpa);
Output:- }
ERROR Output:-
9.9
Note:-It will give error because here structure
is local.so we can access it only in main
function.
Output
Enter student details
Enter student name: Ramesh
Enter roll no: 1224
Enter address: vizag
Enter the day:15
Enter the month:8
Enter the year:1991
Student Details
-----------------
Student Name: Ramesh
Roll No: 1224
Date of birth is: 15-8-1991
Address: vizag
Syntax :
OUTPUT:
enter the students roolno: 1224
enter the students name: Ram
enter the students marks: 78.9
enter the students roolno: 1256
enter the students name: Syam
enter the students marks: 45.7
enter the students roolno: 7654
enter the students name: Lava
enter the students marks: 90.9
Details Of students
Roll no=1224
Name=Ram
marks = 78.9
Details Of students
Roll no=Syam
Name=1256
marks = 45.7
Details Of students
Roll no=7654
Name=Lava
marks = 90.9
0 1 2
2000 3000 4000
1000
1000
St
0 1 2
2000 3000 4000
1000
1000
st
passing
structures to
function
Output:- Output:-
24+7=31 24+7=31
#include<stdio.h> #include<stdio.h>
struct prgm typedef struct
{ {
int x; int x;
int y; int y;
}; }student;
void add(struct prgm ); void add(student);
void main() void main()
{ {
struct prgm p={24,7}; student p={24,7};
add(p); add(p);
} }
void add(struct prgm pr) void add(student s)
{ {
printf("%d+%d=%d",pr.x,pr.y, printf("%d+%d=%d",s.x,s.y,s.x+s.y);
pr.x+pr.y); }
}
Output:-
Output:- 24+7=31
24+7=31
Typedef in structures:-
#include<stdio.h> #include<stdio.h>
typedef struct student typedef struct student
{ {
int x; int x;
int y; int y;
}; }a;
void main() void main()
{ {
typedef struct student a; a s={27,3};
a s={27,3}; printf("%d",s.x+s.y);
printf("%d" ,s.x+s.y); }
}
Passing large structures to function using the call by value method is very inefficient.
It is professional to run structure through pointer
It is possible to create a pointer to almost any type in C ,including user defined types
Syntax:-
struct struct_name
{
datatype member_name;
..............;
...............;
}*ptr;
Or
struct struct_name *ptr;
Ex:-
#include<stdio.h>
typedef struct student
{ Output
int sid; enter sid=123
char name[20]; enter name1=Ramesh
float marks; enter marks1=9.8
}; enter sid2=456
void main() enter name2=abc
{
typedef struct student st; enter marks2=9.5
st *ptr1,*ptr2,st1,st2;
ptr1=&st1; Student details=
ptr2=&st2; sid1=123
printf("Enter sid1="); name1=Ramesh
scanf("%d",&ptr1->sid); marks1=9.8
printf("Enter name1=");
scanf("%s",&(ptr1->name));
printf("Enter marks1="); sid2=456
scanf("%f",&(ptr1->marks)); name2=abc
printf("Enter sid2="); marks2=9.5
scanf("%d",&ptr2->sid);
printf("Enter name2=");
scanf("%s",&(ptr2->name));
printf("Enter marks2=");
scanf("%f",&(ptr2->marks));
printf("\nStudent details=\n");
printf("sid=%d\nsname=%s\nmarks=%.1f\n\n",ptr1->sid,ptr1->name,ptr1->marks);
printf("sid=%d\nsname=%s\nmarks=%.1f\n",ptr2->sid,ptr2->name,ptr2->marks); }
Defines a data type, struct node. A structure type struct node has two members-integer member
data and pointer member nextptr. Member nextptr points to a structure of type struct node – a
structure of the same type as one being declared here, hence the term “self-referential structure”.
Member nextptr referred to as a link i.e. nextptr can be used to tie a structure of type struct node
to another structure of the same type. self referential structures can be linked together to form a
usual data structures such as lists etc.
#include<stdio.h>
struct student
{
char name[30];
int age;
char address[20];
struct student *next;
};
int main()
{
struct student st1={"Ramesh",24,"Vizag"};
struct student st2={"Rajesh",21,"Nuzvid "};
struct student st3={"Mahesh",22,"Hyd"};
st1.next = &st2;
st2.next = &st3;
st3.next = NULL;
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st1.name,st1.age,st1.address);
printf("Student 1 stored at %x \n",st1.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st2.name,st2.age,st2.address);
printf("Student 2 stored at %x \n",st2.next);
printf("Student Name:%s\tAge:%d\tAddress:%s\n",st3.name,st3.age,st3.address);
printf("Student 3 stored at %x \n",st3.next); return 0;
}
Output
Student Name:Ramesh Age:24 Address: Vizag
Student 1 stored at 88f0
Student Name:Rajesh Age:21 Address:Nuzvid
Student 2 stored at 8854
Student Name:Mahesh Age:22 Address: Hyd
Student 3 stored at 0
Note:-
If pointer variable is pointing to the structure we are using ->operator to read the structure
members.
Unions
A Union is a user defined data type like structure. The union groups logically related variables
into a single unit.
In structure each member has its own memory location where as the members of union
has the same memory location.
We can assign values to only one member at a time, so assigning value to another
member that time has no meaning.
When a union is declared, compiler allocates memory locations to hold largest data type member
in the union. So, union is used to save memory. Union is useful when it is not necessary to
assign the values to all the members of the union at a time.
Union can be declared as
union
{
member 1;
member 2;
……
……
member N;
};
Following example shows how to declare union and accessing the members of union
#include<stdio.h> Example 2:
union student
{ #include<stdio.h> a, b
char name[30]; Union un
int age;
{ 10 20
};
int main() int a,b;
{ }var; 2046 (2 bytes )
union student st;
clrscr(); int main( )
printf("Enter student name:"); {
scanf("%s",st.name);
var.a=10;
printf("Student Name:%s, age=
%d\n",st.name,st.age); st.age=24; pf(“A=%d \t B=%d”,var.a,var.b);
printf("Student Name:%s, age= var.b=20;
%d\n",st.name,st.age);
getch(); pf(“A=%d \t B=%d”,var.a,var.b);
return 0; }
}
OUTPUT:
Output
Enter student name: Ramesh A=10 B=10
Student Name: Ramesh, age= 26966 A=20 B=20
Student Name: ¶ , age= 24
Following figure illustrates how members of structure and union are stored.
struct student
{
char name[15];
int age;
};
Array of Unions:
#include<stdio.h>
union num
{
int a; OUTPUT:
int b; the a and b values in index 0 is 20 and 20
}; the a and b values in index 1 is 40 and 40
int main() the a and b values in index 0 is 60 and 60
{
int i;
union num arr[3];
arr[0].a=10;
arr[0].b=20;
arr[1].a=30;
arr[1].b=40;
arr[2].a=50;
arr[2].b=60;
for(i=0;i<3;i++)
{
printf("\n the a and b values in index %d is %d and %d ",i,arr[i].a,arr[i].b);
}
return 0;
}
#include<stdio.h>
struct student
{
union st
{
char name[20];
int sid;
}st1;
int marks;
};
int main()
{
struct student st;
char choice;
printf("\n you can enter the NAME or ID:");
else
{
printf("\n enter sid:");
scanf("%d",&st.st1.sid);
printf("\n enter marks:");
scanf("%d",&st.marks);
printf("\ Student Id:%d",st.st1.sid);
printf("\nStudent matrks:%d",st.marks);
}
}
OUTPUT:
you can enter the NAME or ID:
Do you want Ur results by Name Enter (Y): Y
Enter name: Ram
Enter marks: 24
Student Name: Ram
Student Marks: 24
Note: When we are declare the union inside the structure , no need to declare variable for union,
by accessing union members it also possible to access through structure variable.
St.un.member or st.member
Structure.union.member
};
union Student
{
struct a A;
struct b B;
};
int main()
{
union Student s;
char ch;
printf("\n you can enter the NAME or ID:");
printf("\n Do you want Ur results by Enter Name or Roll No (N/R) :");
scanf("%c",&ch);
if(ch=='N'||ch=='n')
{
printf("\n enter Name:");
scanf("%s",s.B.name);
printf("\n enter marks:");
scanf("%d",&s.B.marks);
printf("\ Student Name:%s",s.B.name);
printf("\nStudent matrks:%d",s.B.marks);
}
if(ch=='R'||ch=='r')
{
printf("\n enter RoolNo:");
scanf("%d",&s.A.sid);
printf("\n enter marks:");
scanf("%d",&s.A.marks);
printf("\ Student ID:%d",s.A.sid);
printf("\nStudent matrks:%d",s.A.marks);
}
return 0;
OUTPUT:
you can enter the NAME or ID:
Do you want Ur results by Enter Name or Roll No: (N/R) : N
Enter name: Ram
Enter marks: 24
Student Name: Ram
Student Marks: 24
A file has a beginning and an end; it has a current position, typically defined as on many
bytes from the beginning. You can move the current position to any other point in file. A
new current position can be specified as an offset from the beginning the file.
Types of files:
Binary files :
A binary file is collection of bytes.
In „C‟ both a both a byte and a character are equivalent.
A binary file is also referred to as a character stream, but there are two essential
differences.
Text Stream
It consists of sequence of characters, depending on the compilers.
Each character line in a text stream may be terminated by a newline character.
Text streams are used for textual data, which has a consistent appearance from one
environment to another or from one machine to another.
Binary Stream
It is a series of bytes.
Binary streams are primarily used for non-textual data, which is required to keep exact
contents of the file.
The fopen() function is used to open a file and associates an I/O stream with it. The general
form of fopen() is
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 1
fopen(const char *filename, const char * mode);
This function takes two arguments. The first argument is the name of the file to be opened
while the second argument is the mode in which the file is to be opened.
NOTE: Before opening a file, we have to create a file pointer that is created using FILE
structure is defined in the “stdio.h” header file.
For example
FILE *fp;
if(fp = fopen(“csefile.txt”,”r”)) == NULL)
{
printf(“Error opening a file”);
exit(1);
}
This opens a file named csefile.txt in read mode.
Mode Meaning
R Open a text file for reading only. If the file doesn‟t exist, it returns null.
w+ Opens the existing text file or Creates a text file for read/write
fclose(file pointer);
char ch;
clrscr();
fp=fopen("file1.c","r"); // file opened in read mode
if(fp==NULL)
printf("Unable to open test.txt");
else
{
do
{
ch = getc(fp);
putchar(ch);
}while(ch!=EOF);
fclose(fp);
}
getch();
return 0;
}
Output
Welcome to Files. You opened a file name test.txt
Note: EOF means End of File that denotes the end-of-file.
1. fscanf()
2. fgets()
3. fgetc( )
4. fread()
5. fgetw()
fgets( ) :
The function fgets() stands for file get string.
The function is used to get string from a stream.
Syntax:-
char* fgets(char *str, int size, *stream);
fgetc( ):-
The fgetc( ) function returns next character from streams.
Prototype:- int fgetc(FILE *stream);
fgetc() returns the character read as an int.
fgetc() reads a single character from the current position of a file. After reading the
character, the function increments the associated file pointer to point to the next
character.
If the stream is reached the End Of File, the EOF indicator for the stream for the
steam is set.
Ex:
#include<stdio.h>
main()
{
FILE *fp;
int ch;
fp=fopen(“file.txt”,”r”);
if(fp==NULL)
{
printf(“Unable to open”);
}
while((ch=fgetc(fp))!=EOF)
{
printf(“%c”,ch);
}
}
The function on successful, fread() returns the no. of bytes successfully read. The no.
of objects will be less than num if a read error or end of file is encountered.
If size or num is 0, fread() will return 0.
Note:-
The fread() function does not distinguish between end-of-file and error. The program
must use feof and ferror to determine which of the two occurs.
Ex:
#include<stdio.h>
main()
{
FILE *fp;
char str[20];
fp=fopen(“Letters.txt”,”r+”);
if(fp==NULL)
{
printf(“Unable to open”);
exit(1);
}
fread(str,1,10,fp);
str[10]=’\0’;
printf(“\n The first character of a file %s”,str);
fclose(fp);
}
fgetw( ):-
The fgetw() is used to read an integer from the file stream.
Prototype: int fgetw(fp);
#include<stdio.h>
int main()
{
int num;
FILE *fp;
Fp=fopen(“Num.txt”,”r”);
printf(“The numbers in the file are:”);
num=getw(fp);
while(num!=EOF)
printf(“%d”,num);
return 0;
}
fp = fopen("test.txt", "w");
printf("Enter your Input\n");
while((c =getchar()) != EOF) //writing data to the file
putc(c,fp);
fclose(fp);
(1) fprintf():-
The fprintf() is used to write formatted output to stream. It same as printf( ), but here
first argument is file pointer.
This function write the information to file.
#include<stdio.h>
main()
{
FILE *fp;
int i,n;
char sname[20];
int sid;
fputs():-
The opposite of fgets() is fputs(). The fputs() is used to write a line to a file.
Syntax:-
#include<stdio.h>
main()
{
FILE *fp;
char greeting[100];
fp=fopen(“wishes.txt”,”w”);
if(fp==NULL)
printf(“\n Enter your wishes”);
gets(greeting);
fflush(stdin);
fputs(greeting, fp);
fclose(fp);
}
fputc():-
It is opposite to fgetc() and is used to write a character to the stream.
On successful completion, fputc() will return the value it has written otherwise error,
the function will return EOF.
#include<stdio.h>
main()
{
FILE *fp;
char welcome[100];
int i;
fp=fopen(“Welcome.txt”,”w”);
if(fp==NULL)
printf(“\n Provide welcome message”);
gets(welcome);
for(i=0;i<feedback[i];i++)
fputc(“feedback[i]”, fp);
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 8
fclose(fp);
}
fwrite():-
Prototype: int fwrite(const void *str, size_t, size, size_t count, FILE *stream);
Ex:-
#include<stdio.h>
main()
{
FILE *fp;
size_t count;
char str[]=”GOOD MORNING”;
fp=fopen(“Welcome.txt”,”wb”);
count=fwrite(str, 1, strlen(str), fp);
printf(“\n%d bytes were written to the file”,count);
fclose(fp);
return 0;
}
fputw():-
Syntax :
int fputw(word, fpt);
#include<stdio.h>
main()
{
FILE *fp;
int i, n, val;
fp=fopen(“file1”, “wb”);
if(fp==NULL)
{
printf(“File does not exists”);
exit(1);
}
else
{
printf(“\nEnter the no. of values to be stored:”);
scanf(“%d”,&n);
printf(“\nEnter the values:”);
for(i=1;i<=n;i++)
{
scanf(“%d”,&val);
fputw(val, fr);
}
}}
M.Ramesh, Dept of CSE, IIIT-Nuzvid. Page 9
6.15 RANDOM ACCESS FILES:
We can access the file in any place that’s from beginning , ending and middle of the
file also.
1. fseek( )
2. ftell( )
3. rewind( )
4. fgetpos( )
5. fsetpos( )
(1) fseek():-
Prototype:-
• fseek() is used to set the file position pointer for the given stream.
• It is used to move the file pointer to different position using fseek function.
Syntax:-
Pointer Position:-
This sets the pointer position in the file. Origin values should have one of the
following.
Ex:-
ftell():-
The ftell() function used to know the current position of file pointer.
Syntax:-
Here, file pointer points to the file whose file position indicator has to be determined.
Ex:-
Hello CSE
printf(“%d”, ftell(fp)); --> 9
#include<stdio.h>
main()
{
FILE *fp;
int len;
fp=fopen(“file.txt”,”r”);
fseek(fp, 0, SEEK_END);
len=ftell(fp);
printf(“%d”, len);
fclose(fp);
}
rewind():- rewind() is used to move the file pointer to the beginning of the file.
Syntax:- rewind(fp);
where fp is a file pointer.
fp fp
fgetpos():-
The fgetpos() is used to determine the current position of the file pointer.
Syntax:-
The function returns zero on success, else non-zero value in case of an error.
getpos( ) can be used by two fsetpos() to return to this same position.
fsetpos():-
The fsetpos() is used to move the file position indicator of a stream to the location
indicated by the information obtained in position by making a call to the fgetpos().
Syntax:-
int fsetpos(file *stream, const fpos_t pos);
#include<stdio.h>
main()
{
FILE *fp;
fpos_t position;
fp=fopen(“file.txt”, “w+”);
fgetpos(fp, &position);
fputs(“Hello CSE!”, fp);
fsetpos(fp, &position);
fputs(“This is going to override previous content”, fp);
}
Example:
#include<stdio.h>
int main( )
{
typedef int cse;
cse a=10,b=20,c=30;
printf(“sum:%d”,a+b+c);
}
OUTPUT: sum: 30
int i=0;
typedef int Array[5]; // Array is a new name for integer array with specified size;
Array x={1,2,3,4,5};
printf(“Array elements are:”);
for( i=0;i<5;i++)
{
printf(“%d\n”,x[i]); OUTPUT:
1
} 2
} 3
4
5
In above program int changes to new data type i.e Array , it stores the array elements
with specified size.
When we are declare the variable with Array data type . that variable holds the elements .
Array x; x is a variable it holds the five elements.
Ex: Ex:
Ex:-
#include<stdio.h>
typedef char* string;
char* read(void);
OUTPUT:
void main( )
Enter Name: CSE
{ Welcome CSE
string name;
name=read( );
printf(“Welcome %s”name);
}
string read( )
{
string name;
printf(“Enter Name:”);
gets(name);
return name;
}
The enum keyword basically used to declare and initialize a sequence of integer
constants. Here enumeration name is optional.
Ex:-
Rules:-
An Enumeration list may contain duplicate constant values. Therefore, two different
identifiers may be assigned the same value.
The identifiers in the enumeration list must be different from other identifiers in the same
scope with same visibility including ordinary variable names and identifiers in other
enumeration lists.
Enumeration names follow the normal scoping rules. So, every enumeration must be
different from other enumeration, structures and unions.
Ex:-
#include<stdio.h>
int main()
prinnf(“\n CSE1=%d”,CSE1);
prinnf(“\n CSE2=%d”,CSE2);
prinnf(“\n CSE3=%d”,CSE3);
prinnf(“\n CSE4=%d”,CSE4);
prinnf(“\n CSE5=%d”,CSE5);
return 0;
OUTPUT:
CSE1=2
CSE2=3
CSE3=10
CSE4=11
CSE5=24
enum colors c;
c=black+white
2 + 6 = 8
Two things
To declare c as int
Cast the right handisde of
c=enum colors(black+white);
c=black;
//c=2; // error
c=(enum colors) 2;
enum colors{r,b,b,g,y,p,w};