You are on page 1of 9

MODULE IV: STRUCTURES

INTRODUCTION
• Suppose, you want to store the information about person about his name, citizenship number and salary.
• You can create these information separately but, better approach will be collection of these information under
single name because all these information are related to person.
• For this purpose, structure can be used.

STRUCTURES
• Structure is a collection of elements of different data type.
• The syntax is shown below:

struct structure_name
{
data_type member1;
data_type member2;
data_type member3;
};
• The variables that are used to store the data are called members of the structure.
• We can create the structure for a person as shown below:

struct person
{
char name[50];
int cit_no;
float salary;
};
• This declaration above creates the derived data type struct person.

Structure Variable Declaration


• A structure can be declared using 2 methods:
1) Tagged Structure
• When a structure is defined, it creates a user-defined type but, no storage is allocated. For the above structure of
person, variable can be declared as:

struct person
{
char name[50];
int cit_no;
float salary;
};
Inside main function:
struct person p1, p2;
• Here the above statement declares that the variables p1 and p2 are variables of type struct person.
• Once the structure variable is declared, the compiler allocates memory for the structure variables.
• The size of the memory allocated is the sum of size of individual members.

2) Type Defined Structure


• Another way of creating sturcture variable using the keyword typedef is:

typedef struct person


{ char name[50];
int cit_no;
float salary;
} EMP;
Inside main function: EMP p1 ,p2 ;
• Here the above statement declares that the variables p1 and p2 are variables of type EMP(which is of type as
struct person)..

Structure Variable Initialization


• For ex:
struct person
{ char name[50];
int cit_no;
float salary;
};
struct person p1={"ram", 24, 23000};
Accessing Members of a Structure
• Member operator(.) can be used for accessing members of a structure.
• Any member of a structure can be accessed as:

structure_variable_name.member_name
• By specifying p1.name, we can access the name ram

By specifying p1.salary, we can access the value 23000


• The various values can be accessed and printed as shown below:

printf("%s", p1.name); printf("%f", p1.salary);


• We can read the members of a structure as shown below:

gets(p1.name); or scanf("%s", p1.name); scanf("%f",&p1.salary);.

STRUCTURES WITHIN STRUCTURES


• For ex: struct dob //dob = date of birth

{
int day;
int month;
int year;
};
struct person
{
char name[50];
int cit_no;
float salary;
struct dob d1;
};
float salary;
struct dob d1;
}; Inside main: struct person p1 ,p2 ;
• Suppose you want to access month for p1 structure-variable then, structure-member p1.d1.month is used.

SELF REFERENTIAL STRUCTURES


• A self-referential structure is one in which one or more of its components is a pointer to itself.
• These require dynamic storage management functions (malloc & free) to explicitly obtain and release memory.
typedef struct
{
char data;
struct list *link; //list is a pointer to a list
}list; structure

Consider three structures and values assigned to their respective fields:


list item1,item2,item3;
item1.data='a';
item2.data='b';
item3.data='c';
item1.link=item2.link=item3.link=Null;

• We can attach these structures


together as follows:
item1.link=&item2;
tem2.link=&item3;

In C, structure can be passed to


functions by 2 methods:
1) Passing by value (passing actual
value as argument)
2) Passing by reference (passing
address of an argument)

Passing Structure by Value


• A structure-variable can be passed to
the function as an argument as normal
variable.
• If structure is passed by value, change
made in structure-variable in function-
definition does not reflect in original
structure variable in calling-function.
• Example: Write a C program to create
a structure student, containing name and
roll. Ask user the name and roll of a
student in main function. Pass this
structure to a function and display the
information in that function.

#include<stdio.h>
struct student
{
char name[50];
int roll;
};
void Display(struct student stu)
{
printf("Your Name: %s \n",stu.name);
printf("Your Roll: %d",stu.roll);
}
void main()
{
struct student s1;
printf("Enter student's name: ");
scanf("%s", &s1.name);
printf("Enter roll number: ");
scanf("%d", &s1.roll);
Display(s1); //passing structure variable
s1 as argument
}
Output:
Enter student's name: rama
Enter roll number: 149
Your Name: rama
Your Roll: 149

Passing Structure by Reference


• The address location of structure-
variable is passed to function while
passing it by reference.
• If structure is passed by reference,
change made in structure-variable in
function-definition reflects in original
structure variable in the calling-
function.
• Write a C program to add two
complex numbers entered by user. To
solve this program, make a structure.
Pass two structure variable (containing
distance in real and imaginary part) to
add function by reference and display
the result in main function without
returning it.

#include <stdio.h>
struct comp
{
int real;
float img;
};
void Add(struct comp c1,struct comp
c2, struct comp *c3)
{
// Adding complex numbers c1 and d2
and storing it in c3
c3->real=c1.real+c2.real;
c3->img=c1.img+c2.img;
}
void main()
{
struct comp c1, c2, c3;
printf("First complex number \n");
printf("Enter real part: ");
scanf("%d",&c1.real);
printf("Enter imaginary part: ");
scanf("%f",&c1.img);
printf("Second complex number \n");
printf("Enter real part: ");
scanf("%d",&c2.real);
printf("Enter imaginary part: ");
scanf("%f",&c2.img);
Add(c1, c2, &c3);
//passing structure variables c1 and c2
by value whereas passing
// structure variable c3 by reference
printf("Sum of 2 complex numbers =
%d + i %d",c3.real, c3.img);
}
Output:
First complex number
Enter real part: 3
Enter imaginary part: 4
Second complex number
Enter real part: 2
Enter imaginary part: 5
Sum of 2 complex numbers = 5 + i 9

File Handling in C
Why files are needed?
When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is
time consuming to enter the entire data. But, if file is created, this information can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. In this study material, you will learn to handle
standard I/O (High level file I/O functions) in C. High level file I/O functions can be categorized as:
1. Text file
2. Binary file

File Operations
1. Creating a new file
2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file

Working with file


While working with file, you need to declare a pointer of type file. This declaration is needed for communication
between file and program. FILE *ptr; fopen() and fclose() functions
Opening a file
Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:
ptr=fopen("fileopen","mode")
For Example: SYNTAX:- fopen("E:\\cprogram\program.txt","w");

/* --------------------------------------------------------- */

E:\\cprogram\program.txt is the location to create file.

"w" represents the mode for writing.

/* --------------------------------------------------------- */

Here, the program.txt file is opened for writing mode.


Closing a File
The file should be closed after reading/writing of a file. Closing a file is performed using library function fclose().
SYNTAX:- fclose(ptr); //ptr is the file pointer associated with file to be closed.
The Functions fprintf() and fscanf() functions.
Important is that the functions fprintf() and fscanf() are the file version of printf() and fscanf(). The only difference
while using fprintf() and fscanf() is that, the first argument is a pointer to the structure FILE
Writing to a file
#include <stdio.h>
int main()
{ int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");

if(fptr==NULL)

printf("Error!");
exit(1);
}

printf("Enter n: ");

scanf("%d",&n);

fprintf(fptr,"%d",n);

fclose(fptr);
return 0;

} This program takes the number from user and stores in file. After you compile and run this program, you can see a

text file program.txt created in C drive of your computer. When you open that file, you can see the integer you
entered. Similarly, fscanf() can be used to read data from file.
Reading from file
#include <stdio.h>
int main()
{ int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL)
{ printf("Error! opening file");
exit(1);
/* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
If you have run program above to write in file successfully, you can get the integer back entered in that program using
this program. Other functions like fgetchar(), fputc() etc. can be used in similar way.
Description
The C library function int fputc(int char, FILE *stream) writes a character (an unsigned char) specified by the
argument char to the specified stream and advances the position indicator for the stream.
Declaration
Following is the declaration for fputc() function.
Parameters
char -- This is character to be written. This is passed as its int promotion.

stream -- This is the pointer to a FILE object that identifies the stream where the character is to be written.

Return Value
If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the
error indicator is set.
Example
The following example shows the usage of fputc() function.
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("file.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);

return(0);

} Let us compile and run the above program, this will create a file file.txt in the current directory which will have
following content:
Now let's the content of the above file using the following program:
#include <stdio.h>
int main ()
{
FILE *fp;
int c;
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Binary Files
Depending upon the way file is opened for processing, a file is classified into text file and binary file. If a large amount
of numerical data it to be stored, text mode will be insufficient. In such case binary file is used.
Working of binary files is similar to text files with few differences in opening modes, reading from file and writing to
file.
Opening modes of binary files
Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+. The only difference between opening modes of text
and binary files is that, b is appended to indicate that, it is binary file.

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.
The three main functions are:
rewind() – return the file pointer to the beginning;

fseek() – position the file pointer;

ftell() – return the current offset of the file pointer.

Each of these functions operates on the C file pointer, which is just the offset from the start of the file, and can be
positioned at will. All read/write operations take place at the current position of the file pointer.
The rewind() Function
The rewind() function can be used in sequential or random access C file programming, and simply tells the file system to
position the file pointer at the start of the file. Any error flags will also be cleared, and no value is returned. While
useful, the companion function, fseek(), can also be used to reposition the file pointer at will, including the same
behavior as rewind().
Using fseek() and ftell() to Process Files-Positioning the file pointers
The fseek() function is most useful in random access files where either the record (or block) size is known, or there is an
allocation system that denotes the start and end positions of records in an index portion of the file. The fseek() function
takes three parameters:
FILE * f – the file pointer;

long offset – the position offset;

int origin – the point from which the offset is applied.


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); By a similar token, if the programmer wanted to
append a record to the end of the file, the pointer could be repositioned thus: fseek( f, 0, SEEK_END);

You might also like