CP Unit-V - RIT CSE (2)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Programming For Problem Solving Using C

UNIT-V
STRUCTURES
Structure is a constructed data type for packing data of different types. It is a convenient tool for
handling a group of logically related data items.
Advantages:
1. Structures enable the user to group together a collection of different data items of
different data types using a single name.
2. Structures help to organize complex data in a more meaningful way.
Example:
A structure can be used to represent a student‟s details such as student_name, rollno, marks etc
as follows
Struct student
{
char stud_name[20];
char stud_rollno[10];
float stud_mark1;
float stud_mark2;
float stud_mark3;
};
A structure definition creates a format that may be used to declare structure variables.
General format for structure definition is as follows:

CSE, RIT Page 1


Example:

In the above example book_bank is a tag-name that is optional one. If you give the tagname then
later in the program you can declare the variables using the given tag-name otherwise it is not
possible. The title, author, pages and price are members of the structure. While defining the
structure memory is not allocated for its members. Only during the declaration the memory is
allocated for the members. Thus the structure definition creates a template to represent a group of
logically related information. In the structure definition we should follow the rules stated below
1. The template is terminated with semicolon.
2.While the entire declaration is considered as a statement, each member is declared
independently for its name and type in a separate statement inside the template.
3. The tag name such as book_bank can be used to declare structure variables of its type
later in the program.

There are 2 ways in which we can declare a structure.


1.The user can combine the template declaration and the variable declaration in a single
statement as follows
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;

2.The use of tag name is optional as follows


struct
{
char title[20];
char author[15];
int pages;
float price;
}book1,book2,book3;

CSE, RIT Page 2


We can assign values to members of a structure. The structure members themselves are not
variables. They should be linked to the structure variables in order to make them meaningful
members. For example the word title, has no meaning when it appears alone. The same structure
member when it appears with the structure variable book1 as book1‟s title has a meaning. The
link between a structure member and a structure variable is established using the member
operator „.‟, which is also called as “dot operator” or “period operator”. Thus we can assign a
value to the member using dot operator like as follows
b1.price=150.00;
b2.title=”c programming”;
The same dot operator can be used to assign values to the structure members through the
keyboard as follows
scanf(“%s”,book1.title);

Example:
/*Program to illustrate the dot operator*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}student1;
void main()
{
printf(“Enter student details\n”);
printf(“\nStudent Name : “);
scanf(“%s”,student1.stud_name);
printf(“\nRoll no : “);
scanf(“%s”,student1.stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&student.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&student.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&student.mark3);
student1.tot = student1.mark1 + student1.mark2 + student1.mark3;
printf(“The student details are as follows….\n”);
printf(“Student name : %s\n”,student1.stud_name);
printf(“Roll no : %s\n”,student1.stud_rollno);
printf(“Marks : %f %f %f\n”,student1.mark1,student1.mark2,student1.mark3);
printf(“Total : %f\n”,student1.tot);
}

CSE, RIT Page 3


Structure Initialization
Like any other type, a structure variable can be initialized. However, a structure must be declared
as static if it is to be initialized inside a function.
Example:
main( )
static struct
{
int weight;
float height;
}student={100,150.45};
……………………..
}
Thus in the above example the value 100 is stored in student.weight and 150.45 to
student.height. There is a one- to-one correspondence between the members and their initializing
values.
A variation in initializing a structure is as follows:
main( )
{
struct st_record
{
int weight;
float weight;
};
static struct st_record stu1={30,70.56};
static struct st_record stu2={45,65.73};
……………
}
Another variation in initializing structure variable outside the function is as follows:
struct stu
{
int weight;
float height;
}stu1={56,170.56};
main()
{
static struct stu student2 = {23,150.5};
………………..
………………..
}

Comparison of structures
Two variables of same structure type can be compared in the same way as ordinary variables. If
book1 and book2 are of same type then it is possible to compare two variables as book1==
book2. Similarly we can assign book2 to book1 as book1=book2.etc.

CSE, RIT Page 4


Example:
/*Program to illustrate comparison and copying of structure variables*/
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
}
void main()
{
static struct student s1={“aaa”,”00CS0001”,50,50,50};
static struct student s2,s3={“bbb”,”00CS002”,20,90,30};
s2=s1; //assigns structure s1‟s contents to structure s2
if(s2 = = s1) //compares structure s2 and s1
printf(“Both the persons are the same\n”);
if(s2 = = s3)
printf(“Both the persons are the same”);
else
printf(“Both he persons are different”);
if(s2.mark1 = = s3.mark1) //compares structure elements
printf(“Student 1 and 2‟s marks are the same\n”);
else
printf(“Marks are different\n”);
}
Arrays of Structures:
We use structures to describe the format of a number of related variables. For example if we
want to analyze the marks obtained by a class of students then we can use array of structures.
Example:
/*Program to illustrate arrays of structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3,tot;
};
void main()
{
static struct student s[3];
int I;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
CSE, RIT Page 5
scanf(“%s”,s[I].stud_rollno);
printf(“\nMark1 : “);
scanf(“%f”,&s[I].mark1);
printf(“\nMark2 : “);
scanf(“%f”,&s[I].mark2);
printf(“\nMark3 : “);
scanf(“%f”,&s[I].mark3);
s[I].tot = s[I].mark1 + s[I].mark2 + s[I].mark3;
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Marks : %f %f %f\n”,s[I].mark1,s[I].mark2,s[I].mark3);
printf(“Total : %f\n”,s[I].tot);
}
}
The above example declares a structure with 6 members. Also we have declared s to be an array
consisting of 3 members of type struct student. Each individual element is accessed using the dot
operator. Thus the details of the first student can be represented as follows
S[1].stud_name
S[1].stud_rollno etc.

Arrays within structures

C permits the use of arrays as structure members. In the previous example we have declared
three variables mark1, mark2, mark3. We can eliminate this by using an array to hold the 3
marks. Thus the declaration will be as like as follows.
struct student
{
char stud_name[25];
char stud_rollno[10];
float marks[3];
}s[3];
Thus in the above example student contains 3 elements - stud_name, stud_rollno, and an array of
3 marks. The marks can be accessed as stu[2].marks[1]. Thus it refers to the mark obtained in the
first subject by the second student.

Example:
/*Arrays within structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
CSE, RIT Page 6
float marks[3],tot;
};
void main()
{
static struct student s[3];
int I,j;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
s[I].tot=0;
for(j=0;j<3;j++)
{
printf(“\nMark%d : “,j);
scanf(“%f”,&s[I].marks[j]);
s[I].tot = s[I].marks[j];
}}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
for(j=0;j<3;j++)
{
printf(“Mark%d : %f \n”,j,s[I].marks[j]);
}
printf(“Total : %f\n”,s[I].tot); }}

Structures within structures (Nested structures)

Structures within the structure means nesting of structures. Nesting of structures is permitted in
„C‟. Let us consider the following structure definition to store the information about the student.
struct student
{
char stud_name[25];
char stud_rollno[10];
float mark1,mark2,mark3;
float tot;
};
The above structure defines student name, rollno, and the marks of the student. We can group the
marks into one sub structure as follows:
struct student
{
CSE, RIT Page 7
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
}s[3];

The individual marks of the second student are referred as s[2].m.mark1.

Example: (complete program)


/*Structures within structures*/
#include<stdio.h>
struct student
{
char stud_name[25];
char stud_rollno[10];
struct marks
{
float mark1;
float mark2;
float mark3;
}m;
float tot;
};
void main()
{
static struct student s[3];
int I,j;
for(I=0;I<3;I++)
{
printf(“Enter student %d details\n”,i);
printf(“\nStudent Name : “);
scanf(“%s”,s[I].stud_name);
printf(“\nRoll no : “);
scanf(“%s”,s[I].stud_rollno);
s[I].tot=0;
printf(“\nMark1 : “);
scanf(“%f”,&s[I].m.mark1);
printf(“\nMark2 : “);
scanf(“%f”,&s[I].m.mark2);
printf(“\nMark3 : “);
scanf(“%f”,&s[I].m.mark3);
CSE, RIT Page 8
s[I].tot = s[I].m.mark1+s[I].m.mark2+s[I].m.mark3;
}
printf(“The student details are as follows….\n”);
for(I=0;I<3;I++)
{
printf(“Student name : %s\n”,s[I].stud_name);
printf(“Roll no : %s\n”,s[I].stud_rollno);
printf(“Mark1 : %f \n”,s[I].m.mark1);
printf(“Mark2 : %f\n”,s[I].m.mark2);
printf(“Mark3 : %f\n”,s[I].m.mark3);
printf(“Total : %f\n”,s[I].tot);
}
}

Self referential structures

A self-referential structure is used to create data structures like linked lists, stacks, etc.
Following is an example of this kind of structure:

struct struct_name
{
datatype datatype_name;
struct_name * pointer_name;
};

Example with self-referential structure:

/*self referential structures */


#include <stdio.h> #include <string.h>
struct person
{
char name1[20];
int age;
char name2[10];
struct person *tPrev; /* self-referential structure */
struct person *tNext; /* self-referential structure */
};
void main()
{
long x;
struct person *person1,*person2,p1,p2;
person1 = &p1;
person2 = &p2;

CSE, RIT Page 9


person1->tNext = person2;
person1->tPrev = NULL;
person2->tPrev = person1;
person2->tNext = NULL;
person1->age = 40;
person2->age = 50;
clrscr();
printf("person1 & person2 ages: %d\t%d\n",(*person1).age,(*person2).age);/* using *(value
at) */
printf("person1 & person2 ages: %d\t%d\n",person1->age,person2->age);/* using arrow
*/
getch();
}
NULL 40
50 NULL
Output:
person1 & person2 ages: 40 50
person1 & person2 ages: 40 50

UNIONS
Unions are the concept derived from structure. So the definition of union is same as structure
except with the keyword union. The main difference between the structure and the union is in the
memory allocation only. In structure the memory is allocated for all the members included
within the structure and all can be accessed simultaneously. In union the memory is allocated
for the longest member in the union so that all the members in the union can share the
allocated memory one at a time.
Example:
union product
{
int quantity;
float price;
char code;
} p1;
In the above the memory is allocated based on the longest data type float. Thus 4 bytes will be
allocated and all members in the union share that memory.
Example:
/unions example*/
void main()
{
union samp
{

CSE, RIT Page 10


char color;
int size;
}shirt;
shirt.color=‟r‟;
printf (“%c\n”,shirt.color);
shirt.size=12;
printf(“%d\n”,shirt.size);
}
Thus at a time only one member can be accessed. If we have a statement as follows
shirt.size=12;
printf(“%d %c\n”, shirt.size, shirt.color);

Then the output will be


12 garbage character
EXAMPLE-2( ACCESSING UNION MEMBERS)
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we
wish to access.
union Data
{
int i;
float f;
char str[20];
};
void main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
}
OUTPUT:
data.i : 10
data.f : 220.500000
data.str : C Programming

EXAMPLE-2
#include <stdio.h>
union test {
int x, y;
};
void main()
CSE, RIT Page 11
{
// A union variable t
union test t;
t.x = 2; // t.y also gets value 2
printf("After making x = 2:\n x = %d, y = %d\n\n",t.x, t.y);

t.y = 10; // t.x is also updated to 10


printf ("After making y = 10:\n x = %d, y = %d\n\n",t.x, t.y);
}

OUTPUT:
After making x = 2:
x = 2, y = 2
After making y = 10:
x = 10, y = 10

The differences between structure and union are ,


Structure Union
1.The keyword struct is used to define a 1. The keyword union is used to define a
structure union.

2. When a variable is associated with a 2. When a variable is associated with a union,


structure, the compiler allocates the memory the compiler allocates the memory by
for each member. The size of structure is considering the size of the largest memory. So,
greater than or equal to the sum of sizes of its size of union is equal to the size of largest
members. The smaller members may end with member.
unused slack bytes.
3. Each member within a structure is assigned 3. Memory allocated is shared by individual
unique storage area of location. members of union.

4. The address of each member will be in 4. The address is same for all the members of a
ascending order This indicates that memory for union. This indicates that every member begins
each member will start at different offset at the same offset value.
values.
5 Altering the value of a member will not 5. Altering the value of any of the member will
affect other members of the structure. alter other member values.

6. Individual member can be accessed at a time 6. Only one member can be accessed at a time.

7. Several members of a structure can initialize 7. Only the first member of a union can be
at once. initialized.

CSE, RIT Page 12


Bit Fields:

We have been using integer field of size 16 bits to store data. There are occasions where
data items require much less than 16 bits space. In such cases, we waste memory space.

A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A word
can therefore be divided into a number of bit fields. The name and size of bit fields are defined
using a structure. The general form of bit field is:

Struct tag-name
{
Data-type name1: bit-length;
Data-type name2: bit-length;
……
……
Data-type nameN: bit-length;
}
The data-type is either int or unsigned int or signed int and the bit-length is the number of bits
used for the specified name.

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
0

nameN ………. name 2 name 1

EXAMPLE: ( A SIMPLE REPRESENTATION OF DATE WITHOUT USING


BITFIELDS)

#include <stdio.h>
// A simple representation of the date
struct date {
unsigned int d;
unsigned int m;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2020 };

CSE, RIT Page 13


printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}

OUTPUT: (in 32-bit compiler)

Size of date is 12 bytes

Date is 31/12/2020

( A SIMPLE REPRESENTATION OF DATE USING BITFIELDS)

Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12, we can
optimize the space using bit fields.

#include <stdio.h>
struct date {
unsigned int d : 5;
unsigned int m : 4;
unsigned int y;
};
void main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2020 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}

OUTPUT:

(in 32-bit compiler)

Size of date is 8 bytes

Date is 31/12/2020

TYPEDEF

The C programming language provides a keyword called typedef, which you can use to
give a type a new name. You can use typedef to give a name to user defined data type as well.
For example you can use typedef with structure to define a new data type and then use that data
type to define structure variables directly as follows:

CSE, RIT Page 14


struct date
{
int day;
int mm;
int yy;
};
typedef struct date d;

EXAMPLE:

/*typedef example */
#include <stdio.h>
void main()
{
struct date
{
int day;
int mm;
int yy;
};
typedef struct date d;
struct student
{
int rno;
char name[20];
d jod; /* usage of typedef */
}s;
printf("\nEnter roll no: ");
scanf("%d",&s.rno);
printf("\n Enter name: ");
scanf("%s",s.name);
printf("\n Enter date of joining dd mm yy: ");
scanf("%d%d%d", &s.jod.day,&s.jod.mm,&s.jod.yy);
printf("\nno is %d", s.rno);
printf("\nname is %s",s.name);
printf("\njoining date %d-%d-%d",s.jod.day,s.jod.mm,s.jod.yy);
getch();
}
Output:
Enter Roll no: 100
Enter name: sastry

CSE, RIT Page 15


Enter date of joining dd mm yy: 01 01 08
no is 100
name is sastry
joining date 1-1-8

FILE HANDLING IN C:

A file is a collection of bytes stored on a secondary storage device.

• When a program is terminated, the entire data is lost. Storing in a file will preserve your
data even if the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of
the file using a few commands in C.
• You can easily move your data from one computer to another without any changes.
• When accessing files through C, the first necessity is to have a way to access the files.
For C File I/O you need to use a FILE pointer, which will let the program keep track of
the file being accessed. For Example:
FILE *fp;

Types of Files:

When dealing with files, there are two types of files you should know about: Text files, Binary
files
1. Text files
• Text files are the normal .txt files. You can easily create text files using any simple text
editors such as Notepad.
• When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold a higher amount of data, are not readable easily, and provides better security
than text files.

CSE, RIT Page 16


FILE OPERATIONS:

• File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a
file.

• Creation of the new file

• Opening an existing file

• Reading from the file

• Writing to the file

• Deleting the file

Defining and Opening a file:

If we want to store data in a file in the secondary memory, we must specify certain things about
the file, to the operating system. They include:

1. Filename
2. Data structure
3. Purpose

Following is general format for declaring and opening a file:

FILE *fp;

fp=open(“filename”,”mode”);

The first statement declares the variable fp as a “pointer to the data type FILE. The second
statement opens the file named filename and assigns an identifier to the FILE type pointer fp.
This pointer which contains all the information about the file is subsequently used as a
communication link between the system and the program.

 filename is a string that holds the name of the file on disk


 mode is a string representing how you want to open the file.

 w - open for writing (file need not exist)


 r - open the file for reading only.
 a - open for appending (file need not exist)
 r+ - open for reading and writing, start at beginning

CSE, RIT Page 17


 w+ - open for reading and writing (overwrite file)
 a+ - open for reading and writing (append if file exists)
Here's a simple example of using fopen:
FILE *fp;
fp=fopen("test.txt", "r");
This code will open test.txt for reading in text mode. To open a file in a binary mode you
must add a b to the end of the mode string; for example, "rb" (for the reading and writing modes,
you can add the b either after the plus sign - "r+b" - or before - "rb+")

Important file handling functions that are available in the C library.

Function name Operation


fopen() Creates new file for use & Opens an existing file for use.
fclose() Closes a file which has been opened for use
fgetc() Reads a character from a file
fputc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current passion in the file(in terms of bytes from the start)
rewind() Sets the position to the beginning of the file.

Closing a file:

A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from from the buffers and
all links to the file are broken.

fclose(file_pointer);

Example: (file1.c)
#include <stdio.h>
main()
{
FILE *fp;
fp = fopen(“test.txt", "w"); /* file(test.txt) opening in write mode*/
fprintf(fp, "This is testing...\n");
fclose(fp;);
}
CSE, RIT Page 18
This will create a file test.txt in and will write This is testing in that file.
Output at file(test.txt):
Hello, This is testing...

Example:
Program to create a data file containing student records*/

#include<stdio.h>
main()
{
FILE *fp;
int stno;
char stname[10];
int m1,m2,m3,n,i;
fp=fopen("stu.dat","w");
printf("enter no of students: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nstno: ");
scanf("%d",&stno);
printf("stname: ");
scanf("%s",stname);
printf("m1 m2 m3: ");
scanf("%d%d%d",&m1,&m2,&m3);
fprintf(fp,"%d %s %d %d %d\n",stno,stname,m1,m2,m3);
}
fclose(fp);
getch();
}

Output:
enter no of students: 2
stno: 101
stname: xyz
m1 m2 m3: 90 80 95
101 xyz 90 80 95
stno: 102
stname: pqr
m1 m2 m3: 88 87 89
102 pqr 88 87 89

CSE, RIT Page 19


Input / Output operations on Files

The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.

The routine getc(fp) is similar to getchar()


and putc(c,fp) is similar to putchar(c).

NOTE: You can use fgetc() and fputc() just in the same way as that of getc() and putc() functions.
Thus the statement

c = getc(fp);

reads the next character from the file referenced by fp and the statement

putc(c,fp);

writes the character c into file referenced by fp.

/* file1.c: Display contents of a file on screen */

Example program: (fgetc usage)


#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
fp = fopen( "file1.c", "r" );
c = fgetc( fp ) ;
while ( c != EOF )
{
putchar( c );
c = fgetc ( fp );
}
fclose( fp );
}
Output: (from file1.c)
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("test.txt", "w");
fprintf(fp,"Hello, This is testing...\n");
CSE, RIT Page 20
fclose(fp);
}
Another Example program: (putc and getc usage)
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
char c;
clrscr();
printf("input:\n");
f1 = fopen("file3","w"); /* open file input*/
while((c=getchar())!=EOF) /* get character from keyboard*/
putc(c,f1); /* write a character to file3*/
fclose(f1); /* close the file*/
f1=fopen("file3","r"); /* re open the file*/
printf("output:\n");
while((c=getc(f1))!=EOF) /* display character on screen*/
printf("%c",c);
fclose(f1);
getch();
}
Output:
input:
hai hello, this is nec....Ece.b students designed me..^Z
output:
hai hello, this is nec....Ece.b students designed me..

The getw and putw functions

The getw and putw are integer-oriented functions. They are similar to the getc and putc
functions and are used to read and write integer values. These functions would be useful when
we deal with only integer data. The general form of getw and putw are:

putw(integer, fp);
getw(fp);

Example program:
/*usage of getw, putw functions....*/
#include<stdio.h>
#include<conio.h>
void main()
{

CSE, RIT Page 21


FILE *f1,*f2,*f3;
int number,i;
clrscr();
printf("Contents of DATA file:\n\n");
f1=fopen("DATA","w");
for(i=1;i<=30;i++)
{
scanf("%d",&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);

f1=fopen("DATA","r");
f2=fopen("EVEN","w");
f3=fopen("ODD","w");
while((number=getw(f1))!=EOF)
{
if(number%2==0)
{
putw(number,f2);
}
else
putw(number,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);

f2=fopen("EVEN","r");
f3=fopen("ODD","r");

printf("\n contents of ODD file\n");


while((number=getw(f3))!=EOF)
printf("%4d",number);
printf("\n contents of EVEN file\n");
while((number=getw(f2))!=EOF)
printf("%4d",number);
fclose(f2);
CSE, RIT Page 22
fclose(f3);
getch();
}
Output:
Contents of DATA file:
1 2 3 4 5 6 7 8 9 10 11 -1
contents of ODD file
1 3 5 7 9 11
contents of EVEN file
2 4 6 8 10

The fprintf and fscanf Functions

The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and fscanf functions, except of course that they work on files. The first argument of these
functions is a file pointer which specifies the file to be used. The general form of fprintf is

fprintf(fp, “control strings”,list);

where fp is file pointer associated with a file that has been opened for writing.
The control strings contains output specifications for the items in the list. (%d,%f,%s,%u,%e,
etc)
The list may include variables, constants and strings.

example is fprintf(f1,”%s %d %f”, name, age, percentage);


here f1 is file pointer.
The general form of fprintf is

fscanf(fp, “control strings”,list);

example is fprintf(f1,”%s %d %f”, name, &age, &percentage);

Example program:
/*usage of fprintf,fscanf functions....*/
#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;

CSE, RIT Page 23


int number,quantity,i;
float price,value;
char item[10],filename[10];
printf("input file name:\n");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("Input inventary data\n");
printf("itemname number price quantity \n");
for(i=1;i<=3;i++)
{
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("itemname number price quantity value\n");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;
fprintf(stdout,"%-8s %7d %8.2f %8d
%11.2f\n",item,number,price,quantity,value);
}
fclose(fp);
getch();
}
Output:
Input file name:
samplefile
Input inventary data
itemname number price quantity
soap 100 36 20
dettol 101 76 15
pen 102 25 50

itemname number price quantity value


soap 100 36.00 20 720.00
dettol 101 76.00 15 1140.00
pen 102 25.00 50 1250.00
CSE, RIT Page 24
Another example

/*usage of fprintf,fscanf functions....*/


#include<stdio.h> #include<conio.h>
void main()
{
FILE *fp;
char name[20],filename[20];
clrscr();
printf("enter file name:");
scanf("%s",filename);
fp=fopen(filename,"w");
printf("enter ur name: \n");
fscanf(stdin,"%s ",name); /* reading data from keyboard(stdin) */
fprintf(fp,"hai %s",name); /* printing data into file */
printf("hai %s",name); /* printing data into console(monitor)*/
fclose(fp);
getch();
}
Output:
enter file name: sample.c
enter ur name:
omprakash ^Z
hai omprakash

Note: u can observe output in sample.c file also

Random access file Operations in c.

There is no need to read each record sequentially, if we want to access a particular record.C
supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()
1.fseek() :
It is used to move the reading control to different positions using fseek function.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position.This is attached
with L because this is a long integer.

CSE, RIT Page 25


Pointer position:
This sets the pointer position in the file.
Value pointer position
0 Beginning of file.
1 Current position
2 End of file
1) fseek( p,10L,0)

0 means pointer position is on beginning of the file,from this statement pointer position is
skipped 10 bytes from the beginning of the file.

2)fseek( p,5L,1)

1 means current position of the pointer position.From this statement pointer position is
skipped 5 bytes forward from the current position.

3)fseek(p,-5L,1)

From this statement pointer position is skipped 5 bytes backward from the current
position.

Example Program:
Write a program to read last „n‟ characters of the file using appropriate file functions.
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{
printf("Enter value of n to read last „n‟ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}
}
fclose(fp);
getch();
}

CSE, RIT Page 26


2.ftell() :
This function returns the value of the current pointer position in the file.The value
is count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.

Example Program: ( ftell() )


#include<stdio.h>

int main()

/* Opening file in read mode */

FILE *fp = fopen("test.txt","r");

/* Reading first string */

char string[20];

fscanf(fp,"%s",string);

/* Printing position of file pointer */

printf("%ld", ftell(fp));

return 0;

Output : Assuming test.txt contains “Someone over there ….”.

3. rewind():
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer

Example Program ( Assume the file “file.txt” contains the text “this is a simple text”
#include<stdio.h>
#include<conio.h>

CSE, RIT Page 27


void main(){
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF){
printf("%c",c);
}

rewind(fp);//moves the file pointer at beginning of the file

while((c=fgetc(fp))!=EOF){
printf("%c",c);
}

fclose(fp);
getch();
}
Output:

this is a simple text this is a simple text

Few Examples on File handing in C:

1. write a C program to copy the contents of one file into another file.

#include <stdio.h>
#include <stdlib.h> // For exit()

int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;

printf("Enter the filename to open for reading \n");


scanf("%s", filename);

// Open one file for reading


fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
CSE, RIT Page 28
}

printf("Enter the filename to open for writing \n");


scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt

2. Write a program to merge to files and copy it in to third file.

#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fs1, *fs2, *ft;
char ch, file1[20], file2[20], file3[20];
printf("Enter name of first file\n");
gets(file1);
printf("Enter name of second file\n");
gets(file2);

printf("Enter name of file which will store contents of two files\n");


gets(file3);
CSE, RIT Page 29
fs1 = fopen(file1,"r");
fs2 = fopen(file2,"r");
if( fs1 == NULL || fs2 == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
getch();
exit(EXIT_FAILURE);
}
ft = fopen(file3,"w");
if( ft == NULL )
{
perror("Error ");
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fs1) ) != EOF )
fputc(ch,ft);
while( ( ch = fgetc(fs2) ) != EOF )
fputc(ch,ft);
printf("Two files were merged into %s file successfully.\n",file3);
fclose(fs1);
fclose(fs2);
fclose(ft);
return 0;
}

CSE, RIT Page 30

You might also like