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

Unit - 4 (Structures)

The document discusses C data types including derived data types, structures, unions, and enumerated types. It provides details on defining and initializing structures, accessing structure members using the dot operator, and using typedef to define user-defined data types for structures. Structures allow storing different data types together and accessing members using the structure variable name and dot operator. Typedef defines a new name for an existing data type.

Uploaded by

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

Unit - 4 (Structures)

The document discusses C data types including derived data types, structures, unions, and enumerated types. It provides details on defining and initializing structures, accessing structure members using the dot operator, and using typedef to define user-defined data types for structures. Structures allow storing different data types together and accessing members using the structure variable name and dot operator. Typedef defines a new name for an existing data type.

Uploaded by

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

Enumerated, Structure, and Union types – The

type definition (typedef), enumerated types,


Structure, Unions

1
• The basic data types in C are int, float and char. using
these data types, we can derive some other data types,
the data types that are derived from the basic data
types are called derived data types.

Using arrays we can store only group of similar data types.


If u you want to store the dissimilar data types in same place then go for structures
STRUCTURES

• Structure definition
• initialization and accessing the members of a
structure
• nested structures
• structures and functions
• self- referential structures
• unions and enumerated data types.
STRUCTURES
Structure Definition
 A structure is a collection of one or more variables,
possibly of different data types, grouped together
and stored under a single name .
How to define a structure
Defined in three different ways
1. Tagged Structure
2. Structure Variables
3. Typedef Structure
1. Tagged Structure
struct tag_name
{
type1 member1;
type2 member2;
……………
……………
};
Where,
 struct is the keyword which tells the compiler that a structure is being
defined.
 Tag_name is the name of the structure.
 member1, member2 … are called members of the structure.
The members are declared within curly braces.
The closing brace must end with the semicolon.
Example: student details using tagged structure
Tag name
keyword

struct student
{
char rno[10];
Curly braces char name[30]; Members of structure
surround or
The structure float marks; structure elements
elements };
Semi colon required

Memory is not reserved for the structure definition since no variables are
associated with the structure definition. The members of the structure do not occupy
any memory until they are associated with the structure variables
The declaration of the structure variable takes of the form

struct tag_name var1, var2…;


We can declare structure variables any where in the program.
For the above example the variable declaration as follows,
struct student s1; // memory is allocated for the variable
now a variable of type struct student (derived type) is created,
the memory is allocated for the variable s1.

The following figure shows the memory organization for the above example .
s1
------ rno ------> <- name -> <- Marks ->
< 10 Bytes > < 30 Bytes > < 4 Bytes >

The no of bytes allocated for the structure variable s1= 10+30+4=44bytes.


Note: Normally, structure definition appears at the beginning of the program file,
before any variables or functions defined.
2. Structure Variables
We can also combine the structure definition and structure variables into a
single statement is referred as structure variables.
Syntax is
struct tag_name
{
type1 member1;
type2 member2;
……………
} var1, var2…;

Where,
 struct is the keyword which tells the compiler that a structure is being defined.
tag_name is the name of the structure.
 member1, member2 … are called members of the structure.
The members are declared within curly braces.
var1, var2… are structure variables that follow curly braces.
Here each variable occupies memory.
The closing brace must end with the semicolon
• Example struct student
{
char rno[10];
char name [30];
float marks;
} s1;

struct student
{
char rno[10];
char name [30];
float marks;
} s1,s2;
We can omit the tag name from the structure definition, the following is valid.
struct
{
char rno[10];
char name [30];
float marks;
} s1;
Does Not Reserve Space Reserves Space

struct my_example struct my_example


{ {
int label;
int label;
char letter;
char letter;
char name[20];
char name[20];
} mystruct ;
};
/* The name "my_example" is
called a structure tag */
The Type Definition (typedef)

A type definition, typedef, gives a name to a data type by creating a new type
that can then be used anywhere a type is permitted.

Its purpose is to redefine the name of an existing variable type.

11
Type-definition Format
The general syntax of the typedef is as follows,

typedef data_type IDENTIFIER;

where typedef is the keyword that tells the compiler about the type
definition, data_type refers to an existing data type and IDENTIFIER
refers the “new” name given to the data type.

Note that using typedef, we are not creating new data types.

Instead we are creating only new name for the existing data type.

These new data type names are called user-defined data types.

12
Suppose we want to store marks scored in various subjects
in variables sub1, sub2 and sub3. These variables can be
declared as follows,

int sub1, sub2, sub3;

Using the user-defined data types, the variables can be


declared as shown below,

typedef int MARKS;


MARKS sub1, sub2, sub3;

13
//Example program to demonstrate typedef

14
3. Typedefined Structure
 The structure definition associated with keyword typedef is called
type-defined structure.
 This is the most powerful way of defining the structure.
 The typedef
syntax ofstruct
typedefined structure is
{
type1 member1;
type2 member2;
……
} TYPE_ID;

where,
typedef is keyword added to the beginning of the definition.
struct is the keyword which tells the compiler that a structure is being de
member1, member2…are called members of the structure.
The closing brace must end with type definition name which in turn
ends with semicolon.
• Example: Student details
//Structure Definition
typedef struct
{
char rno[10];
char name [30];
float marks;
} STUDENT; //no memory is allocated for
structure
/* structure declaration */
STUDENT s1, s2; //memory is allocated for the variables.
Note: Using typedef it is not possible to declare a variable.
But, we can have user defined data type. TYPE_ID can be
treated as the new data type.
INITIALIZATION OF STRUCTURES
Structure initialization also similar to the array initialization.
Initializing values are put into curly braces and values separated
by commas.
Struct student s1={var1,var2,…..varn};

ex- struct student s1={“61”,”ramu”,75.5};

Initialization can be done in several ways


1. Initialization along with structure definition
struct student
{
char rno[10];
char name[30];
float avg;
}s1= {“61”,”ramu”,75.5};

6 1 \0 r a m u \0 7 5 . 5
2. Initialize during structure variable declaration
struct student
{
char rno[10];
char name[30];
float mark;
};
struct student s1={“61”,”ramu”,75.5};
 points to remember
1. members of the structure cannot be initialized in the structure definition.
struct student
{
char rno[10]=“61”;
invalid
char name[30];
float marks;
}s1;
2. We can initialize one structure variable at a time. The values are
assigned to members in the order specified in the structure
declaration.
3. During partial initialization, the values are assigned to members in
the order specified and remaining members are initialized with
garbage value.
ex- struct student s1={“61”};
will assign the string 61 to rno and remaining members are initialized
to garbage value.
however the statement
s1= {“ramu”,75.5}; invalid
HOW TO ACCESS STRUCTURE MEMBERS
• Structures use a dot (.) operator to refer its elements, also known as
period operator.
• structure_variable_name. structure_member_name.

• Before dot, there must always be a structure variable. After the dot,
there must always be a structure member

• For example, consider the example as shown below,


• struct student
{
char name [5];
int roll_number;
float avg;
};
struct student s1= {“Ravi”, 10, 67.8};
• The members can be accessed using the variables as shown below,
• s1.name --> refers the string “ravi”
• s1.roll_number --> refers the roll_number 10
• s1.avg --> refers avg 67.8
Structure Direct Selection Operator
21
#include<stdio.h>
struct student {
int rollno;
char name[20];
};
main() {
struct student s1 = {1222,“cbit"};
printf("\n%d%s",s1.rollno,s1.name);
#include<stdio.h>
}
typedef struct {
int rollno;
#include<stdio.h> char name[20];
struct student { }student;
int rollno; main() {
char name[20]; student s1 = {1222,“cbit"};
}s1; printf("\n%d %s",s1.rollno,s1.name);
main() { }
s1.rollno = 1222;
gets(s1.name);
printf("\n%d %s",s1.rollno,s1.name);
}
STRUCTURES AND POINTERS

• Pointer to a structure is called structure pointer.


• To access the members of the structure using pointers we need to
perform following things,

• 1. Declare structure variable: struct tag_name var;


• 2. Declare a pointer to a structure: struct tag_name *ptr;// refers
whole structure.
• 3. Store the address of structure variable in structure pointer:
ptr= &var;
• 4. Access the members of the structure.
• Members of the structures can be accessed in following ways two ways
1.Using De-Reference Operator * and Dot (.) Operator
Once the structure pointer is initialized, then each member of the
structure can be accessed using dot operator as shown below,
• (*ptr).structure_member1
• (*ptr).structure_member2
 Let’s take the following segment of code
 struct student
{
int rno;
char name[10];
float avg;
};
• struct student s1={101,”ABC”,78.98};
• struct student *ptr;
• ptr=&s1;
• Now the members of the structure can be accessed by using the dot
operator as shown below,
• (*ptr).name// Access the name
• (*ptr).rno // Access roll number
• (*ptr).avg // Access average
• Note: The parenthesis to all three expressions is necessary. We should
not omit the parenthesis. For example,
• *ptr .name // invalid way of accessing the member
2. Using Selection Operator (->)
• If ptr is a pointer to structure, then the members of the structure can
also be accessed using selection operator denoted by ->(which is formed
by minus sign and greater than symbol).
• Using this various members of the structure can be accessed as shown
below,
• ptr -> structrure_member
• For the above syntax the members can be accessed as follows,
• ptr - > name // Access the name
• ptr - > rno // Access roll number
• ptr - > avg // Access average
• Remember that on the right hand side of the dot operator, there must
always be a structure member, whereas on the left hand side of ->
operator there must be always be a pointer to structure. This method is
efficient, preferred over the previous method.
s1.rno s1.name s1.avg

0461 Arjun 80.5


1000 1003 1013
ptr

1000

2000
Example on structures using pointers.
Struct student
{
int rno;
char name[10];
float avg;
};
void main()
{
struct student s1;
struct student *ptr;
ptr=&s1;
printf(“\n enter student details”);
scanf(“%d %s %f”, &ptr->rno,ptr->name,&ptr-
>avg);
printf(“\n rollno=%d”,ptr->rno);
printf(“\n name=%s”,ptr->name);
printf(“\n average=%f”,ptr->avg);
SELF REFERENTIAL STRUCTURE

• A structure declaration which includes at least one member as a pointer to the same
structure is known as self-referential structure.
• Can be linked together to form useful data structures such as lists, queues, stacks and
trees.
• Terminated with a NULL pointer (0).
• The syntax for using the self referential structure as follows,

Struct tag_Name
Example
{
struct student
type1 member1;
{
type2 member2;
int rno;
….
struct student *next;
Struct tag_Name *next;
}s1,s2;
};
ARRAYS WITH IN STRUCTURES
• It is also possible to declare an array as a member of structure, like
declaring ordinary variables.
• For example to store marks of a student in three subjects the we
can have the following definition of a structure.
• struct student
{
char name [5];
int roll_number;
int marks [3];
float avg;
};
• Then the initialization of the array marks done as follows,
• struct student s1= {“ravi”, 34, {60,70,80},70.0};
• The values of the member marks array are referred as follows,
• s1.marks [0] --> will refer the 0th element in the marks
• s1.marks [1] --> will refer the 1st element in the marks
• s1.marks [2] --> will refer the 2ndt element in the marks
• This program illustrates how to read values into the structure and access the
members of the structure. Struct student
{
char name[30];
char rollno[10];
float marks[3];
};
void main() {
struct student s1;
int i;
printf(“\n enter student details”);
scanf(“%s”,s1.name);
scanf(“%s”,s1.rollno);
for(i=0;i<3;i++)
scanf(“%f”,&s1.marks[i]);
printf(“\n display student details”);
printf(“\n%s”,s1.name):
printf(“\n%s”,s1.rollno);
for(i=0;i<3;i++)
printf(“ %f”,s1.marks[i]);
}//main
ARRAY OF STRUCTURES
• As we have an array of integers, we can have an array of structures
also. For example, suppose we want to store the information of all
the students of a class, consisting of name, roll_number and marks,
A better approach would be to use an array of structures.
• Array of structures can be declared as follows,

struct tag_name arrayName[size];
Let’s take an example, to store the information of 3 students,
we can have the following structure definition and declaration,
struct student
{
char name[10];
int rno;
float avg;
};
struct student s[3];
Defines array called s, which contains three elements.
Each element is defined to be of type struct student
• For the student details, array of structures can be initialized as follows,
• struct student s[3]={{“ABC”,1,56.7},{“xyz”,2,65.8},{“pqr”,3,82.4}};
• The memory organization of the variables is illustrated in the below Figure,

S[0] Name rno avg


(10byte) (2byte) (4bytes)
Name rno avg
S[1]
(10byte) (2byte) (4bytes)
Name rno avg
S[2]
(10byte) (2byte) (4bytes)

…..
…. …. …

…. … … …
EXAMPLE ON ARRAY OF STRUCTURES
struct student
{
char name[30];
printf(“\n display student details”);
char rollno[10];
for(i=0;i<3;i++)
float marks;
{
};
printf(“\n student %d”,i+1);
void main()
printf(“\n name=“);
{
puts(s[i].name);
struct student s[3];
printf(“roll no=“);
int i;
puts(s[i].name);
printf(“\nenter the student details”);
printf(“marks=“);
for(i=0;i<3;i++)
puts(s[i].marks);
{
}//for
gets(s[i].name);
}//main
gets(s[i].rollno);
scanf(“%f”,&s[i].marks);
}//for
NESTED STRUCTURES
• A structure which includes another structure is called nested
structure i.e a structure can be used as a member of another
structure.
• The syntax for the nesting of the structure as follows
struct tag_name1 Example
{ struct student
{
type1 member1; char name [10];
……. int roll_number;
……. int marks [3];
struct tag_name2 float avg;
{ struct data
type1 member1; {
…… int day;
…… int month;
} var1; int year;
}var2; } dob;

}s1;
• The syntax for accessing members of a nested structure as follows,
outer_structure_variable.innerstructurevariable.membername

Example
struct student
{ s1.dob.day;
char name [10]; s1.dob.month;
int roll_number; s1.dob.year;
int marks [3]; s1.name;
float avg; s1.roll_number;

struct data
{
int day;
int month;
int year;
} dob;
}s1;
• Another way of using nested structures are

struct data
struct tag_name1
{
{
int day;
type1 member1;
int month;
…….
int year;
…….
};
};
struct student
struct tag_name2
{
{
char name [10];
type1 member1;
int roll_number;
……
struct data dob;
……
int marks [3];
struct tag_name1 var;
float avg;
……
} s1;
};
Note that the above structure consists of a member identified by dob whose type is
struct data.
The members contained in the inner structure namely day, month and year can be
referred to as
s1.dob.day s1.dob.month s1.dob.year
EXERCISE
• Write a c program to define a structure student having members roll no, name,
class, section,marks. Create an array of 10 students give the data and find the
average marks, in section wise.
//Program to demonstrate structure with functions.
#include<stdio.h>
struct student
{
int rollno;
char name[20];
}s1;

void display(struct student);


main()
{
s1.rollno = 1222;
gets(s1.name);
display(s1);
}

void display(struct student s2)


{
printf("%d%s",s2.rollno,s2.name);
}
EXAMPLE ON PASSING THE WHOLE STRUCTURE
UNIONS
• A union is one of the derived data type.
• Union is a collection of different variables referred under a single name.
• The syntax, declaration and use of union is similar to the structure but its
functionality is different.
• The major distinction between structure and union is, in terms of storage.
• The compiler allocates a piece of storage that is large enough to hold the largest
variable type in the union.
• In structure each member has its own storage location.
• Whereas all the members of a union use the same location.
• Although a union may contain many members of different types, it can handle only
one member at a time.
• The general format or syntax of a
union definition is as follows,
example
union u
union tag_name
{
{
char c;
type1 member1;
int i;
type2 member2;
float f;
……..
};
……..
};
union u a;

c i f
a.c

a.i

a.f
Enumerated Types

The enumerated type is a user-defined type based on the standard integer


type.

In an enumerated type, members are integer constants


For each member unique integer value is assigned called an enumeration
constant.

43
Declaring an Enumerated Type:

To declare an enumerated type, we must declare its


identifier and its values. Because it is derived from integer
type, its operations are the same as for integers.

Syntax for defining an enumerated type is as follows,

enum tag_name
{
member1;
member2;
…. Anther way of declaring the variables are shown below:
…. enum tag_Name var;
}var1,var2,var3;
44
Following are some of the examples of enumerator type:

enum color
enum days
{
{
RED,
SUNDAY,
BLUE,
MONDAY,
GREEN

};
SATURDAY
enum color c1, c2;
} d1;

By default the first member of the enum type is given the value 0.
- The next values are initialized to adding one to the previous value.
Second member value is 1 and so on.

RED-0,BLUE-1,GREEN-2

45
We can override it and assign our own values.
For example, to make JAN start with 1 we could use the following
declaration.
enum month
{
JAN=1, FEB, MAR, APR, MAY,JUN, JUL, AUG, SEP, OCT, NOV, DEC
}m1;

Note that we need not to assign every enumerator constant value. If


we omit the initializes, the complier assigns the next value by adding 1.

Consider the following enumerated declaration,


enum days
{
sun=4, mon, tue, wed=0, thu, fri, sat
} d1, d2;

46
//Example program to demonstrate enum
#include<stdio.h>
main()
{
enum color
{
RED,
GREEN,
BLUE
}c1;
printf("%d %d %d",RED,GREEN,BLUE); Output:
c1 = BLUE; 0 1 2
printf("\n%d ",c1); 2
}

47
48
49
Arrays Structures Unions
Keyword … struct union
Definition An array is a A structure is a collection A union is a collection of
homogeneous of logically related logically related elements,
collection of data. elements, possibly of possibly of different types,
different types, having a having a single name, shares
single name. single memory location.
Declaration data_type struct tag_name union tag_name
array_Name[size]; { {
type1 member1; type1 member1;
type1 member2; type1 member2;
…………… ……………
…………… ……………
}; };
struct tag_name var; union tag_name var;

Initialization Done by separating Same. Same.


list of values with
comma (,), specified
in Curly braces { }.
Accessing Accessed by Accessed by specifying Accessed by specifying
specifying array structure variablename. union variablename.
name with subscript membername
50 membername
Memory Each array element Each member of the Memory is allocated by
Allocation occupies memory, structure occupies unique considering the size of largest
stored in contigenous location, stored in member. All the members
locations. contigenous locations. share the common location
Size Size of the array is Size of the structure Size is given by the size of
depending on the depends on the type of largest member storage.
array type and size. members, adding size of all sizeof(un_variable);
sizeof (arr); members.
sizeof (st_var);
Using pointers An array elements Structure members can be Same as structure.
values can be accessed by using de-
accessed by using de- referencing dot operator and
referencing selection operator(->)
operator(*)
We can have array of We can have arrays as a We can have array as a
structures or unions. member of structures. member of union.
here the array type is
structure or union.
All elements can be All members can be Only one member can be
accessed at a time accessed at a time accessed at a time.

51
FILES

Files – File name, file information table, streams, text


and binary streams, stream file processing, system
created streams.
Standard library I/O functions, file open and close,
Formatting I/O functions, Character I/O functions,
Binary I/O, Standard library functions.
NEED OF FILES

• Scanf and printf functions are used to read and


write the data through terminals.
• This is fine as long as the data is small.
• When data is large, it is time consuming to handle
the data through terminals.
• The entire data is lost when the program is
terminated or the computer is turned off.
• It is necessary to maintain the data in a manner
that could be retrieved or used whenever needed.
FILES
A file is an external collection of related data treated as a unit.
The primary purpose of a file is to keep record of data.
 Record is a group of related fields. Field is a group of
characters they convey meaning.
Files are stored in auxiliary or secondary storage devices. The
two common forms of secondary storage are disk (hard disk, CD
and DVD) and tape.
Each file ends with an end of file (EOF) at a specified byte
number, recorded in file structure.
A file must first be opened properly before it can be accessed
for reading or writing. When a file is opened an object (buffer)
is created and a stream is associated with the object
FILE NAME:

File name is a string of characters that make up a valid filename.

Every operating system uses a set of rules for naming its files.

When we want to read or write files, we must use the operating


system rules when we name a file.

The file name may contain two parts, a primary name and an optional
period with extension.

Example: input.txt
program.c

55
55
FILE INFORMATION TABLE:

A program that reads or write files needs to know several


pieces of information, such as name of the file, the
position of the current character in the file ,size, type
and so on.

C has predefined structure to hold this information.

The stdio.h header file defines this file structure; its


name is FILE

When we need a file in our program, we declare it using


the FILE type.

56
56
BUFFER/ STREAM

 When the computer reads, the data move from the


external device to memory; when it writes, the data move
from memory to the external device. This data movement
often uses a special work area known as buffer.
 A buffer is a temporary storage area that holds data
while they are being transferred to or from memory.
 The primary purpose of a buffer is to synchronize the
physical devices(keyboard, monitor) with a program's
need.
STREAM:
 A stream is a source or destination of the data, it is associated
with a physical device such as terminals (keyboard, monitor) or
with a file stored in memory.

 C has two forms of streams: Text Stream and Binary Stream.


 A text stream consists of a sequence of characters divided into
lines with each line terminated by a new line (\n).

 A binary stream consists of sequence of data values such as


integer, real, or complex using their memory representation.

 A terminal keyboard and monitor can be associated only with a


text stream. A keyboard is a source for a text stream; a monitor
is a destination for a text stream.
59
59
System Created Streams:

C provides standard streams to communicate with a terminal.

The first, stdin, points to the standard input stream which is


normally connected to the keyboard.

The second, stdout, points to the standard output stream


which is normally connected to the monitor.

The third, points to the standard error stream which is also


normally connected to the monitor.

There is no need to open and close the standard streams. It is


done automatically by the operating system.

60
60
STREAM FILE PROCESSING:

A file exists as an independent entity with a name known to the


O.S.

A stream is an entity created by the program.

To use a file in our program, we must associate the program’s


stream name with the file name.

In general, there are four steps to processing a file.


1. Create a stream
2. Open a file
3. Process the file (read or write data)
4. Close a file
61
61
Creating a Stream:
We can create a stream when we declare it.

The declaration uses the FILE type as shown below:


FILE *spData;

The FILE type is a structure that contains the information needed


for reading and writing a file and spData is a pointer to the
stream.
Opening a File:
Once stream has been created, we can ready to associate the stream
to a file. This is done through open function.

When the file is opened, the stream and the file are associated with
each other.

Closing the Stream:


When file processing is complete, we close the file. After closing the
file The stream is no longer available.

62
62
FILE OPERATIONS
• Several operations are applied on the files.
1. creation a file
2. opening an existing file
3. reading from a file
4. closing a file.
5. writing to a file.
6. copying a file.
7. moving to a desired location in a file.
1.CREATION OF A FILE

• File name as “abc.c” and write some data in the file and save
in your folder then it permanently stored on to the disk.
• Abc.c
2. OPEN A FILE
 Before read or write data from or to a file on a disk we must open the file
using the function fopen() .
 it takes two arguments
1. file name which is to be opened
2. mode of a file whether it is read or write
fopen() performs three tasks
1. searches file on a disk which is to be opened
2. loads the file from disk to memory called buffer (temporary memory)
3. sets a character pointer that points to the first character of the buffer.
What is the need of buffer at all?
When we want to read a character from the file every time we need to access
the disk it takes the more time for the disk drive to position the read/write
head correctly.
- Read the file character by character from the buffer is efficient rather than
from disk.
• To open a file, we need to specify the physical filename and its mode.
• Syntax

fopen (“filename”,
• fopen() returns the address “mode”);
of the first character of the buffer which is
collected in the structure pointer called fp.
• Hence we declared as
FILE *fp;
FILE structure is defined in the header file “stdio.h”.
FILE OPENING MODES
while creating a file we are also specifying the purpose of opening this file.
The modes does this job.
1. “r” (read mode)- searches for the file. If file exist on disk, brought
into the memory and sets the pointer points to the first character in
the memory. If file does not exist returns the NULL.
syntax fopen(“filename”,”r”);
operation- reading the file.
2. “w” (write mode) - searches for the file. if file exist overwrite its
contents. If not create a new file . If space is not available on the
disk returns the NULL.
syntax fopen(“filename”,”w”);
operation- writing to a file.
3. “a” ( append mode) - searches file. If file already exist it returns the
pointer points to last character in the file. The new data is added at
the end of the file.
If the file doesn’t exist, it is created and opened. In this case, the
writing will start at the beginning of the file.
syntax fopen(“filename”,”a”);
operation- adding new contents to the end of the file.
4. “r+” ( read and write mode) - same as r mode. If file does not exist it
returns NULL.
Syntax: fopen (“filename”,”r+”);
operations are different – reading, writing new contents and modifying
the existing contents of the file.
5. “w+”-(write and read) writing new contents, reading them back and
modifying the existing contents of the file. If a file already exists its
contents erased. If a file does not exist then new file created.
Syntax: fopen (“filename”,”w+”);
6. “a+” (append and read) - reading existing contents, appending new
contents at the end of the file and cannot modify the existing content of
the file.
syntax: fopen(“filename”,”a+);
File Modes
69
PROGRAM FOR CHECK
WHETHER THE FILE IS EXIST
OR NOT
void main()
{
FILE *fp;
fp=fopen(“abc.r”,”r”);
if(fp= =NULL)
{
puts(“ file does not exist\n”);
exit();
}//if
}//main
4. CLOSING A FILE

• When we have finished with the open file, we need


to close it using fclose()
syntax fclose(file pointer);
this would perform three operations
1. file would be again written on to disk
2. buffer would be eliminated.
STANDARD LIBRARY I/O FUNCTIONS:

C includes many standard functions to input data from the keyword and
output data to the monitor.

The stdio.h header file contains several different input/output functions


declarations.

These are grouped into eight different categories.

72
72
73
73
FORMATED I/O FUNCTIONS:

We have already familiar with two formatting functions scanf and
printf.
These two functions can be used only with the keyboard and
monitor.

The C library defines two more general functions, fscanf and


fprintf, that can be used with any text stream.

74
74
Reading from Files: fscanf ()
It is used to read data from a user-specified stream.(files)

The general format of fscanf() is:


fscanf (stream_pointer, ”format string”, list);

The first argument is the stream pointer, it is the pointer to


the streams that has been declared and associated with a text
file. Remaining is same as scanf function arguments.

The following example illustrates the use of an input stream.


int a, b;
FILE *fptr1;
fptr1 = fopen (“mydata", "r”);
fscanf (fptr1, "%d %d", &a, &b);

The fscanf function would read values from the file "pointed"
to by fptr1 and assign those values
75
to a and b. 75
Writing to Files: fprintf ()
It can handle a group of mixed data simultaneously.

The first argument of these functions is a file pointer which


specifies the file to be used.

The general form of fprintf is:


fprintf (stream_pointer, ”format string”, list);

Where stream_pointer is a file pointer associated with a file


that has been opened for writing.

The format string contains output specifications for the items


in the list.

The list may include variables, constants and strings.


76
76
The following example illustrates the use of an Output stream.
int a = 5, b = 20;
FILE *fptr2;
fptr2 = fopen (“results", "w”);
fprintf (fptr2, "%d %d\n", a, b) ;

The fprintf functions would write the values stored in a and b


to the file "pointed" to by fptr2.

fprintf function works like printf except that it specifies the


file in which the data will be displayed.

77
77
WRITES RECORD OF A STUDENTS
TO A FILE USING STRUCTURE
#include<stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","w");
printf("\n enter name rollno and marks of a student\n");
scanf("%s %d %f",s.name,&s.rollno,&s.marks);
fprintf(fp,”%s\nr %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
}//main
READING RECORDS FROM A FILE
fscanf()- used to read the structure from a file
general form- fscanf(fp,”control string”,&var1,&var2….);
#include<stdio.h>
struct student
{
char name[30];
int rollno;
float marks;
};
void main()
{
FILE *fp;
struct student s;
fp=fopen("abc.c","r");
while(fscanf(fp,"%s %d %f",s.name,&s.rollno,&s.marks)!=EOF)
printf("%s\n %d\n%f\n",s.name,s.rollno,s.marks);
fclose(fp);
CHARACTER I/O FUNCTIONS:
Character input functions read one character at a time from a text
stream.
Character output functions write one character at the time to a text
stream.

These functions can be divided into two categories:


Terminal Character I/O, Terminal and File Character I/O
Character I/O

Terminal Only Any Stream

Input Output Input Output

getchar putchar getc / fgetc putc / fputc


80
TERMINAL CHARACTER I/O:
C declares a set of character input/output functions that can only be used
with the standard streams:
standard input (stdin), standard output (stdout).

Read a character: getchar ()


It reads the next character from the standard input stream and return its
value.
Syntax: int getchar (void);

Its return value is integer. Up on successful reading returns the ASCII


value of character otherwise it returns EOF.

Write a character: putchar ()


It writes one character to the monitor.
Syntax: int putchar (int ch);

Its return value is integer. Up on successful writing returns the ASCII value
of character. Otherwise returns EOF.

81 81
TERMINAL AND FILE CHARACTER I/O :

The terminal character input/output functions are designed for


convenience; we don’t need to specify the stream.

Here, we can use a more general set of functions that can be


used with both the standard streams and a file.

These functions require an argument that specifies the stream


associated with a terminal device or a file.

When used with a terminal device, the streams are declared


and opened by the system, the standard input stream (stdin)
for the keyword and standard output stream (stdout) for the
monitor.

When used with a file, we need to explicitly declare the stream,


it is our responsibility to open the stream and associate with
the file. 82
82
Read a character: getc () and fgetc ()

The getc functions read the next character from the stream,
which can be a user-defined stream or stdin, and converts it in
to an integer.

This function has one argument which is the file pointer


declared as FILE or stdin (in case of standard input stream).

If the read detects an end of file, the function returns EOF,


EOF is also returned if any error occurs.

The functionality of getc / fgetc is same.

Syntax:
int getc (FILE *spIn); or int getc(stdin);
int fgetc (FILE *spIn); or int fgetc(stdin);

83
83
Write a Character: putc () and fputc ()
The putc function writes a character to the stream which can
be a user-defined stream, stdout, or stderr.

The functionality of putc/ fputc is same.

The functions, putc or fputc takes two arguments.

The first parameter is the character to be written and the


second parameter is the file.

The second parameter is the file pointer declared as FILE or


stdout or stderr.

If the character is successfully written, the function returns


it. If any error occurs, it returns EOF.
Syntax:
int putc (char, *fp);
int fputc (char, *fp); 84
84
READING FROM A FILE-
FGETC()
• To read the contents of a file there exists a
function called fgetc().
• This function reads the character from the current
pointer position, advances the pointer to next
position and returns the character that is read.
WRITE A PROGRAM TO READ THE CONTENTS OF
THE FILE AND DISPLAY THEM ON CONSOLE

readf.c
• #include<stdio.h>
void main()
{
FILE *fp;
Char c;
fp=fopen(“readf.c”,”r”);
while((c=fgetc(fp))!=EOF)•While loop would be exit when it reaches to
the EOF which is special character of
printf(“%c”,c);
ascii value 26 placed beyond the last
fclose(fp); character of the file, when the file is created.
}//main
•EOF is macro defined in the file stdio.h
WRITING CHARACTERS ON TO A FILE

• To write characters on to a file use the function fputc() or


putc().
• It takes two arguments
1. character to be write on to a file
2. file pointer which points a file
WRITING CONTENTS ON TO A
FILE
#include<stdio.h>
void main() // read the contents of a file again
{ printf("display the contents of a file
FILE *fp; abc.c\n");
fp= fopen("abc.c","r");
char c; while((c=fgetc(fp)!=EOF)
// write contents on to a file printf("%c",c);
printf("open a file abc.c\n"); fclose(fp);
fp= fopen("abc.c","w"); }//main
while( (c=getchar())!=EOF)
fputc(c,fp);
fclose(fp);
6. WRITE A PROGRAM TO COPY THE
CONTENTS OF ONE FILE TO OTHER FILE.
fw=fopen("xyz.c","w");
#include<stdio.h> if(fw==NULL)
#include<stdlib.h> {
puts("no space in memory cannot be opened");
void main()
fclose(fw);
{ exit(0);
FILE *fr,*fw; }//if
while((c=fgetc(fr)!=EOF)
char c;
fputc(c,fw);
fr=fopen("abc.c","r"); }//while
if(fr==NULL) fclose(fr);
fclose(fw);
{ }//main
puts("file does not exist");
exit(0);
}//if
EXAMPLE ILLUSTRATING COUNTING
CHARACTERS,TABS,SPACE,…FROM A FILE
#include<stdio.h> if(c==' '||c=='\t'||c=='\n')
now++;
#include<stdlib.h>
if(c=='\n')
void main() nol++;
{FILE *fr; }//while
char c; fclose(fr);
int nol=0,nos=0,not=0,noc=0,now=0; printf("\n the no of characters=%d",noc);
printf("\n the no of spaces=%d",nos);
fr=fopen("countingf.c","r"); printf("\n the no of tabs=%d",not);
while((c=fgetc(fr))!=EOF) printf("\n the no of words=%d",now);
if(c!='\n') printf("\n the no of lines=%d",nol);
noc++; getch();
}//main
if(c==' ')
nos++;
if(c=='\t')
not++;
TEXT AND BINARY FILES

• All the programs what we have done so


far called text files in which
characters ,strings ,and numbers are
stored in the ascii codes that file is
text file.
• A binary file is a collection of bytes. It
is a compiled version of c program
like .exe file.
TEXT FILES AND BINARY FILES:
Text File: It is a file in which data are stored using only characters; a text file is
written using text stream.
Non-character data types are converted to a sequence of characters before they are
stored in the file.

In the text format, data are organized into lines, terminated by newline character.
The text files are in human readable form and they can be created and read using any
text editor.

Text files are read and written using input / output functions that convert characters
to data types: scanf and printf, getchar and putchar, fgets and fputs.

The following figure shows the data transfer in text file:

92
Reading and Writing Text Files 92
Binary File:
A binary file is a collection of data stored in the internal format of
the computer.

The binary files are not in human readable form.

There are no lines or newline characters.

Binary files are read and written using binary streams known as block
input / output functions.

The following figure shows the data transfer in binary file:

93
Block Input and Output 93
Differences between Text File and Binary File
94

Text File Binary File


Data is stored as lines of Data is stored on the disk in the
characters with each line same way as it is represented in
terminated by newline. the computer memory.
Human readable format. Not in human readable format.
There is a special character called There is an end-of-file marker.
end-of-file(EOF) marker at the
end of the file.
Data can be read using any of the Data can be read only by specific
text editors. programs written for them.
Opening Binary Files
The basic operation is unchanged for binary files, only the mode changes.
95
Just like text files, binary files must be closed when they are not needed
anymore using fclose ().

Mode Meaning
This mode opens a binary file in write mode.
wb
Example: fp=fopen (“data.dat”,”wb”);
This mode opens a binary file in read mode.
rb
Example: fp=fopen (“data.dat”,”rb”);
This mode opens a binary file in append mode.
ab
Example: fp=fopen (“data.dat”,”ab”);
This mode opens/creates a binary file in write and read mode.
w+b
Example: fp=fopen (“data.dat”,”w+b”);
This mode opens a pre-existing binary file in read and write mode.
r+b
Example: fp=fopen (“data.dat”,”r+b”);
This mode opens/creates a binary file in append mode.
a+b
Example: fp=fopen (“data.dat”,”a+b”);

Binary Modes of Opened File


BLOCK I/O FUNCTIONS:

C language uses the block input and output functions to read and write
data of binary files.

As we know that data are stored in memory in the form of 0’s and 1’s.

When we read and write the binary files, the data are transferred
just as they are found in memory and hence there are no format
conversions.

The block read function is file read(fread) and the block write
function is file write (fwrite).

96
96
• To write the records on to a binary file use library function fwrite()
• fwrite() takes 4 arguments

syntax

fwrite (&structure variable,sizeof(structure variable),no.of records to be


write at time,file pointer);

To read the records from a file use fread with four arguments .
fread (&structure variable,sizeof(structure variable),no.of records to be
read at a time,file pointer);
/* write a c program to write and read a student record by using fwrite() and fread()*/

#include<stdio.h>

Struct student{

Char name[30];

int rollno;

float marks;

}s;

void main(){

FILE *fptr;

fptr=fopen(“student.dat”,”wb+”);

Printf(“enter student details”);

scanf(“%s %d %f”,s.name,&s.rollno,&s.marks);

fwrite(&s,sizeof(s),1,fptr);

fread(&s,sizeof(s),1,fptr);

printf(“\n student name=%s”,s.name);

printf(“\n student rollno=%d”,s.rollno);

printf(“\n student marks=%f”,s.marks);

fclose(fptr);}//main
COMMAND LINE ARGUMENTS

• Passing parameters to the main function is called command


line arguments.
• It is also supplying the parameters to a program when the
program is running.
• If we want to copying the one file to another file use the
command as
c> ./a.out abc.data xyz.data.
• Main function also takes two arguments called argc and
argv the information contained in the command line is
passed on to the program through these arguments.
• argc- no of arguments passing to a program
when the program is running.
• argv()- it is an array of pointers to strings.
• When the program is executed, the strings on
the command line are passed to main()
• Ex- ./a.out abc.data xyx.data
Then
argc would contains 3
argv[0]- base address of the string “./a.out”
argv[1]- base address of the string “abc.data”
argv[2]- base address of the string “xyz.data”.
COPY CONTENT OF ONE FILE TO ANOTHER FILE USING COMMAND LINE
ARGUMENTS
void main(int argc,char *argv[])

FILE *fp;

Char ch;

FILE *fp1,*fp2;
How to execute this command line arguments
program
fp1= fopen(argv[i],”r”);

fp2= fopen(argv[2],”w”);

if(fp1)

To compile cc filename.c
{

While(( ch=getc(fp1))!= EOF)

putc(ch,fp2);

To execute .\a.out inputfilename outputfilename


}//while

}//if

else

printf(“file does not exist”);

fclose(fp1);

fclose{fp2);

}//main
• /* write c c program to create a file by command line argument and add
text given by the user to that file and open the file created above and display it

#include<stdio.h>
void main(int argc,char *argv[])
{
char ch;
FILE *fp;
fp=fopen(argv[1],"w");
while((ch=getchar())!=EOF)
fputc(ch,fp);
fclose(fp);
fp=fopen(“xyz.c”,”r”);
while((ch=fgetc(fp))!=EOF)
printf(“%c”,ch);
fclose(fp);
}//main
RANDOM ACCESS TO FILES

• So far we have used functions to read or write data


sequentially.
• How do you access a file randomly?

• To access the particular part of the file use the


following functions
1. ftell() - current position of the file pointer in a file
2. fseek() – move to particular position in a file.
3. rewind() – moves file pointer to the beginning of
the file.
FTELL() CURRENT POSITION
• ftell()-IN A FILE
• This function gives the current position of the file pointer in a
file, relative to beginning of a file.
• It measures the position in the file by the number of bytes,
relative to zero, from the beginning of the file.
• Returns the no of bytes from the beginning of a file to current
position.
• syntax long int ftell(File Pointer);
REWIND()- REWIND FILE
• rewind() – this function takes the file pointer to the beginning of
the file.
• Used when you want to read a file more than one time without
close and open a file.
• to change a work file from a write state to a read state.
• syntax
void rewind(file pointer);
• rewind(fp);
rewind(fp);
n=ftell(fp);
here n=0
Remember that the first byte in the file is numbered as 0.
FSEEK()- SET PARTICULAR
POSITION
• fseek()- sets the file pointer to a particular position in a file.
• We can move forward and backward within the file.
Syntax
int fseek(FILE *stream, long offset, int position);
Where
FILE *stream- file pointer
offset- specifies the number of positions to be moved from the location
specified by the position.
Position- it may have three values.
0- beginning of the file
1- current position
2- end of the file.
If offset is +ve it moves forward , -ve moves backward
When operation is successful it returns the value zero else returns -1
OPERATIONS OF FSEEK()
Statement Meaning
fseek(fp,0L,0); Go to the beginning.
fseek(fp,0L,1); Stay at the current position.
fseek(fp,0L,2); Go to the end of the file, past the last character
of the file.
fseek(fp,m,0) Move to (m+1)th byte in the file from
beginning
fseek(fp,m,1); Go forward by m bytes from current location
fseek(fp,-m,1); Go backward by m bytes from the current
position.
fseek(fp,-m,2); Go backward by m bytes from the end.
(positions the file to the character from the end.)
#include<stdio.h>

void main()

{ Example illustrates ftell(),fseek() and rewind()


FILE *fptr;

char ch;

long int n=0L;

fptr=fopen("fseekExout.c","w+");

while((ch=getchar())!=EOF)

fputc(ch,fptr);

printf("\n");

printf("\ncurrent position of file pointer is %ld and character is %c",ftell(fptr),getc(fptr));

rewind(fptr);

fseek(fptr,n,0);

printf("\ncharacter at this position is %c=",getc(fptr));

fseek(fptr,10L,1);

printf("\n charcter at position is %c=",getc(fptr));

fclose(fptr);

}//main

You might also like