You are on page 1of 33

Introduction to Programming With C – 19CSE13/23 Module 4

Module 4 STRUCTURES
Basic of structures, structures and Functions, Array of structures, structure Data types, type definition, Defining,
opening and closing of files, Input and output operations, Programming examples and exercises.

Course Outcome:
Explain Structure and File I/O operations.

Definition: A structure is defined as a collection of data of same/different data types. All data items thus
grouped are logically related and can be accessed using variables. Thus, structure can also be defined as a
group of variables of same or different data types. The variables that are used to store the data are called
members of the structure or fields of the structure. In C, the structure is identified by the keyword struct.

Ex: The structure definition to hold the student information such as name, roll_number and average_marks
can be written as shown below:

Structure declaration
“How to declare a structure?” As variables are declared before they are used in the function, the structures are
also should be declared before they are used. A structure can be declared using three different ways as shown
below:
Definition:
1. The structure definition with tag name is called tagged structure. The tag name is the name of
the structure. The syntax of tagged structure is shown below:

Struct tag_name v1,v2,v3 …… vn;


For example, consider the following structure definition:

Struct student cse,ise;


Introduction to Programming With C – 19CSE13/23 Module 4

2. Structure without a tag is where the declaration is done immediately after the definition without using
the tag name.
struct
{
type1 member1;
type2 member2;
Curly braces …… ……
…… ……
} v1, v2,…..vn ; Note: semicolon is must at the end of variables

Structure variables

3. Type-Defined Structure: The structure definition associated with keyword typedef is called
type- defined structure. This is the most powerful way of defining the
structure.

typedef is the keyword added to the beginning of the definition


struct is the keyword which tells the compiler that a structure is being defined.
member1, member2,….. are called members of the structure. They are also called fields of the
structure.
The members are declared within curly braces.
The closing brace must end with type definition name (TYPE_ID in the syntax shown) which in turn
ends with semicolon. Note that TYPE_ID is not a variable; instead it is a user-defined data type.
For example, the type-defined structure definition is shown below:

Since STUDENT is the type created by the user, it can be called as user-defined data type. From this
point onwards we can use STUDENT as data type and declare the variables. For example, consider the
following declaration:

This statement declares that the variables cse and ise are variables of type STUDENT.
Structure initialization
Assigning the values to the structure members is known as structure initialization. All the elements that
are being initialized are enclosed within the braces { and }.
Introduction to Programming With C – 19CSE13/23 Module 4

syntax:
struct tag_name variable = {v1,v2,..................vn};

Example:
struct student
{
char name[ ];
int usn;
float avg;
};
struct student std1 = {“raju” , 18, 87.5};

Values initialized to studentd1 (ie std1)

Accessing members of a structure


The member of a structure is identified and accessed using the dot operator “.” The dot
operator connects the member name to the name of its containing structure.
syntax
struct_variable.membername;

Example
struct student
{
char name[ ];
int usn;
float avg;
};
struct student std1 = {“raju” , 18, 87.5};
The members of structure variable std1 can be accessed using dot operator as follows:
std1.name access the string “rama”
std1.usn access the usn 18
std1.avg access the value 87.5

Write a program to read and write a structure called employee with members as name, age and salary.
#include<stdio.h>
struct employee
{
char name[ ];
int age;
float salary;
};
void main( )
{
struct employee e1;
printf(“Enter employee name\n”);
gets(e1.name);
Introduction to Programming With C – 19CSE13/23 Module 4

printf(“Enter employee age\n”);


scanf(“%d”,&e1.age);
printf(“enter salary\n”);
scanf(“%f”, &e1.salary);
printf(“name is %s\n”,e1.name);
printf(“age is %d\n”,e1.age);
printf(“salary is %f\n”,e1.salary);
}

Array of a structure
In C language as we can have an array of integers, we can also have an array of structures.
Example: suppose you want to store the information of 10 students consisting of name and usn. The structure
definition can be written as shown below:
struct student
{
char name[ ] ;
int usn;
};
To store the information of 10 students, the structure variable has to be declared as follows:
struct student s[10];
The general syntax for structure array declaration is:
struct tag_name arrayname[size];

Write a C program to store and print name, usn, subject and IA marks of 10 students using structure
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
Introduction to Programming With C – 19CSE13/23 Module 4

}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}

Structure and Functions


A structure variable can be passed to the function as an argument just like normal variable are passed to
the function.
Example:
Program to pass structure variable to a function.
#include<stdio.h>
struct student
{
char name[20];
int usn;
};
void main()
{
void display( struct student s);
struct student s1;
printf(“Enter the student name\n”);
gets(s1.name);
printf(“Enter student usn\n”);
scanf(“%d\n”, &s1.usn);
displat(s1);
}
Void display(struct student s)
{
puts(“name is” s.name);
printf(“usn is” s.usn);
}
Type Definition
The typedef is a keyword using which the programmer can create a new data type name for an already
existing data type name. Thus the purpose of typedef is to redefine or rename the name of an existing data type.
Syntax:
typedef dat_type newname;
Example:
typedef int percentage, usn;
typedef float salary;
Introduction to Programming With C – 19CSE13/23 Module 4

the new names that are given for the already existing data types are called user defined data types. In the above
example percentage, usn and salary are user defined data types. The user defined data types can be used to
describe variables as
typedef int percentage, usn;
percentage p1, p2, p3;
usn u1,u2,u3;

program to compute simple interest that uses various typedef definition.


#include<stdio.h>
typedef float principle_amount;
typedef float time_period;
typedef float rate_of_intrest;
void main()
{
principle_amount p,si;
time_period t;
rate_of_intrest r;
printf(“Enter p t and r\n);
scanf(“%f %f %f”, &p,&t,&r);
si = (p*t*r)/100;
printf(“si=%f”, si);
}

The structure defined using the keyword typedef is called type defined structure.
typedef struct
{
datatype member1;
datatype member2;
---------
---------
}structure_name;

Example:
typedef struct
{
char name[20];
int usn;
}student;
Here „student‟ is the new data type using which variables can be declared as
student s1,s2;
The typedef structure can also be defined as
Example:
struct student
{
char name[20];
int usn;
Introduction to Programming With C – 19CSE13/23 Module 4

}
typedef struct student VTU
VTU s1, s2;

Nested structures
A structure can be member of another structure. This is called as a nested structure ie. A structure which
includes another structure is called a nested structure.
Example:
Consider the structure date which includes members like date, month and yesr
struct date
{
int dd;
int mm;
int yyyy;
};
The above structure date can be used in the structure employee as
struct employee
{
char name[20];
int emp_id;
float salary;
struct date doj;
};
In the above example, the date structure is nested within employee structure. in order to access the member of a
date structure, we need to first create a variable of employee structure.
struct employee e1;
Now we can access member of date structure as
e1.doj.dd;
e1.doj.mm;
e1.doj.yyyy;
Introduction to Programming With C – 19CSE13/23 Module 4

Question paper solution

1. How structure is different from an array? Explain declaration of a structure with an example.
An array is a collection of elements of similar data types. An array behaves like a built in data type. All
we have to do is to declare an array variable and use it.
Ex: int a[10];
A structure is a collection of elements of similar or dissimilar data types. In case of a structure, first we
have to design and declare a data structure before the variables of that type are declared and used.
Ex:
struct student
{
char name[20];
int rollno;
float marks;
};

2. Explain with an example, how to create a structure using ‘typedef’


The structure defined using the keyword typedef is called type defined structure.
typedef struct
{
datatype member1;
datatype member2;
---------
---------
}structure_name;

Example:
typedef struct
{
char name[20];
int usn;
}student;

Here „student‟ is the new data type using which variables can be declared as
student s1,s2;

The typedef structure can also be defined as


Example:
struct student
{
char name[20];
int usn;
}
typedef struct student VTU
VTU s1, s2;
Introduction to Programming With C – 19CSE13/23 Module 4

3. Write a C program to input the following details of „N‟ students using structure: Roll No: integer,
Name: string Marks: float Grade: char. prints the names of the students with marks >-70%.
#include <stdio.h>
struct student
{
char name[50];
int roll;
int marks;
char grade[2];
};
int main()
{
struct student s[100];
int i, n, marks;
printf("Enter the number of students:\n");
scanf("%d", &n);
printf("Enter information of students:\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("\nEnter roll number \n");
scanf("%d",&s[i].roll);
printf("Enter name: ");
scanf("%s",&s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade: ");
scanf("%s",&s[i].grade);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("Roll number: %d\n", s[i].roll);
printf("Name: %s\n", s[i].name);
printf("Marks: %d\n", s[i].marks);
printf("Grade: %s\n", s[i].grade);
printf("\n");
}
printf(“Names of students with marks greater than 75 are\n”);
for(i=0;i<n;i++)
{
if(s[i].marks >=75)
puts(s[i].name);
}
Introduction to Programming With C – 19CSE13/23 Module 4

4. What is a structure? Explain the C syntax of structure declaration with example.


A structure is a collection of one or more variables of similar or dissimilar data types, grouped together
under a single name. A structure is a derived data type containing multiple variables of same or different
data types.
The general format for structure definition is
struct tag_name
{
datatype member1;
datatype member2;
------------------------
------------------------
};
The word struct is a keyword in C and the tag_name is used to declare structure variables.
Example:
struct student
{
char name[10];
int rollno;
float marks;
};
Student is the tag_name.

5. Write a C program to pass structure variable as function argument.


A structure variable can be passed to the function as an argument just like normal variable are passed to the
function.
Example:
Program to pass structure variable to a function.
#include<stdio.h>
struct student
{
char name[20];
int usn;
};
void main()
{
void display( struct student s);
struct student s1;
printf(“Enter the student name\n”);
gets(s1.name);
printf(“Enter student usn\n”);
scanf(“%d\n”, &s1.usn);
displat(s1);
}
Introduction to Programming With C – 19CSE13/23 Module 4

void display(struct student s)


{
puts(“name is” s.name);
printf(“usn is” s.usn);
}

6. Write a C program to store and print name, usn, subject and IA marks of students using
structure.
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}
Introduction to Programming With C – 19CSE13/23 Module 4

7. Define a STRUCTURE. Explain structure with syntax and example.


A structure is a collection of one or more variables of similar or dissimilar data types, grouped
together under a single name. A structure is a derived data type containing multiple variables of same or
different data types.
The general format for structure definition is
struct tag_name
{
datatype member1;
datatype member2;
------------------------
------------------------
};
The word struct is a keyword in C and the tag_name is used to declare structure variables.
Example:
struct student
{
char name[10];
int rollno;
float marks;
};
Student is the tag_name.

8. Write a program to maintain a record of “n” student details using an array of structures with four
fields (Roll No, name, marks, and grade). Each field must be of appropriate data type. Print the
marks of the student name as input.
#include <stdio.h>
struct student
{
char name[50];
int roll;
int marks;
char grade[2];
};
int main()
{
struct student s[100];
char searchname[50];
int i, n;
printf("Enter the number of students:\n");
scanf("%d", &n);
printf("Enter information of students:\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1);
printf("\nEnter roll number \n");
Introduction to Programming With C – 19CSE13/23 Module 4

scanf("%d",&s[i].roll);
printf("Enter name: ");
scanf("%s",&s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("Enter grade: ");
scanf("%s",&s[i].grade);
printf("\n");
}
printf("Displaying information of students:\n\n");
for(i=0;i<n;++i)
{
printf("\nFor %d Student\n",i+1); printf("Roll
number: %d\n", s[i].roll); printf("Name:
%s\n", s[i].name); printf("Marks: %d\n",
s[i].marks); printf("Grade: %s\n", s[i].grade);
printf("\n");
}
printf("Enter the Search Name of the Student :");
scanf("%s",&searchname);
for(i=0;i<n;++i)
{
if (strcmp( s[i].name, searchname ) == 0)
{
printf("%s is in the List and her marks is %d\n",s[i].name,s[i].marks);
getch();
return 0;
}
}
printf("%s Student is not in the List\n", searchname);
getch();
return 0;
}

9. Differentiate between structures and unions.


The difference between structure and union is,
1.
The amount of memory required to store a structure variable is the sum of the size of all
the members.
On the other hand, in case of unions, the amount of memory required is always equal to
that required by its largest member.
2.
In case of structure, each member have their own memory space
In union, one block is used by all the member of the union.
3.
Introduction to Programming With C – 19CSE13/23 Module 4

Example for structure:


struct stu
{
char c;
int l;
float p;
};
Example for union
union emp
{
char c;
int l;
float p;
};
In the above example size of the structure stu is 7 and size of union emp is 4.

10. What is a structure data type? Explain.


A structure is a collection of one or more variables of similar or dissimilar data types, grouped
together under a single name. A structure is a derived data type containing multiple variables of same or
different data types.
The general format for structure definition is
struct tag_name
{
datatype member1;
datatype member2;
------------------------
------------------------
};
The word struct is a keyword in C and the tag_name is used to declare structure variables.
Example:
struct student
{
char name[10];
int rollno;
float marks;
};
Student is the tag_name.

11. Show how a structure variable is passed as a parameter to a function, with an example.
A structure variable can be passed to the function as an argument just like normal variable are passed to the
function.
Example:
Program to pass structure variable to a function.
#include<stdio.h>
struct student
Introduction to Programming With C – 19CSE13/23 Module 4

{
char name[20];
int usn;
};
void main()
{
void display( struct student s);
struct student s1;
printf(“Enter the student name\n”);
gets(s1.name);
printf(“Enter student usn\n”);
scanf(“%d\n”, &s1.usn);
displat(s1);
}
void display(struct student s)
{
puts(“name is” s.name);
printf(“usn is” s.usn);
}

12. Explain the concept of array of structures, with a suitable C program.


In C language as we can have an array of integers, we can also have an array of structures.
Example: suppose you want to store the information of 10 students consisting of name and usn.
The structure definition can be written as shown below:
struct student
{
char name[ ] ;
int usn;
};
To store the information of 10 students, the structure variable has to be declared as follows:
struct student s[10];
The general syntax for structure array declaration is:
struct tag_name arrayname[size];

Write a C program to store and print name, usn, subject and IA marks of 10 students using structure
#include<stdio.h>
struct student
{
char name[20];
int usn;
char subject[20];
float marks;
};
void main()
{
struct student s[10];
Introduction to Programming With C – 19CSE13/23 Module 4

int i;
for(i=0; i<10;i++)
{
printf(“Enter student name\n”);
gets(s[i].name); printf(“
Enter usn\n”); scanf(“%d”,
&s[i].usn); printf(“Enter the
subject\n”);
gets(s[i].subject);
printf(“Enter the marks\n”);
scanf(“%d”, &s[i].marks);
}
printf(“students details are\n”);
for(i=0;i<10;i++)
{
puts(s[i].name);
printf(“%d”,s[i].usn);
puts(s[i].subject);
printf(“%d”,s[i]..marks);
}
}
Introduction to Programming With C – 19CSE13/23 Module 4

FILE HANDLING
A file is defined as a collection of data stored on the secondary device such as hard disk. An input file
contains the same items we might have typed in from the keyboard. An output file contains the same
information that might have been sent to the screen as the output from our program.
The advantages of creating and using an input file are
It is very convenient to read input from a data file than to enter data interactively using the keyboard.
It is very difficult to input large volume of data through terminals
It is time consuming to enter large volume of data using keyboard.
When we are entering the data through the keyboard, if the program is terminated for any of
the reason or computer is turned off, the entire input data is lost.
To overcome all these problems, the concept of storing the data in disks was introduced. Here, the data can be
stored on the disks; the data can be accessed as and when required and any number of times without
destroying the data. The data is stored on the disk in the form of a file.

Creating a data file


A data file also called text file can be created as shown below:
When we use Linux/Unix operating system, we can invoke “vi” editor
When we are using Windows operating system, we can invoke notepad or Microsoft word.
After invoking the editor, type the data or text and save the data or text into a file. The file along with
data is stored in hard disk permanently till we physically delete it.
When we type the text, we may enter any sequence of characters such as letters, digits, symbols such as;
: ? # $ and so on and insert tab characters, spaces and newline characters. All these symbols we store in
a text file.
The various steps to be performed when we do file manipulations are shown below:

Declare a file pointer variable


What is a FILE? Where it is defined?
FILE is type defined structure and it is defined in a header file “stdio.h”. So, FILE can be used as a data
type.
It is derived using basic data types such as short, char etc., with the help of the keyword struct.
FILE is a derived data type.
FILE is not a basic data type in C language.

How to declare a file pointer variable?


A file pointer variable can be declared using the derived data type FILE as shown below:
Introduction to Programming With C – 19CSE13/23 Module 4

where FILE *fp;

FILE is the derived data type defined in the header file “stdio.h”. Since, FILE is defined in “stdio.h”, we
have to include the file “stdio.h” in the beginning of the program.
Since fp is a pointer variable, it is the responsibility of the programmer to point fp to the opened file.
The program segment that shows the declaration of a file pointer is shown below:
#include <stdio.h>
void main()
{
FILE *fp; /* Here, fp is a pointer to a structure FILE */
………. /* File operations */
……….
}

Modes of a file
The various modes in which a file can be opened successfully along with meanings are shown below:

Opening and closing the files


fopen()
fopen() is a function using which
an existing file can be opened only in read mode using mode “r”.
an existing file can be erased and treat it as a new file. This can be done by opening the file in write
mode using “w”.
a new file can be created to write information into the file. This can be done by opening the file in write
mode using “w”.
an existing/non-existing file can be opened so that new data can be written at the end of the file. This is
called appending. This can be done by opening the file in append mode using “a”.
The syntax is shown below:
Introduction to Programming With C – 19CSE13/23 Module 4

Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”

Return values The function may return the following:


A file pointer to the beginning of the opened file, if the file is opened successfully.
NULL otherwise.
If the file pointer fp is not NULL, the necessary data can be accessed from the specified file. If a file cannot be
opened successfully for some reason, the function returns NULL. We can use this NULL character to
test whether a file has been successfully opened or not using the statement:
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}

fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
If a file is closed successfully, 0 is returned otherwise EOF is returned.
The syntax is shown below:
fclose(fp);

Open the file for reading


The steps to open a file in read mode are shown below:
Invoke the function fopen() with two arguments
The first argument is the file name which has to be opened
Second argument is the mode in which the file has to be opened
The function fopen() returns NULL if file does not exist. Otherwise, it returns pointer to the opened file.
The following set of instructions are used to open the file “input.txt”
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “r”); // Open the file in read mode
Introduction to Programming With C – 19CSE13/23 Module 4

When the function fopen() is executed and if the file does not exist, the function fopen() returns NULL. In this
situation, we display the message “Error in opening the file” as shown below:
if (fp == NULL) // If the file does not exist
{
printf(“Error in opening the file”);
exit(0);
}
If the file is existing, the function fopen() returns a pointer to the file which points to the beginning of the file
and it is copied into file pointer variable fp as shown in figure below:
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ

EOF
fp

The final program segment to open an existing/non-existing file can be written as shown below:
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “r”); // Open the file
if (fp == NULL) // If file does not exist
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
/* Read the opened file and perform various operations
………..
fclose(fp); // close the file

Open the file for writing


To open a file for writing, we use the same procedure as given in previous section. But, the file mode has to be
changed from “r” to “w”. Suppose, the file “input.txt” has to be opened for writing. We can use the following
instructions.
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “w”); // Open the file in write mode
When fopen() is executed in write mode “w”, three situations may arise.
1) Read only file exists.
2) Normal file exists.
3) File does not exist.

Case 1: Read only file exists: Suppose the read only file “input.txt” is opened for writing. Since the file is read
only, it should not be modified. So, the function fopen() returns NULL. It indicates that it is an error and the file
should not be opened. The code for this can be written as shown below:
if (fp == NULL)
{
Introduction to Programming With C – 19CSE13/23 Module 4

printf(“Error in opening the file”);


exit(0);
}
Case 2: Normal file exists: Suppose, the file “input.txt” exists as shown below:
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ

EOF

Now, once fopen() is executed, the contents of the file are erased and file pointer points to the beginning of the
file as shown below:
input.txt

fp
Now, we can start writing into the file from fp onwards as if it is a new file. Suppose, a string “Subject videos
:www.gat.ac.in” is written into the file. The contents of the file are shown below:
input.txt
Welcome to C Programming Δ

EOF

So, when a normal file is opened in write mode, the contents of the given file are deleted. The file pointer points
to the beginning of the file and we can start writing the characters into the file. Now, the file pointer will always
points to the end of the file.
Case 3: File does not exist: Suppose, the file “input.txt” is opened for writing and the file does not exist. Now, a
new file “input.txt” is created and the function fopen() returns a pointer to the beginning of the file and it is stored
in the variable fp as shown below:

input.txt

fp
Now, we can start writing into the file from fp onwards. Suppose we write the string “Global Academy
of
Technology”, then the contents of the file is shown below:
Introduction to Programming With C – 19CSE13/23 Module 4
fp
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ

EOF

So, when a non-existing file is opened in write mode, a new file is created and we can write into the file. Now, the
file pointer will always points to the end of the file. The final program segment can be written as shown below:
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “w”); // Create the file
if (fp == NULL) // If file cannot be created
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
// write the data into the file
………..
fclose(fp); // close the file

Open the file for appending


To open a file for writing, we use the same procedure as we use in opening the file in read mode. But, the file
mode has to be changed from “r” to “a”. Suppose, the file “input.txt” has to be opened for appending. We can use
the following instructions.
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “a”); // Open the file in append mode
When fopen() is executed in append mode “a”, three situations may arise.
1) Read only file exists.
2) Normal file exists.
3) File does not exist.

Case 1: Read only file exists: Since the file is read only, it should not be modified. So, the function fopen() returns
NULL. It indicates that it is an error and the file should not be opened. The code for this can be written as shown
below:
if (fp == NULL)
{
printf(“Error in opening the file”);
exit(0);
}
So, when a read only file is opened in append mode, we cannot perform any operations on the file and hence
after displaying the message “Error in opening the file” the program is terminated.
Case 2: Normal file exists: Suppose, the file “input.txt” exists as shown below:
Introduction to Programming With C – 19CSE13/23 Module 4

input.txt
NEW HORIZON COLL

EOF

Now, once fopen() is executed, the file pointer points to the end of the file as shown below:
input.txt
NEW HORIZON COLL

fp

Now, we can start appending into the file from fp onwards as if it is a new file. The file after
appending a
sequence of characters “of Technology” is shown below:

fp
input.txt
NEW HORIZON COLLEGE OF ENGINEERINGΔ

EOF
So, when a normal file is opened in append mode, we can insert the characters at the end of the file. Now, the file
pointer will always points to the end of the file.
Case 3: File does not exist: Suppose, the file “input.txt” has to be opened for appending and the file does not
exist. Now, a new file “input.txt” is created and the function fopen() returns a pointer to the beginning of the file
and it is stored in the variable fp as shown below:
input.txt

fp
Now, we can start appending into the file from fp onwards. When the string “Global Academy of Technology”
is written into the file, the contents of the file are shown below:

So, when a non-existing file is opened in append mode, a new file is created and we can write into the file. Now,
the file pointer will always points to the end of the file as shown in above figure. The final program
segment can be written as shown below:
Introduction to Programming With C – 19CSE13/23 Module 4

#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “a”); // Open the file
if (fp == NULL) // If file cannot be appended
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
// append the data into the file
………..
fclose(fp); // close the file

I/O file functions


The three types of I/O functions to read from or write into the file
File I/O functions for fscanf() and fprintf()
File I/O functions for strings fgets() and fputs()
File I/O functions for characters fgetc() and fputc()

fscanf: The function of fscanf and scanf are exactly same. Only change is that scanf is used to get data input from
keyboard, whereas fscanf is used to get data from the file pointed to by fp. Because input is read from the file,
extra parameter file pointer fp has to be passed as the parameter. Rest of the functionality of fscanf remains same
as scanf. The syntax of fscanf() is shown below:
fscanf(fp, “format string”, list);
where
fp is a file pointer. It can point to a source file or standard input stdin. If fp is pointing to stdin, data is
read from the keyword. If fp points to source file, the data is read from the specified source file.
format string and list have the same meaning as in scanf() i.e., the variables specified in the list will
take the values from the file specified by fp using the specifications provided in format string.
The function returns EOF when it attempts to read at the end of the file; Otherwise, it returns
the number of items read in and successfully converted
Example:
fscanf(fp, “%d %s %f”, &id, name, &avg_marks);
Suppose, fp points to the source file. After executing above statement, the values for the variables id, name and
avg_marks are obtained from the file associated with file pointer fp. This function returns the number of items
that are successfully read from the file.

fprintf: The function of fprintf and printf are exactly same. Only change is that printf is used to display the data
onto the video display unit, whereas fprintf is used to send the data to the output file pointed to by fp. Since file
is used, extra parameter file pointer fp has to be passed as parameter. Rest of the functionality of fprintf
remains same as printf. The syntax of fprintf() is shown below:
fprintf(fp, “format string”, list);
where
fp is a file pointer associated with a file that has been opened for writing.
Introduction to Programming With C – 19CSE13/23 Module 4

format string and list have the same meaning as in printf() function i.e., the values of the variables
specified in the list will be written into the file associated with file pointer fp using the specifications
provided in format string.
Example:
fprintf(fp, “%d %s %f”, id, name, avg_marks);
After executing fprintf, the values of the variables id, name and avg_marks are written into the file associated
with file pointer fp. This function returns the number of items that are successfully written into the file.

C program to read n numbers from keyboard and write into a file

#include <stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“input.dat”, “w”); // Open the file in write mode
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while (scanf(“%d”, &num) != EOF) // 10 20 30 40 50 Cntl-z (Turbo)
{ // Cntl-d (linux)
fprintf(fp,“%d\n”, num); // The above data is written into
} // file : input.dat
fclose(fp);
}

C program to read n numbers from input file and display on the screen

#include <stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“input.dat”, “r”); // input.dat : 10 20 30 40 50
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while (fscanf(fp, “%d”, &num) > 0)
{ // Output
printf(“%d\n”, num); // 10 20 30 40 50
}
fclose(fp);
Introduction to Programming With C – 19CSE13/23 Module 4

C program to read student name and usn from two different files and write into a different file in the
sequence
#include <stdio.h>
void main()
{
FILE *fp1, *fp2, *fp3;
char name[20];
int usn;
fp1 = fopen(“studentname.txt”, “r”); // Open the name file in read mode
fp2 = fopen(“usn.txt”, “r”); // Open the usn file in read mode
fp3 = fopen(“output.txt”, “w”); // Open the file in write mode
for(;;)
{
if ( fscanf(fp1, “%s”, name) > 0) // read name from 1st file
{
if (fscanf(fp2, “%d”, &usn) > 0) // read name from 2nd file
{
fprintf(fp3,”%s %d\n”, name, usn); // write to 3rd file
}
else break;
}
else break;
}
fclose(fp1); /* close all the files */
fclose(fp2);
fclose(fp3);
}
Introduction to Programming With C – 19CSE13/23 Module 4

Question Paper Solution

1. Explain following file operations along with syntax and examples.


i.fopen() ii.fclose() iii.fscanf() iv.fprintf() v.fgets
fopen()
fopen() is a function using which
an existing file can be opened only in read mode using mode “r”.
an existing file can be erased and treat it as a new file. This can be done by opening the file in write
mode using “w”.
a new file can be created to write information into the file. This can be done by opening the file in write
mode using “w”.
an existing/non-existing file can be opened so that new data can be written at the end of the file. This is
called appending. This can be done by opening the file in append mode using “a”.
The syntax is shown below:

Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”

Return values The function may return the following:


A file pointer to the beginning of the opened file, if the file is opened successfully.
NULL otherwise.
If the file pointer fp is not NULL, the necessary data can be accessed from the specified file. If a file cannot be
opened successfully for some reason, the function returns NULL. We can use this NULL character to
test whether a file has been successfully opened or not using the statement:
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}

fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
Introduction to Programming With C – 19CSE13/23 Module 4

If a file is closed successfully, 0 is returned otherwise EOF is returned.


The syntax is shown below:
fclose(fp);

fscanf()
The function of fscanf and scanf are exactly same. Only change is that scanf is used to get data input from
keyboard, whereas fscanf is used to get data from the file pointed to by fp. Because input is read from the file,
extra parameter file pointer fp has to be passed as the parameter. Rest of the functionality of fscanf remains same
as scanf. The syntax of fscanf() is shown below:
fscanf(fp, “format string”, list);
where
fp is a file pointer. It can point to a source file or standard input stdin. If fp is pointing to stdin, data is
read from the keyword. If fp points to source file, the data is read from the specified source file.
format string and list have the same meaning as in scanf() i.e., the variables specified in the list will
take the values from the file specified by fp using the specifications provided in format string.
The function returns EOF when it attempts to read at the end of the file; Otherwise, it returns
the number of items read in and successfully converted
Example:
fscanf(fp, “%d %s %f”, &id, name, &avg_marks);
Suppose, fp points to the source file. After executing above statement, the values for the variables id, name and
avg_marks are obtained from the file associated with file pointer fp. This function returns the number of items
that are successfully read from the file.

fprintf()
The function of fprintf and printf are exactly same. Only change is that printf is used to display the data onto the
video display unit, whereas fprintf is used to send the data to the output file pointed to by fp. Since file is used,
extra parameter file pointer fp has to be passed as parameter. Rest of the functionality of fprintf remains same as
printf. The syntax of fprintf() is shown below:
fprintf(fp, “format string”, list);
where
fp is a file pointer associated with a file that has been opened for writing.
format string and list have the same meaning as in printf() function i.e., the values of the variables
specified in the list will be written into the file associated with file pointer fp using the specifications
provided in format string.
Example:
fprintf(fp, “%d %s %f”, id, name, avg_marks);
After executing fprintf, the values of the variables id, name and avg_marks are written into the file associated
with file pointer fp. This function returns the number of items that are successfully written into the file.

fgets()
The syntax of fgets() is shown below
ps = fgets(str, n, fp);
where
fp is a file pointer. It can point to a source file or standard input.
str is an array of characters
Introduction to Programming With C – 19CSE13/23 Module 4

n represents the number of characters to be read from the file.


If the operation is successful, it returns a pointer to the string otherwise it returns NULL
Example:
fgets(str, 10, stdin);

2. Write a C program to read the contents from the file called abc.txt, count the number of
characters, number of lines and number of words and output the same.
#include <stdio.h>

int main()
{
FILE *fp;
char filename[100];
char ch;
int linecount= 0, wordcount=0, charcount=0;
fp = fopen(“abc.txt”,"r");
if ( fp )
{
while ((ch=getc(fp)) != EOF)
{
if (ch != ' ' && ch != '\n')
{
++charcount;
}
if (ch == ' ' || ch == '\n')
{
++wordcount;
}
if (ch == '\n')
{
++linecount;
}
}
if (charcount > 0)
{
++linecount;
++wordcount;
}
}
else
{

printf("Failed to open the file\n");


}
printf("Lines : %d \n", linecount);
printf("Words : %d \n", wordcount);
printf("Characters : %d \n", charcount);
Introduction to Programming With C – 19CSE13/23 Module 4

getchar();
return(0);
}

3. Explain fputc(), fputs(), fgetc() and fgets functions with syntax.


fputc()
The C library function fputc(char, fp) writes a character (an unsigned char) specified by the argument
char to the specified stream and advances the position indicator for the stream
Syntax:
int fputc(int char, FILE *fp)
char -- This is the character to be written. This is passed as its int promotion.
fp -- This is the pointer to a FILE object that identifies the stream where the character is to be written.

Example:
#include <stdio.h>
int main ()
{
FILE *fp;
int ch;
fp = fopen("file.txt", "w+");
for( ch = 33 ; ch <= 100; ch++ )
{
fputc(ch, fp);
}
fclose(fp);
return(0);
}

fputs()
The C library function int fputs(const char *str, FILE *fp) writes a string to the specified stream up to but not
including the null character.
Syntax:
int fputs(const char *str, FILE *stream)
str -- This is an array containing the null-terminated sequence of characters to be written.
fp-- This is the pointer to a FILE object that identifies the stream where the string is to be written.
Example:
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt", "w+");
fputs("This is c programming.", fp);
fputs("This is a system programming language.", fp);
fclose(fp);
return(0);
}
Introduction to Programming With C – 19CSE13/23 Module 4

fgetc()
The C library function int fgetc(FILE *fp) gets the next character (an unsigned char) from the specified stream
and advances the position indicator for the stream.
Syntax:
int fgetc(FILE *fp)
fp -- This is the pointer to a FILE object that identifies the stream on which the operation is
to be performed.
Example:
#include <stdio.h>

int main ()
{
FILE *fp;
int c;
int n = 0;

fp = fopen("file.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
}
do
{
c = fgetc(fp);
if( feof(fp) )
{
break ;
}
printf("%c", c);
}while(1);

fclose(fp);
return(0);
}

fgets()
The C library function char *fgets(char *str, int n, FILE *fp) reads a line from the specified stream and stores
it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or
the end-of-file is reached, whichever comes first.
Syntax:
char *fgets(char *str, int n, FILE *fp)
tr -- This is the pointer to an array of chars where the string read is stored.
n -- This is the maximum number of characters to be read (including the final null-character). Usually,
the length of the array passed as str is used.
fp -- This is the pointer to a FILE object that identifies the stream where characters are read from.
Introduction to Programming With C – 19CSE13/23 Module 4

Example:
#include <stdio.h>
int main()
{
FILE *fp;
char str[60];
/* opening file for reading */
fp = fopen("file.txt" , "r");
if(fp == NULL)
{
perror("Error opening file");
return(-1);
}
if( fgets (str, 60, fp)!=NULL )
{
/* writing content to stdout */
puts(str);
}
fclose(fp);
return(0);
}

4. Explain fopen() anf fclose function.


fopen()
fopen() is a function using which
an existing file can be opened only in read mode using mode “r”.
an existing file can be erased and treat it as a new file. This can be done by opening the file in write
mode using “w”.
a new file can be created to write information into the file. This can be done by opening the file in write
mode using “w”.
an existing/non-existing file can be opened so that new data can be written at the end of the file. This is
called appending. This can be done by opening the file in append mode using “a”.
The syntax is shown below:

Where
fp is a file pointer of type FILE
Filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”
Introduction to Programming With C – 19CSE13/23 Module 4

Return values The function may return the following:


A file pointer to the beginning of the opened file, if the file is opened successfully.
NULL otherwise.
If the file pointer fp is not NULL, the necessary data can be accessed from the specified file. If a file cannot be
opened successfully for some reason, the function returns NULL. We can use this NULL character to
test whether a file has been successfully opened or not using the statement:
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}

fclose()
flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
All the links to the file are broken.
Once the file is closed, to access the file, it has to be re-opened.
If a file is closed successfully, 0 is returned otherwise EOF is returned.
The syntax is shown below:
fclose(fp);

5. What is a FILE? Explain any 2 FILE functions with example.


FILE is type defined structure and it is defined in a header file “stdio.h”. So, FILE can be used as a data
type.
It is derived using basic data types such as short, char etc., with the help of the keyword struct.
FILE is a derived data type.
FILE is not a basic data type in C language.
Note:you can explain any 2 functions of your choice { fopen, fclose, fscanf, fprintf, fgetc, fputc, fgets,
fputs }

6. Explain how input is accepted from a file and displayed.


The three types of I/O functions to read from or write into the file
File I/O functions for fscanf() and fprintf()
File I/O functions for strings fgets() and fputs()
File I/O functions for characters fgetc() and fputc()
Note: Explain any one method

You might also like