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

unit 5 notes

The document covers the concepts of structures and unions in C programming, explaining their definitions, syntax, and how to declare and access their members. It also discusses file handling, including the definition of files, basic operations like opening, reading, writing, and closing files, along with examples of how to implement these operations in C. The document provides a comprehensive overview of data types, memory allocation, and file operations essential for effective programming in C.

Uploaded by

abitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

unit 5 notes

The document covers the concepts of structures and unions in C programming, explaining their definitions, syntax, and how to declare and access their members. It also discusses file handling, including the definition of files, basic operations like opening, reading, writing, and closing files, along with examples of how to implement these operations in C. The document provides a comprehensive overview of data types, memory allocation, and file operations essential for effective programming in C.

Uploaded by

abitha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT - 5

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

If we want to store details of an employee we have to create a structure:


struct employee
{
int eno;
char ename[20];
char eadd[100];
float bs;
};

Prepared by IT & CSE Page 142


Programming with C - Lab

Memory Image for structure employee

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

Declaring Structure variable


You can declare structure variables using struct structname. You can use a variable of any
structure anywhere in the program where the structure is visible. Normally structures are
declared at the beginning of the program and outside all functions, so that they are
global and available to the entire program.
Following is the declaration of structure variable e1:
struct employee e1;

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.

Prepared by IT & CSE Page 143


Programming with C - Lab

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()
{

Prepared by IT & CSE Page 144


Programming with C - Lab
}
getch();
}

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.

Prepared by IT & CSE Page 150


Programming with C - Lab

Example: Program to illustrate concept of unions.


#include<stdio.h>
#include<conio.h>
main()
{
union number
{
int n1;
float n2;
char name[20];
};
union number x;
clrscr();
printf("\nEnter Name: ");
gets(x.name);
printf("Enter the value of n2: ");
scanf("%f", &x.n2);
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("\n\nValue of n1 = %d",x.n1);
printf("\nValue of n2 = %f",x.n2);
printf("\nName = %s",x.name);
getch();
}

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 = ♠

Prepared by IT & CSE Page 151


UNIT-5

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.

Prepared by IT & CSE Page 177


Programming with C - Lab

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.

Prepared by IT & CSE Page 178


Programming with C - Lab

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

Prepared by IT & CSE Page 179


Programming with C - Lab

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

Prepared by IT & CSE Page 180


Programming with C - Lab
getch();
}
Example: Program to illustrate the append mode of operation for given file.
#include<stdio.h>
main()
{
FILE *f1;
char c,fname[20];
clrscr();
printf("Enter filename to be appended: ");
gets(fname);
printf("Read data from file: \n");
f1 = fopen(fname,"r");
if(f1==NULL)
{
printf("File not found!");
exit(1);
}
else
{
while((c=getc(f1))!=EOF)
printf("%c",c);
}
fclose(f1);
f1 = fopen(fname,"a");
while((c=getchar())!='@')
putc(c,f1);
/*characters are appended into file with existing data until
'@' is encountered*/
fclose(f1);
getch();
}

Reading and Writing Integers getw and putw functions:


These are integer-oriented functions. They are similar to getc and putc functions and are
used to read and write integer values. These functions would be useful when we deal
with only integer data.
The general forms of getw and putw are:
putw: Writes an integer to a file.
putw(integer,fp);
getw: Reads an integer from a file.
getw(fp);

Prepared by IT & CSE Page 181


Programming with C - Lab

Example: Program to illustrate getw and putw functions.


#include<stdio.h>
main()
{
int n,num,i,sum=0;
FILE *fp;
clrscr();
printf("Enter the number of integers to be written to file: ");
scanf("%d",&n);
fp = fopen("numbers.txt","w");
for(i=0;i<n;i++)
{
scanf("%d",&num);
putw(num,fp);
}
fclose(f1);
fp = fopen("numbers.txt","r");
while((num=getw(fp))!=EOF)
{
sum=sum+num;
}
fclose(fp);
printf("Sum of %d numbers is %d\n\n",n,sum);
printf("Average of %d numbers is %d",sum/n);
getch();
}
End of File: feof()
The feof() function can be used to test for the end of the file condition. It takes a FILE
pointer as its only argument and returns a non-zero integer value if all the data from
specified file has been read and returns zero otherwise.
This function returns true if you reached end of file in given file, otherwise returns false.
while(!feof(fp))
{
....
....
....
}
/*executes set of statements in the loop until EOF is encountered*/

fgets and fputs functions:


fputs writes string followed by new line into file associated with FILE pointer fp.
fputs(char *st, FILE *fp);
E.g.: fputs(str,fp);

Prepared by IT & CSE Page 182


Programming with C - Lab

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 and fscanf functions


The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and scanf functions, except of course that they work on files. The first argument of
these functions is a file pointer, where specifies the file to be used.
fprintf(): Writes given values into file according to the given format. This is similar to
printf but writes the output to a file instead of console.
fscanf(): Reads values from file and places values into list of arguments. Like scanf it
returns the number of items that are successfully read. When the end of file is reached, it
returns the value EOF.
The general form of fprintf and fscanf is

Prepared by IT & CSE Page 183


Programming with C - Lab

fprintf(file_pointer/stream, “control string”, list);


fscanf(file_pointer/stream, “control string”, list);
where file_pointer is a pointer associated with a file that has been opened for writing.
The stream refers to a stream or sequence of bytes that can be associated with a device or
a file. The following are the available standard file pointers/streams:
 stdin refers to standard input device, which is by default keyboard.
 stdout refers to standard output device, which is by default screen.
 stdprn refers to printer device.
 stderr refers to standard error device, which is by default screen.
The control string (format specifier) contains output specifications for the items in the list.
The list may include variables, constants and strings.
E.g.:
fprintf(fp, “%s %d %f”, name, age, 7.5); /*writes to file*/
fprintf(stdout, “%s %d %f”, name, age, 7.5); /*prints data on console*/
fscanf(fp, “%s %d %f”, name, &age, &per); /*reads from file*/
fscanf(stdin, “%s %d %f”, name, &age, &per); /*reads data from console*/
Example: Program to illustrate fprintf and fscanf function.
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[20],filename[10];
clrscr();
printf("Enter filename: ");
gets(filename);
fp=fopen(filename,"w");
printf("Enter Inventory data: \n");
printf("Enter Item Name, Number, Price and Quantity
(3 records):\n");
for(i=1;i<=3;i++) {
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %0.2f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("Item Name\tNumber\tPrice\tQuantity\tValue\n");
for(i=1;i<=3;i++)

Prepared by IT & CSE Page 184


Programming with C - Lab
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;

fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}

Prepared by IT & CSE Page 185

You might also like