Module-5
Module-5
struct struct–name
{
data_type var–name;
data_type var–name;
...............
};
For example:
struct student
{
int r_no;
char name[20]; char
course[20];float fees;
};
1
5.1.2 Typedef Declarations
The typedef (derived from type definition) keyword enables the programmer to create a new data
type name by using an existing data type alternate name is given to a known data type.
The general syntax of using the typedef keyword is given as:
typedef existing_data_type new_data_type;
For example: typedef int INTEGER;then INTEGER is the
new name of data type int.
To declare variables using the new data type name, precede the variable name with the data type name
(new).
Therefore, to define an integer variable, INTEGER num=5;For
example, consider the following declaration:
typedef struct student
{
int r_no;
char name[20]; char
course[20];float fees;
};
2
by writing,
struct student stud1 = {01, "Rahul", "BCA", 45000};
1. Simple Addition
In this techniques, make a list of all data types and add the memory required by each.
Consider a simple structure of an employee
3
struct Employee
{
int emp_id; char name[20];
double salary;
char designation[20]; float experience;
};
Size = size of emp_id+ size of name + size of salary + size of designation + size of experienceSize of
emp_id = 2
Size of name =20* size of character Size of
salary = 8
Size of designation = 20 * Size of character Size of
experience = 4
Therefore, Size = 2 + 20*1 +8 +20 *1+4
= 2 +20+8+20+4
= 54bytes
2. Using sizeof operator
The sizeof operator is used to calculate the size of a data type, variable, or an expression.
This operator can be used as follows:
sizeof(struct_name);Ex:
#include<stdio.h> struct
employee
{
int emp_id; char name[10];
double salary;
char designation [20]; float experience;
};
void main()
{
struct employee e; printf(“%d”,
sizeof(e));
}
Example: C program to read and display the student details using structures.
#include<stdio.h>
struct student
{
int rnum;
char name[20];int marks;
}s[60];
void main()
{
int i,n;
printf("Enter the number of students");
4
scanf("%d",&n);
}
Output:
Enter the number of students: 5Enter
the roll number,
Name, Marks and Grade of
Student 1 details
14
Dhavan89
Student 2 details
15
Karan55
Student 3 details
11
Deepa45
Student 4 details
12
Lakshmi35
Student 5 details
10
Soma68
Student Details are:
Roll_number Name Marks
14 Dhavan 89
15 Karan 55
11 Deepa 45
12 Lakshmi 35
10 Soma 68
5
5.2 Structures and Functions
A function may access the members of a structure in three ways.
main()
{
POINT p1 = {2, 3};
display(p1.x, p1.y);
}
#include <stdio.h>typedef
struct
{
int x;int y;
}POINT;
void display(POINT);
6
void main()
{
POINT p1 = {2, 3};
display(p1);
}
void display(POINT p)
{
printf("The coordinates of the point are: %d %d", p.x, p.y);
}
Example: Write a program using pointer to structure to initialize the members in thestructure.
#include<stdio.h>struct
student
{
int r_no;
char name[20]; char course[20];
float fees;
};
void main()
{
struct student stud1, *ptr_stud1;ptr_stud1 = &stud1;
ptr_stud1->r_no = 01; strcpy(ptr_stud1->name,
"Rahul");strcpy(ptr_stud1->course, "BCA");
7
ptr_stud1->fees = 45000;
printf("\n DETAILS OF STUDENT");
printf("\n ");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME = %s", ptr_stud1->name); printf("\n
COURSE = %s", ptr_stud1->course); printf("\n FEES
= %f", ptr_stud1->fees);
}
5.3 Union
Like structure, a union is a collection of variables of different data types. The only difference
between a structure and a union is that in case of unions, you can only store information in one field
at any one time.
To better understand union, think of it as a chunk of memory that is used to store variables of different
types. When a new value is assigned to a field, the existing data is replaced with the new data.
8
void main()
{
POINT1 P1 = {2,3};
// POINT2 P2 ={4,5}; Illegal with unionPOINT2 P2;
P2. x = 4;P2.y = 5;
printf("\n The co-ordinates of P1 are %d and %d", P1.x, P1.y);printf("\n The co-
ordinates of P2 are %d and %d", P2.x, P2.y);
}
Output:
The co-ordinates of P1 are 2 and 3 The co-
ordinates of P2 are 5 and 5
int marks;
};
void main()
{
struct student stud;char
choice;
printf("\n You can enter the name or roll number of the student");printf("\n
Do you want to enter the name? (Yes or No) : "); scanf(&choice);
if(choice=='y' || choice=='Y')
{
printf("\n Enter the name : ");
scanf(“%s”,&stud.name);
}
else
9
}
10
border_color = bg_color;
11
5.5.6 Input/Output Operations on Enumerated Types
Since enumerated types are derived types, they cannot be read or written using formatted I/O
functions available in C. When we read or write an enumerated type, we read/write it as an integer.
The compiler would implicitly do the type conversion as discussed earlier.
enum COLORS(RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
enum COLORS c; c =
RED;
printf("\n Color = %d", c);
A variable of structure student can be defined by A variable of union student can be defined by
writing: writing:
struct student stud1; union student stud1;
Several members of a structure can be initialized at Individual members of a structure can be initialized
once. one by one.
Ex: Ex:
struct student stud1 = {01, "Rahul", "BCA", union student stud1;
45000}; stud1. r_no=01;
stud1. name= "Rahul";
stud1. course="BCA";
stud1. fees =45000;
Each member within structure is assigned unique The members or fields share the same memory
storage area of location. space, so fresh data replaces any existing data.
The size of the structure is the sum of all members The size of the union is the size of the largest
or fields. member or field.
Altering the value of a member will not affect other Altering any value of a member will alter other
members of the structure. member values.
12
Module 5
Files
5.6 Introduction to Files
A file is a collection of data stored on a secondary storage device like hard disk.
A file is basically used because real life applications involve large amounts of data and in such situations
the console oriented I/O operations pose two major problems:
First, it becomes cumbersome and time consuming to handle huge amount of data through
terminals.
Second, when doing I/O using terminal, the entire data is lost when either the program is
terminated or computer is turned off. Therefore, it becomes necessary to store data on a
permanent storage (the disks) and read whenever necessary, without destroying the data.
5.6.1 Streams in C
In C, the standard streams are termed as pre-connected input and output channels between a text
terminal and the program (when it begins execution).
Therefore, stream is a logical interface to the devices that are connected to the computer.
Stream is widely used as a logical interface to a file where a file can refer to a disk file, the computer
screen, keyboard, etc.
Although files may differ in the form and capabilities, all streams are the same.
The three standard streams (figure 16.1) in C languages are- standard input (stdin), standard output
(stdout) and standard error (stderr).
Standard input (stdin): Standard input is the stream from which the program receives its data.
The program requests transfer of data using the read operation. However, not all programs require
input. Generally, unless redirected, input for a program is expected from the keyboard.
Standard output (stdout): Standard output is the stream where a program writes its output
data. The program requests data transfer using the write operation. However, not all programs
generate output.
Standard error (stderr): Standard error is basically an output stream used by programs to
report error messages or diagnostics. It is a stream independent of standard output and can be
redirected separately. No doubt, the standard output and standard error can also be directed to the
same destination.
A stream is linked to a file using an open operation and disassociated from a file using a close operation.
13
5.6.2 Buffer Associated with File Stream
When a stream linked to a disk file is created, a buffer is automatically created and associated
with the stream.
A buffer is nothing but a block of memory that is used for temporary storage of data that has to
be read from or written to a file.
Buffers are needed because disk drives are block oriented devices as they can operate efficiently when
data has to be read/ written in blocks of certain size. The size of ideal buffer size is hardware dependant.
The buffer acts as an interface between the stream (which is character-oriented) and the disk
hardware (which is block oriented).
When the program has to write data to the stream, it is saved in the buffer till it is full. Then the entire
contents of the buffer are written to the disk as a block as shown in figure 16.2.
14
2. Binary Files
A binary file is a file which may contain any type of data, encoded in binary form for computer
storage and processing purposes.
Like a text file, a binary file is a collection of bytes.
Note that in C a byte and a character are equivalent. Therefore, a binary file is also referred to as a
character stream with following two essential differences.
A binary file does not require any special processing of the data and each byte of data is
transferred to or from the disk unprocessed.
C places no constructs on the file, and it may be read from, or written to, in any manner the
programmer wants.
Binary files store data in the internal representation format. Therefore, an int value will be stored I
binary form as 2 or byte value. The same format is used to store data in memory as well as in file. Like
text file, binary file also ends with an EOF marker.
Binary files can be either processed sequentially or randomly.
In a text file, an integer value 123 will be stored as a sequence of three characters- 1, 2 and 3. So each
character will take 1 byte and therefore, to store the integer value 123 we need 3 bytes. However, in a
binary file, the int value 123 will be stored in 2 bytes in the binary form. This clearly indicates that
binary files takes less space to store the same piece of data and eliminates conversion between
internal and external representations and are thus more efficient than the text files.
2. Opening a File
A file must be first opened before data can be read from it or written to it.
In order to open a file and associate it with a stream, the fopen() function is used.
The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
Using the above prototype, the file whose pathname is the string pointed to by file_name is opened in
the mode specified using the mode.
15
If successful, fopen() returns a pointer-to-structure and if it fails, it returns NULL.
File Name
Every file on the disk has a name associated with it.
In DOS the file name can have one to eight characters optionally followed by a period and an
extension that has one to three characters.
Windows and UNIX permit filenames having maximum of 256 characters.
In C, fopen() may contain the path information instead of specifying the filename. The path gives
information about the location of the file on the disk.
File Mode
Mode conveys to C the type of processing that will be done with the file.
The different modes in which a file can be opened for processing are given in Table below:
MODE DESCRIPTION
r Open a text file for reading. If the stream (file) does not exist then an error will be reported.
Open a text file for writing. If the stream does not exist then it is created otherwise if the file
w
already exists, then its contents would be deleted
a Append to a text file. if the file does not exist, it is created.
Open a binary file for reading. B indicates binary. By default this will be a sequential file in
rb
Media 4 format
wb Open a binary file for writing
ab Append to a binary file
Open a text file for both reading and writing. The stream will be positioned at the beginningof
r+ the file. When you specify "r+", you indicate that you want to read the file before you write
to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created if it does not exist,
w+
and will be truncated if it exists.
Open a text file for both reading and writing. The stream will be positioned at the end of the
a+
file content.
r+b/ rb+ Open a binary file for read/write
w+b/wb+ Create a binary file for read/write
a+b/ab+ Append a binary file for read/write
The fopen() can fail to open the specified file under certain conditions that are listed below:
Opening a file that is not ready for usage.
Opening a file that is specified to be on a non-existent directory/drive.
Opening a non-existent file for reading.
Opening a file to which access is not permitted.
Ex:
FILE *fp;
fp = fopen("Student.DAT", "r"); if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
} OR
char filename[30];FILE *fp;
gets(filename);
fp = fopen(filename, "r+");
16
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
1. fscanf()
The fscanf() is used to read formatted data from the stream.
The syntax of the fscanf() can be given as,
int fscanf(FILE *stream, const char *format,…);
The fscanf() is used to read data from the stream and store them according to the parameter
format into the locations pointed by the additional arguments.
Ex:
#include<stdio.h>
void main()
{
FILE *fp;
char name[80];int roll_no;
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
printf("\n Enter the name and roll number of the student : ");
fscanf(stdin, "%s %d", name, &roll_no); /* read from keyboard */
17
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no); // READ FROM FILE-
Student.DAT
fscanf(fp, "%s %d", name, &roll_no);
printf(“\n NAME : %s \t ROLL NUMBER = %d", name, roll_no);fclose(fp);
}
2. fgets()
fgets() stands for file get string.
The fgets() function is used to get a string from a stream.
The syntax of fgets() can be given as:
char *fgets(char *str, int size, FILE *stream);
The fgets() function reads at most one less than the number of characters specified by size (gets
size - 1 characters) from the given stream and stores them in the string str. The fgets() terminates
as soon as it encounters either a newline character or end-of-file or any other error. However, if a
newline character is encountered it is retained. When all the characters are read without any error, a '\0'
character is appended to end the string.
Ex:
#include<stdio.h>
void main()
{
FILE *fp; char str[80];
fp = fopen("Student.DAT", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
while (fgets(str, 80, fp) != NULL)printf("\n
%s", str);
printf("\n\n File Read. Now closing the file");fclose(fp);
}
3. fgetc()
The fgetc() function returns the next character from stream, or EOF if the end of file is reached
or if there is an error.
The syntax of fgetc() can be given as
int fgetc( FILE *stream );
fgetc returns the character read as an int or return EOF to indicate an error or end of file.
fgetc() reads a single character from the current position of a file (file associated with stream). After
reading the character, the function increments the associated file pointer (if defined) to point to the next
character. However, if the stream has already reached the end of file, the end-of-file indicator for the
stream is set.
Ex: Write a C program to copy a text file to another, read both the input file name and target file name.
#include <stdio.h>
#include <stdlib.h>
18
void main()
{
FILE *fptr1, *fptr2;
char filename1[100], filename2[100],ch;
while (!feof(fptr1))
{
ch=fgetc(fptr1);
fputc(ch,fptr2);
}
fclose(fptr1);
fclose(fptr2);
}
4. fread()
The fread() function is used to read data from a file.
Its syntax can be given as
int fread( void *str, size_t size, size_t num, FILE *stream );
The function fread() reads num number of objects (where each object is size bytes) and places them
into the array pointed to by str. The data is read from the given input stream.
Upon successful completion, fread() returns the number of bytes successfully read. The number
of objects will be less than num if a read error or end-of-file is encountered. If size or num is 0, fread()
19
will return 0 and the contents of str and the state of the stream remain unchanged. In case of error, theerror
indicator for the stream will be set.
The fread() function advances the file position indicator for the stream by the number of bytes read.
Ex:
#include <stdio.h>void
main()
{
FILE *fp; char str[10];
fp = fopen("Letter.TXT", "r+");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
fread(str, 1, 10, fp);
str[10]= '\0';
printf("\n First 9 characters of the file are : %s", str);fclose(fp);
}
1. fprintf()
The fpritnt() is used to write formatted output to stream.
Its syntax can be given as,
int fprintf ( FILE * stream, const char * format, ... );
The function writes to the specified stream, data that is formatted as specified by the format argument.
After the format parameter, the function can have as many additional arguments as specified in format.
The parameter format in the fprintf() is nothing but a C string that contains the text that has to be written
on to the stream.
Ex:
#include <stdio.h>void
main()
{
FILE *fp;int i;
char name[20];float salary;
fp = fopen("Details.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");
20
exit(1);
}
for(i=0;i<10;i++)
{
printf ("\n Enter your name : ");gets(name);
printf ("\n Enter your salary : ");scanf("%f",
&salary);
fprintf(fp, " NAME : %s \t SALARY: %f", name, salary);
}
fclose(fp);
}
2. fputs()
The fputs() is used to write a line into a file.
The syntax of fputs() can be given as
int fputs( const char *str, FILE *stream );
The fputs() writes the string pointed to by str to the stream pointed to by stream.
On successful completion, fputs() returns 0. In case of any error, fputs() returns EOF.
Ex:
#include<stdio.h>void
main()
{
FILE *fp;
char feedback[100];
fp = fopen("Comments.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
printf("\n Kindly give the feedback on this book : ");
gets(feedback);
fputs(feedback, fp);fclose(fp);
}
3. fputc()
The fputc() is used to write a character to the stream.
The syntax of fputc() can be given as,
int fputc(int c, FILE *stream);
The fputc() function will write the byte specified by c (converted to an unsigned char) to the output
stream pointed to by stream. Upon successful completion, fputc() will return the value it has written.
Otherwise, in case of error, the function will return EOF and the error indicator for the stream will be
set.
Ex: #include<stdio.h>
void main()
{
FILE *fp;
char feedback[100];
21
int i;
fp = fopen("Comments.TXT", "w");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
printf("\n Kindly give the feedback on this book : ");
gets(feedback);
for(i=0;i<feedback[i];i++)
fputc(feedback[i], fp);
fclose(fp);
}
4. fwrite()
The fwrite() is used to write data to a file.
The syntax of fwrite() can be given as,
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
The fwrite() function will write, from the array pointed to by str, up to count objects of size specified
by size, to the stream pointed to by stream.
The file-position indicator for the stream (if defined) will be advanced by the number of bytes
successfully written. In case of error, the error indicator for the stream will be set.
Ex: #include<stdio.h>
void main()
{
FILE *fp; size_t count;
char str[] = "GOOD MORNING ";
fp = fopen("Welcome.txt", "wb");
if(fp==NULL)
{
printf("\n The file could not be opened");exit(1);
}
count = fwrite(str, 1, strlen(str), fp);
printf("\n %d bytes were written to the files”, count);fclose(fp);
}
fwrite() can be used to write characters, integers, structures, etc to a file. However, fwrite() can be
used only with files that are opened in binary mode.
22
if (c==EOF) break;
printf("%c", c);
}
2. The other way is to use the standard library function feof() which is defined in stdio.h. The feof()
is used to distinguish between two cases
When a stream operation has reached the end of a file
When the EOF ("end of file") error code has been returned as a generic error indicator even
when the end of the file has not been reached
The prototype of feof() can be given as:
int feof(FILE *fp);
feof() returns zero (false) when the end of file has not been reached and a one (true) if the end-of-filehas
been reached.
while( !feof(fp)
{ fgets(str, 80, fp);
printf("\n %s", str);
}