unit 5 notes
unit 5 notes
WEEK - 10
1 Structures: Definition, Syntax, Nested Structures
2 Pointers to Structures
3 Unions: Definition, Syntax
------------------
Structures
We often have to store a collection of values. When the collection is of the same type
then array is used to store values. When the collection of values is not of the same type
then a structure is used to store the collection.
An Array is a group of related data items or collection of homogeneous data that share a
common name i.e. it contains elements of same datatype. If we want to represent a
collection of data items of different types using a single name, then we cannot use an
array.
C supports a constructed data type known as structure which is a method of packing data
of different types. A structure is a convenient tool for handling a group of logically
related data items. It is a collection of heterogeneous data that share a common name.
A structure is a collection of items which may be of different types referenced commonly
using one name. Each item in the structure is called as a member.
Declaration of Structure
A structure is also called user-defined data type. When a structure is declared a new data
type is created. You declare a structure using keyword struct. The following is the syntax
to declare a structure:
struct [structure-name]
{
members declaration
}[variables];
The above is a structure declaration for employee structure. Employee structure contains
members eno, ename, eadd, and bs. Each member may belong to a different type of
data. When you declare a structure you just create a new data type - struct employee.
Structure name is otherwise known as tag. The tag name may be used subsequently to
declare variables that have the tag’s structure.
Note that the above declaration has not declared any variables. It simply describes a format
called template to represent information as shown below:
eno Integer
ename 20 Characters
eadd 100 Characters
bs Float
While declaring a structure you can also declare variables by giving list of variables after
right brace. Members of a structure may be of standard data type or may be of another
structure type.
struct point
{
int x,y;
}fp,sp; /*sp and fp are two structure variables*/
When the variables are created to the template then the memory is allocated. The
number of bytes occupied by structure variable is equal to the total number of bytes
required for all members of the structure. For example, a variable of struct employee will
occupy 126 bytes (2+20+100+4). So, 126 bytes are allocated for the employee structure
variable e1.
Accessing a member
A structure is a collection of members. All members are to be accessed using a single
structure variable. So to access each member of the structure you have to use member
operator (.).
We can assign values to members of a structure in a number of ways. The members
themselves are not variables. They should be linked to structure variables in order to
make them meaningful members.
structure-variable.member
The following is an example for accessing member of a structure variable.
struct employee x;
x.eno=10; /*place 10 into eno number*/
scanf("%f",&x.bs);
strcpy(x.ename,"Santosh");
printf("%d %s %f",x.eno,x.ename,x.bs);
Once you use member operator to access a member of a structure, it is equivalent to a
variable of the member type. That means x.eno in the above example is equal to any
integer variable as eno is of integer type.
Structure Initialization
We can initialize a structure variable by listing out values to be stored in members of the
structure within braces after structure variable, while declaring the variable.
main()
{
struct st_record
{
int rno;
char name[20];
int weight;
float height;
};
struct st_record st1={1, "Ashok",60,180.75};
struct st_record st2={2, "Balu",50,185.72};
…
…
}
C language does not permit the initialization of individual structure members within the
template. The initialization must be done only in the declaration of the actual variables.
Example: Program to demonstrate how to use structure
main()
{
Unions
Unions are the concept borrowed from structures and follow the same syntax as
structures. However there is a distinction between them in terms of storage. In structures
each member has its own storage location, where as all the members of union use the
same location i.e. all through a union may contain many members of different types; it
can handle only one member at a time. In a union, memory is allocated to only the
largest member of the union. All the members of the union will share the same area.
That is why only one member can be active at a time.
Like structure, a union can be declared using keyword union as follows:
union item
{
int m;
char c;
float x;
}code;
This declares a variable code of type union item. The union contains 3 members, each
with different data type. However we can use one of them at a time. This is due to the
fact that only one location is allocated for a union variable, irrespective of its size.
1000 1001 1002 1003
c
------m-----
-------------------------x-------------------------
The compiler allocated a piece of storage that is large enough to hold largest variable
type in the union. In the declaration above, the member x requires 4 bytes which is
largest among the members.
For example, if we use x in the above example, then we should not use m and c. If you
try to use both at the same time, though C doesn’t stop; you overwrite one data with
another. If you access m after x and c, then the value available in union will be the value
of m. If you display all the members the value of m will be the same and rest all will be
garbage values.
A union is used for 2 purposes:
1) To conserve memory by using the same area for two or more different variables.
2) To represent the same area of the memory in different ways.
Output:
Enter Name: Zaheer
Enter the value of n2: 3.23
Enter the value of n1: 6
Value of n1 = 6
Value of n2 = 3.218751
Name = ♠
WEEK - 13
1 Files: Definition, Opening, Closing of Files
2 Reading and Writing of Files
3 Sample C Programs
------------------
File Handling
If the program requires the input data either 1 or 2, the user could supply the data at any
time. But if the details of the student in a very large institution are required to prepare
marks statement for all, we have to enter the whole details every time to our program.
This requires large man power, more time & computational resources; which is a
disadvantage with the traditional way of giving inputs to a program for execution with
the basic I/O functions.
When the data of the students are stored permanently, the data can be referred later and
makes the work easier for the user to generate the marks statement. When you have to
store data permanently, we have to use FILES. The files are stored in disks.
DEFINITION:
A file can be defined as a collection of bytes stored on the disk under a name. A file may
contain anything, in the sense the contents of files may be interpreted as a collection of
records or a collection of lines or a collection of instructions etc.
A file is a collection of records. Each record provides information to the user. These files
are arranged on the disk.
Basic operations on files include:
Open a file
Read data from file/Write data to file
Close a file
To access the data in a file using C we use a predefined structure FILE present in stdio.h
header file, that maintains all the information about files we create (such as pointer to
char in a file, end of file, mode of file etc).
FILE is a data type which is a means to identify and specify which file you want to
operate on because you may open several files simultaneously.
When a request is made for a file to be opened, what is returned is a pointer to the
structure FILE. To store that pointer, a pointer variable is declared as follows:
FILE *file_pointer;
where file_pointer points to first character of the opened file.
Opening of a file:
A file needs to be opened when it is to be used for read/write operation. A file is opened
by the fopen() function with two parameters in that function. These two parameters are
file name and file open mode.
Syntax: fopen(filename, file_open_mode);
The fopen function is defined in the “stdio.h” header file. The filename parameter refers
to any name of the file with an extension such as “data.txt” or “program.c” or
"student.dat" and so on.
File open mode refers to the mode of opening the file. It can be opened in ‘read mode’
or ‘write mode’ or ‘append mode’.
The function fopen() returns the starting address of file when the file we are trying to
open is existing (i.e. success) else it returns NULL which states the file is not existing or
filename given is incorrect.
E.g.: FILE *fp;
fp=fopen("data.txt","r");
/*If file exists fp points to the starting address in memory
Otherwise fp becomes NULL*/
if(fp==NULL) printf("No File exists in Directory");
NULL is a symbolic constant declared in stdio.h as 0.
Modes of Operation:
1. "r" (read) mode: open file for reading only.
2. "w" (write) mode: open file for writing only.
3. "a" (append) mode: open file for adding data to it.
4. "r+" open for reading and writing, start at beginning
5. "w+" open for reading and writing (overwrite file)
6. "a+" open for reading and writing (append if file exists)
When trying to open a file, one of the following things may happen:
When the mode is ‘writing’ a file with the specified name is created if the file does
not exist. The contents are deleted, if the file is already exists.
When the purpose is ‘appending’, the file is opened with the current contents safe.
A file with the specified name is created if the file does not exist.
When the purpose is ‘reading’, and if it exists, then the file is opened with the
current contents safe; otherwise an error occurs.
With these additional modes of operation (mode+), we can open and use a number of
files at a time. This number however depends on the system we use.
Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers
and all the links to the file are broken. It also prevents any accidental misuse of file.
Closing of unwanted files might help open the required files. The I/O library supports a
function to do this for us.
Syntax: fclose(file_pointer);
/*This would close the file associated with the FILE pointer file_pointer*/
fcloseall();
/*This would close all the opened files. It returns the number of files it closed. */
Example: Program to check whether given file is existing or not.
#include<stdio.h>
main()
{
FILE *fp;
fp=fopen("data.txt","r");
if(fp==NULL) {
printf("No File exists in Directory");
exit(0);
}
else
printf("File Opened");
fclose(fp);
getch();
}
Reading and Writing Character on Files
To write a character to a file, the input function used is putc or fputc. Assume that a file is
opened with mode 'w' with file pointer fp. Then the statement,
putc(character_variable,file_pointer);
fputc(character_variable,file_pointer);
writes the character contained in the 'character_variable' to the file associated with FILE
pointer 'file_pointer'.
E.g.: putc(c,fp);
fputc(c,fp1);
To read a character from a file, the output function used is getc or fgetc. Assume that a
file is opened with mode 'r' with file pointer fp. Then the statement,
character_variable = getc(file_pointer);
character_variable = fgetc(file_pointer);
read the character contained in file whose FILE pointer 'file_pointer' and stores in
'character_variable'.
E.g.: getc(fp);
fgetc(fp);
The file pointer moves by one character position for every operation of getc and putc.
The getc will return an end-of-file marker EOF, when end of the file has been reached.
Therefore, the reading should be terminated when EOF is encountered.
Example: Program for Writing to and reading from a file
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Write data to file: \n");
f1 = fopen("test.txt","w");
while((c=getchar())!='@')
putc(c,f1);
/*characters are stored into file until '@' is encountered*/
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("test.txt","r"); /*reads characters from file*/
while((c=getc(f1))!=EOF)
printf("%c",c);
fclose(f1);
getch();
}
Example: Program to write characters A to Z into a file and read the file and print the
characters in lowercase.
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Writing characters to file... \n");
f1 = fopen("alpha.txt","w");
for(ch=65;ch<=90;ch++)
fputc(ch,f1);
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("alpha.txt","r");
/*reads character by character in a file*/
while((c=getc(f1))!=EOF)
printf("%c",c+32); /*prints characters in lower case*/
fclose(f1);
fgets reads characters from current position until new line character is encountered or
len-1 bytes are read from file associated with FILE pointer fp. Places the characters read
from the file in the form of a string into str.
fgets(char *st,int len,FILE *fp);
E.g.: fgets(str,50,fp);
Example: Program to illustrate fgets and fputs function.
#include<stdio.h>
main()
{
FILE *fp;
char s[80];
clrscr();
fp=fopen("strfile.txt","w");
printf("\nEnter a few lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
printf("Content in file:\n");
fp=fopen("strfile.txt","r");
while(!feof(fp))
{
puts(s);
fgets(s,80,fp);
}
fclose(fp);
getch();
}
fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}