0% found this document useful (0 votes)
9 views48 pages

Module5-PPT & Notes(Structure & Files) (1)

This document provides an overview of structures in C programming, detailing their declaration, initialization, member access, and manipulation. It covers typedef declarations, nested structures, arrays of structures, and methods for passing structures to functions, including through pointers. Additionally, it introduces self-referential structures, which are essential for implementing linked data structures.

Uploaded by

Sri Charitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views48 pages

Module5-PPT & Notes(Structure & Files) (1)

This document provides an overview of structures in C programming, detailing their declaration, initialization, member access, and manipulation. It covers typedef declarations, nested structures, arrays of structures, and methods for passing structures to functions, including through pointers. Additionally, it introduces self-referential structures, which are essential for implementing linked data structures.

Uploaded by

Sri Charitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

MODULE-5

CHAPTER 15
STRUCTURES

© Oxford University Press 2012. All rights reserved.


INTRODUCTION-

1. Structured Declaration
2. Typedef Declarations
3. Initialization of Structures
4. Accessing the members of a structure
5. Copying and comparing structures
6. Finding the size of a structure – simple addition, using
sizeof operator, subtracting the addresses

© Oxford University Press 2012. All rights reserved.


INTRODUCTION- 1. STRUCTURED DECLARATION
● A structure is same as that of records. It stores related information about an entity.
● Structure is basically a user defined data type that can store related information (even of
different data types) together.
● A structure is declared using the keyword struct followed by a structure name. All the variables
of the structures are declared within the structure. A structure type is defined by using the given
syntax.
● struct struct-name
{ data_type var-name;
data_type var-name;
...
};
struct student
{ int r_no;
char name[20];
char course[20];
float fees;
};
● The structure definition does not allocates any memory. It just gives a template that conveys to
the C compiler how the structure is laid out in memory and gives details of the member names.
Memory is allocated for the structure when we declare a variable of the structure. For ex, we
can define a variable of student by writing
struct student stud1;© Oxford University Press 2012. All rights reserved.
2. TYPEDEF DECLARATIONS
● When we precede a struct name with typedef keyword, then the struct becomes a new type. It
is used to make the construct shorter with more meaningful names for types already defined by
C or for types that you have declared. With a typedef declaration, becomes a synonym for the
type.
● For example, writing
● typedef struct student
● {
● int r_no;
● char name[20];
● char course[20];
● float fees;
● };
● Now that you have preceded the structure’s name with the keyword typedef, the student
becomes a new data type. Therefore, now you can straight away declare variables of this new
data type as you declare variables of type int, float, char, double, etc. to declare a variable of
structure student you will just write,
● student stud1;

© Oxford University Press 2012. All rights reserved.


3. INITIALIZATION OF STRUCTURES
● Initializing a structure means assigning some constants to the members of the structure.
● When the user does not explicitly initializes the structure then C automatically does that. For int
and float members, the values are initialized to zero and char and string members are initialized
to the ‘\0’ by default.
● The initializers are enclosed in braces and are separated by commas. Note that initializers
match their corresponding types in the structure definition.
● The general syntax to initialize a structure variable is given as follows.
● struct struct_name
● { data_type member_name1;
● data_type member_name2;
● data_type member_name3;
● .......................................
● }struct_var = {constant1, constant2, constant 3,...};
● OR
● struct struct_name
● { data_type member_name1;
● data_type member_name2;
● data_type member_name3;
● .......................................
● };
● struct struct_name struct_var = {constant1, constant2, ….};
● struct student stud1 = {01, “Rahul”, “BCA”, 45000};
© Oxford University Press 2012. All rights reserved.
4. ACCESSING THE MEMBERS OF A STRUCTURE
● Each member of a structure can be used just like a normal variable, but its name will be
a bit longer. A structure member variable is generally accessed using a ‘.’ (dot operator).
● The syntax of accessing a structure a member of a structure is:
struct_var.member_name
● For ex, to assign value to the individual data members of the structure variable Rahul,
we may write,
stud1.r_no = 01;
strcpy(stud1.name, “Rahul”);
stud1.course = “BCA”;
stud1.fees = 45000;
● We can assign a structure to another structure of the same type. For ex, if we have two
structure variables stu1 and stud2 of type struct student given as
● struct student stud1 = {01, "Rahul", "BCA", 45000};
● struct student stud2;
● Then to assign one structure variable to another we will write,
● stud2 = stud1;

© Oxford University Press 2012. All rights reserved.


5. Copying and Comparing a structure
● We can assign a structure to
another structure of the same type.
For ex, if we have two structure
variables stud1 and stud2 of type
struct student given as
● struct student stud1 = {01, "Rahul",
"BCA", 45000};
● struct student stud2;
● Then to assign one structure variable
to another we will write,
● stud2 = stud1;

© Oxford University Press 2012. All rights reserved.


6. Finding the size of a structure

© Oxford University Press 2012. All rights reserved.


6. Finding the size of a structure

© Oxford University Press 2012. All rights reserved.


Write a program using structures to read and display the
information about a student
● #include<stdio.h>
● int main()
● { struct student
● { int roll_no;
● char name[80];
● float fees;
● char DOB[80];
● };
● struct student stud1;
● printf(“\n Enter the roll number : “);
● scanf(“%d”, &stud1.roll_no);
● printf(“\n Enter the name : “);
● scanf(“%s”, stud1.name);
● printf(“\n Enter the fees : “);
● scanf(“%f”, &stud1.fees);
● printf(“\n Enter the DOB : “);
● scanf(“%s”, stud1.DOB);
● printf(“\n ********STUDENT’S DETAILS *******”);
● printf(“\n ROLL No. = %d”, stud1.roll_no);
● printf(“\n NAME. = %s”, stud1.name);
● printf(“\n ROLL No. = %f”, stud1.fees);
● printf(“\n ROLL No. = %s”, stud1.DOB);
● }

© Oxford University Press 2012. All rights reserved.


NESTED STRUCTURES
●A structure can be placed within another structure. That is, a structure may contain another
structure as its member. Such a structure that contains another structure as its member is
called a nested structure.
●typedef struct
● { char first_name[20];
● char mid_name[20];
char last_name[20];
}NAME;
typedef struct
{ int dd;
int mm;
int yy;
}DATE;
struct student stud1;
stud1.name.first_name = “Janak”;
stud1.name.mid_name = “Raj”;
●stud1.name.last_name = “Thareja”;
●stud1.course = “BCA”;
●stud1.DOB.dd = 15;

●stud1.DOB.mm = 09;

●stud1.DOB.yy = 1990;

●stud1.fees = 45000;
© Oxford University Press 2012. All rights reserved.
Write a program to read and display information of a student using
● #include<stdio.h> structure within a structure
● int main()
● { struct DOB
● {
● int day;
● int month;
● int year;
● };
● struct student
● { int roll_no;
● char name[100];
● float fees;
● struct DOB date;
● };
● struct student stud1;
● printf(“\n Enter the roll number : “);
● scanf(“%d”, &stud1.roll_no);
● printf(“\n Enter the name : “);
● scanf(“%s”, stud1.name);
● printf(“\n Enter the fees : “);
● scanf(“%f”, &stud1.fees);
● printf(“\n Enter the DOB : “);
● scanf(“%d %d %d”, &stud1.date.day, &stud1.date.month, &stud1.date.year);
● printf(“\n ********STUDENT’S DETAILS *******”);
● printf(“\n ROLL No. = %d”, stud1.roll_no);
● printf(“\n NAME. = %s”, stud1.name);
● printf(“\n FEES. = %f”, stud1.fees);
● printf(“\n DOB = %d - %d - %d”, stud1.date.day, stud1.date.month, stud1.date.year);
● }

© Oxford University Press 2012. All rights reserved.


ARRAYS OF STRUCTURES

● The general syntax for declaring an array of structure can be given as,
● struct struct_name struct_var[index];
● struct student stud[30];
● Now, to assign values to the ith student of the class, we will write,
● stud[i].r_no = 09;
● stud[i].name = “RASHI”;
● stud[i].course = “MCA”;
● stud[i].fees = 60000;

© Oxford University Press 2012. All rights reserved.


Write a program to read and display information of all the
students in the class.
● #include<stdio.h>
● int main()
● { struct student
● {
● int roll_no;
● char name[80];
● float fees;
● char DOB[80];
● };
● struct student stud[50];
● int n, i;
● printf(“\n Enter the number of students : “);
● scanf(“%d”, &n);
● for(i=0;i<n;i++)
● { printf(“\n Enter the roll number : “);
● scanf(“%d”, &stud[i].roll_no);
● printf(“\n Enter the name : “);
● scanf(“%s”, stud[i].name);
● printf(“\n Enter the fees : “);
● scanf(“%f”, stud[i].fees);
● printf(“\n Enter the DOB : “);
● scanf(“%s”, stud[i].DOB);
● }
● for(i=0;i<n;i++)
● { printf(“\n ********DETAILS OF %dth STUDENT*******”, i+1);
● printf(“\n ROLL No. = %d”, stud[i].roll_no);
● printf(“\n NAME. = %s”, stud[i].name);
● printf(“\n ROLL No. = %f”, stud[i].fees);
● printf(“\n ROLL No. = %s”, stud[i].DOB);
● }
● }

© Oxford University Press 2012. All rights reserved.


Structures and Functions

© Oxford University Press 2012. All rights reserved.


Passing Individual Structure Members to a Function
● To pass any individual member of the structure to a function we must use the direct
selection operator to refer to the individual members for the actual parameters. The called
program does not know if the two variables are ordinary variables or structure members.

● #include<stdio.h>
● typedef struct
● {
● int x;
● int y;
● }POINT;
● void display(int, int);
● main()
● {
● POINT p1 = {2, 3};
● display(p1.x, p1.y);
● return 0;
● }
● void display( int a, int b)
● {
● printf("%d %d", a, b);
● }
© Oxford University Press 2012. All rights reserved.
PASSING A STRUCTURE TO A FUNCTION
● When a structure is passed as an argument, it is passed using call by value method. That is a
copy of each member of the structure is made. No doubt, this is a very inefficient method
especially when the structure is very big or the function is called frequently. Therefore, in such a
situation passing and working with pointers may be more efficient.
● The general syntax for passing a structure to a function and returning a structure can be given
as, struct struct_name func_name(struct struct_name struct_var);
● The code given below passes a structure to the function using call-by-value method.
● #include<stdio.h>
● typedef struct
● {
● int x;
● int y;
● }POINT;
● void display(POINT);
● main()
● {
● POINT p1 = {2, 3};
● display(p1);
● return 0;
● }
● void display( POINT p)
● {
● printf("%d %d", p.x, p.y);
● }

© Oxford University Press 2012. All rights reserved.


PASSING STRUCTURES THROUGH POINTERS
● C allows to crerate a pointer to a structure. Like in other cases, a pointer to a structure is never
itself a structure, but merely a variable that holds the address of a structure. The syntax to
declare a pointer to a structure can be given as
● struct struct_name
● {
● data_type member_name1;
● data_type member_name2;
● .....................................
● }*ptr;
● OR
● struct struct_name *ptr;
● For our student structure we can declare a pointer variable by writing
● struct student *ptr_stud, stud;
● The next step is to assign the address of stud to the pointer using the address operator (&). So
to assign the address, we will write
● ptr_stud = &stud;
● To access the members of the structure, one way is to write
● /* get the structure, then select a member */
● (*ptr_stud).roll_no;
● An alternative to the above statement can be used by using ‘pointing-to’ operator (->) as shown
below.
● /* the roll_no in the structure ptr_stud points to */
● ptr_stud->roll_no = 01;

© Oxford University Press 2012. All rights reserved.


Write a program using pointer to structure to initialize the
members in the structure.
● #include<stdio.h>
● struct student
● {
● int r_no;
● char name[20];
● char course[20];
● float fees;
● };
● main()
● { struct student stud1, *ptr_stud1;
● ptr_stud1 = &stud1;
● ptr_stud1->r_no = 01;
● strcpy(ptr_stud1->name, "Rahul");
● strcpy(ptr_stud1->course, "BCA");
● ptr_stud1->fees = 45000;
● printf("\n DETAILS OF STUDENT");
● printf("\n ---------------------------------------------");
● printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
● printf("\n NAME = ", puts(ptr_stud1->name));
● printf("\n COURSE = ", puts(ptr_stud1->course));
● printf("\n FEES = %f", ptr_stud1->fees);
● }

© Oxford University Press 2012. All rights reserved.


SELF REFERENTIAL STRUCTURES

● Self referential structures are those structures that contain a reference to data of its same type.
That is, a self referential structure in addition to other data contains a pointer to a data that is of
the same type as that of the structure. For example, consider the structure node given below.
● struct node
● {
● int val;
● struct node *next;
● };
● Here the structure node will contain two types of data- an integer val and next that is a pointer
to a node. You must be wondering why do we need such a structure? Actually, self-referential
structure is the foundation of other data structures.

© Oxford University Press 2012. All rights reserved.


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.
● Thus unions are used to save memory. They are useful for applications that involve multiple
members, where values need not be assigned to all the members at any one time.
DECLARING A UNION
● The syntax for declaring a union is same as that of declaring a structure.
● union union-name
● { data_type var-name;
● data_type var-name;
...
};
Again, the typedef keyword can be used to simplify the declaration of union variables.
● The most important thing to remember about a union is that the size of an union is the size of its
largest field. This is because a sufficient number of bytes must be reserved to store the largest
sized field. © Oxford University Press 2012. All rights reserved.
ACCESSING A MEMBER OF A UNION
● A member of a union can be accessed using the same syntax as that of a structure. To access
the fields of a union, use the dot operator(.). That is the union variable name followed by the dot
operator followed by the member name.
INITIALIZING UNIONS
● It is an error to initialize any other union member except the first member
● A striking difference between a structure and a union is that in case of a union, the field fields
share the same memory space, so fresh data replaces any existing data. Look at the code
given below and observe the difference between a structure and union when their fields are to
be initialized.
● #include<stdio.h>
● typedef struct POINT1
● { int x, y;
● };
● typedef union POINT2
● {
● int x;
● int y;
● };
● main()
● { POINT1 P1 = {2,3};
● // POINT2 P2 ={4,5}; Illegeal with union

● POINT2 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);
● return 0;
● }
● OUTPUT
● The co-ordinates of P1 are 2 and 3
● The co-ordinates of P2 are 5 and 5

© Oxford University Press 2012. All rights reserved.


ARRAYS OF UNION VARIABLES
●Like structures we can also have array of union variables. However, because of the problem of
new data overwriting existing data in the other fields, the program may not display the accurate
results.
●#include <stdio.h>
●union POINT
●{ int x, y;
● };
●main()
●{ int i;
union POINT points[3];
points[0].x = 2; points[0].y = 3;
points[1].x = 4; points[1].y = 5;
points[2].x = 6; points[2].y = 7;
for(i=0;i<3;i++)
printf("\n Co-ordinates of Points[%d] are %d and %d", i, points[i].x, points[i].y);
return 0;
}
OUTPUT
●Co-ordinates of Points[0] are 3 and 3
●Co-ordinates of Points[1] are 5 and 5
●Co-ordinates of Points[2] are 7 and 7

© Oxford University Press 2012. All rights reserved.


UNIONS INSIDE STRUCTURES
● union can be very useful when declared inside a structure. Consider an example in which you
want a field of a structure to contain a string or an integer, depending on what the user
specifies. The following code illustrates such a scenario.
● struct student
● { union
● { char name[20];
● int roll_no;
● };
● int marks;
● };
● 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) : ");
● gets(choice);
● if(choice=='y' || choice=='Y')
● { printf("\n Enter the name : ");
gets(stud.name);
● }
● else
● { printf("\n Enter the roll number : ");
scanf("%d", &stud.roll_no);
● }
● printf("\n Enter the marks : ");
● scanf("%d", &stud.marks);
● if(choice=='y' || choice=='Y')
printf("\n Name : %s ", stud.name);
● else
printf("\n Roll Number : %d ", stud.roll_no);
● printf("\n Marks : %d", stud.marks);
● }

© Oxford University Press 2012. All rights reserved.


ENUMERATED DATA TYPES
● The enumerated data type is a user defined type based on the standard integer type.
● An enumeration consists of a set of named integer constants. That is, in an enumerated type,
each integer value is assigned an identifier. This identifier (also known as an enumeration
constant) can be used as symbolic names to make the program more readable.
● To define enumerated data types, enum keyword is used.
● Enumerations create new data types to contain values that are not limited to the values
fundamental data types may take. The syntax of creating an enumerated data type can be
given as below.
enum enumeration_name { identifier1, identifier2, …..., identifiern };
● Consider the example given below which creates a new type of variable called COLORS to
store colors constants.
● enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
In case you do not assign any value to a constant, the default value for the first one in the list -
RED (in our case), has the value of 0. The rest of the undefined constants have a value 1 more
than its previous one. So in our example,
● RED = 0, BLUE = 1, BLACK = 2, GREEN = 3, YELLOW = 4, PURPLE = 5, WHITE =6
● If you want to explicitly assign values to these integer constants then you should specifically
mention those values as shown below.
● enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW, PURPLE , WHITE = 15};
● As a result of the above statement, now
● RED = 2, BLUE = 3, BLACK = 5, GREEN = 7, YELLOW = 8, PURPLE = 9, WHITE = 15

© Oxford University Press 2012. All rights reserved.


ENUM VARIABLES
● The syntax for declaring a variable of an enumerated data type can be given as,
enumeration_name variable_name;

● So to create a variable of COLORS, we may write:


● enum COLORS bg_color;
● Another way to declare a variable can be as illustrated in the statement below.
● enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color, fore_color;
USING THE TYPEDEF KEYWORD
● C permits to use typedef keyword for enumerated data types. For ex, if we write
● typedef enum COLORS color;
● Then, we can straight-away declare variables by writing
● color forecolor = RED;
ASSIGNING VALUES TO ENUMERATED VARIABLES
● Once the enumerated variable has been declared, values can be stored in it. However, an
enumerated variable can hold only declared values for the type. For example, to assign the
color black to the back ground color, we will write,
● bg_color = BLACK;
● Once an enumerated variable has been assigned a value, we can store its value in another
variable of the same type as shown below.
● enum COLORS bg_color, border_color;
● bg_color = BLACK;
● border_color = bg_color;

© Oxford University Press 2012. All rights reserved.


ENUMERATION TYPE CONVERSION

● Enumerated types can be implicitly or explicitly cast. For ex, the compiler can implicitly cast an
enumerated type to an integer when required.
● However, when we implicitly cast an integer to an enumerated type, the compiler will either
generate an error or warning message.
● To understand this, answer one question. If we write:
● enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
● enum COLORS c;c = BLACK + WHITE;
● Here, c is an enumerate data type variable. If we write, c = BLACK + WHITE, then logically, it
should be 2 + 6 = 8; which is basically a value of type int. However, the left hand side of the
assignment operator is of the type enum COLORS. SO the statement would complain an error.
● To remove the error, you can do either of two things. First, declare c to be an int.
● Second, cast the right hand side in the following manner. :
● c = enum COLORS(BLACK + WHITE);

© Oxford University Press 2012. All rights reserved.


COMPARING ENUMERATED TYPES
● C also allows using comparison operators on enumerated data type. Look at the following
statements which illustrate this concept.
● bg_color = (enum COLORS)6;
● if(bg_color == WHITE)
● fore_color = BLUE;
● fore_color = BLUE;
● if(bg_color == fore_color)
● printf("\n NOT VISIBLE");
● Since enumerated types are derived from integer type, they can be used in a switch-case
statement.
● enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE}bg_color;
● switch(bg_color)
● {
● case RED:
● case BLUE:
● case GREEN:
● printf("\n It is a primary color");
● break;
● case default:
● printf("\n It is not a primary color");
● break;
● }
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;
● scanf("%d", &c);
● printf("\n Color = %d", c);

© Oxford University Press 2012. All rights reserved.


CHAPTER 16

FILE HANDLING IN C

© Oxford University Press 2012. All rights reserved.


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.

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 in C languages are- standard input (stdin), standard output (stdout)
and standard error (stderr).

© Oxford University Press 2012. All rights reserved.


STREAMS IN C contd.

● 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.
KEYBOARD
● Standard output (stdout): Standard output is the stream where a
stdin
program writes its output data. The program requests data transfer
PROGRAM
using the write operation. However, not all programs generate output.
stderr
● Standard error (stderr): Standard error is basically an output stream
used by programs to report error messages or diagnostics. It is a SCREEN

stream independent of standard output and can be redirected stdout

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.

© Oxford University Press 2012. All rights reserved.


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.
Data from the buffer is written to the disk file
Program writes data to buffer

PROGRAM BUFFER DISK

Similarly, when reading data from a disk file, the data is read as a block from the file and written
into the buffer. The program reads data from the buffer. The creation and operation of the buffer is
automatically handled by the operating system. However, C provides some functions for buffer
manipulation. The data resides in the buffer until the buffer is flushed or written to a file.
© Oxford University Press 2012. All rights reserved.
TYPES OF FILES
● In C, the types of files used can be broadly classified into two categories- ASCII text files
and binary files.
1. ASCII Text files
● A text file is a stream of characters that can be sequentially processed by a computer in forward
direction. For this reason a text file is usually opened for only one kind of operation (reading,
writing, or appending) at any given time.
● Because text files only process characters, they can only read or write data one character at a
time.
● In a text file, each line contains zero or more characters and ends with one or more characters
that specify the end of line. Each line in a text file can have maximum of 255 characters.
● A line in a text file is not a c string, so it is not terminated by a null character. When data is
written to a text file, each newline character is converted to a carriage return/line feed character.
Similarly, when data is read from a text file, each carriage return/ line feed character is
converted in to newline character.
● Another important thing is that when a text file is used, there are actually two representations of
data- internal or external. For ex, an int value will be represented as 2 or 4 bytes of memory
internally but externally the int value will be represented as a string of characters representing
its decimal or hexadecimal value. To convert internal representation into external, we can use
printf and fprintf functions. Similarly, to convert an external representation into internal scanf
© Oxford University Press 2012. All rights reserved.
and fscanf can be used.
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.
© Oxford University Press 2012. All rights reserved.
USING FILES IN C

● To use files in C, we must follow the steps given below.


● Declare a file pointer variable
● Open the file
● Process the file
● Close the file
Declaring a file pointer variable
● There can be a number of files on the disk. In order to access a particular file, you must
specify the name of the file that has to be used. This is accomplished by using a file pointer
variable that points to a structure FILE (defined in stdio.h). The file pointer will then be used
in all subsequent operations in the file. The syntax for declaring a file pointer is
● FILE *file_pointer_name;
● For example, if we write
● FILE *fp;
● Then, fp is declared as a file pointer.
● An error will be generated if you use the filename to access a file rather than the file pointer

© Oxford University Press 2012. All rights reserved.


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. If successful, fopen() returns a pointer-to-
structure and if it fails, it returns NULL.

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 already exists, then its
w
contents would be deleted
a Append to a text file. if the file does not exist, it is created.
rb Open a binary file for reading. B indicates binary. By default this will be a sequential file in 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 beginning of the file. When you
r+
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, and will be truncated if it
w+
exist.
a+ Open a text file for both reading and writing. The stream will be positioned at the end of the file content.
r+b/ rb+ Open a binary file for read/write
w+b/wb+ Create a binary file©
forOxford University Press 2012. All rights reserved.
read/write
a+b/ab+ Append a binary file for read/write
OPENINING A FILE contd.
● 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

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+");
● if(fp==NULL)
● {
● printf("\n The file could not be opened");
● exit(1);
● }

© Oxford University Press 2012. All rights reserved.


CLOSING A FILE USING FCLOSE()

● To close an open file, the fclose() function is used which disconnects a file pointer from a file.
After the fclose() has disconnected the file pointer from the file, the pointer can be used to
access a different file or the same file but in a different mode.
● The fclose() function not only closes the file but also flushed all the buffers that are maintained
for that file
● If you do not close a file after using it, the system closes it automatically when the program
exits. However, since there is a limit on the number of files which can be open simultaneously;
the programmer must close a file when it has been used. The prototype of the fclose() function
can be given as,
● int fclose(FILE *fp);
● Here, fp is a file pointer which points to the file that has to be closed. The function returns an
integer value which indicates whether the fclose() was successful or not. A zero is returned if
the function was successful; and a non-zero value is returned if an error occurred.

© Oxford University Press 2012. All rights reserved.


READ DATA FROM FILES
● C provides the following set of functions to read data from a file.
● fscanf() fgets() fgetc() fread()

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.
● #include<stdio.h>
● 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 */
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 : © %sOxford University
\t ROLL NUMBER Press 2012.
= %d", All rights
name, reserved.
roll_no);
fclose(fp);
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.
● 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);

© Oxford University Press 2012. All rights reserved.


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.
● FILE *fp;
● char str[80];
● int i, ch;
● fp = fopen("Program.C", "r");
● if(fp==NULL)
● { printf("\n The file could not be opened");
● exit(1);
● }
● // Read 79 characters and store them in str
● ch = fgetc(fp);
● for( i=0; (i < 79 ) && ( feof( fp ) == 0 ); i++ )
● { str[i] = (char)ch;
● ch = fgetc( stream );
● }
● str[i] = '\0';
● printf( "\n %s", str);
● fclose(fp);

© Oxford University Press 2012. All rights reserved.


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() will return 0 and the contents of str and the state of the stream remain unchanged. In
case of error, the error indicator for the stream will be set.
● The fread() function advances the file position indicator for the stream by the number of bytes
read.
● FILE *fp;
● char str[11];
● 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);

© Oxford University Press 2012. All rights reserved.


WRITING DATA TO FILES
● C provides the following set of functions to read data from a file.
● fprintf() fputs() fputc() fwrite()
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.
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");
● exit(1);
}
for(i=0;i<10;i++)
● { puts("\n Enter your name : ");
● gets(name);
● fflush(stdin);
● puts("\n Enter your salary : ");
● scanf("%f", &salary);
● fprintf(fp, " (%d) NAME : [%-10.10s] \t SALARY " %5.2f", i, name, salary);
● }
● fclose(fp);

© Oxford University Press 2012. All rights reserved.


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.
● #include<stdio.h>
● 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 tyhis book : ");
● gets(feedback);
● fflush(stdin);
● fputs(feedback, fp);
● fclose(fp);
● }

© Oxford University Press 2012. All rights reserved.


fputc()
● The fputc() is used to write a character to the stream.
● 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.
● #include<stdio.h>
● main()
● {
● FILE *fp;
● char feedback[100];
● 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=0i<feedback[i];i++)
● fputc(feedback[i], fp);
● fclose(fp);
● }

© Oxford University Press 2012. All rights reserved.


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.
● main(void)
● { 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.

© Oxford University Press 2012. All rights reserved.


DETECTING THE END-OF-FILE
● In C, there are two ways to detect the end-of-file
● While reading the file in text mode, character by character, the programmer can compare the
character that has been read with the EOF, which is a symbolic constant defined in stdio.h with
a value -1.
● while(1)
● { c = fgetc(fp); // here c is an int variable
● if (c==EOF)
● break;
● printf("%c", c);
● }
● 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-file has been reached.
● while( !feof(fp)
● { fgets(str, 80, fp);
● printf("\n %s", str);
© Oxford University Press 2012. All rights reserved.
● }
THANKYOU
ALL THE BEST FOR EXAM
by
Ranjitha J

© Oxford University Press 2012. All rights reserved.

You might also like