module-5-pop-1
module-5-pop-1
MODULE-5
STRUCTURES AND FILES
LEARNING OBJECTIVES
m
o Opening and closing of Files
Basics of Structure:
“A Structure is a user defined data type, which is used to store the values of different
co
data types together under the same name”.
or
“A structure is a collection of one or more variables of same data type or dissimilar
data types grouped under a single name for convenient handling”.
Each member of a structure is assigned a separate memory location.
e.
A structure helps us to organize complicated data, particularly in large programs, because
they permit a group of related variables to be treated as a unit instead of as separate entities.
dg
Defining a Structure:
Definition of structures starts with the ‘struct’ keyword, followed by the name of the
structure, a pair of curly braces containing declaration of a set of variables called structure
members and then semicolon at the end.
Syntax:
ue
struct structure_name
{
data_type1 variable1;
data_type2 variable2;
………………………… structure members
…………………………
vt
data_typen variablen;
};
2. struct book
{
char book_title[20];
m
char author[20];
float cost_of_book;
int pages;
};
co
Declaring Structure Variables:
We can declare variables of the structure name in the same way as we declare variables of
predefined data type.
Syntax:
Example:
e.
struct structure_name variable_name;
struct student
{
dg
int roll_no, age; Structure template with tag
char name[20], grade; Here student is the
tag
float collg_fee;
};
struct student student1; /*student1 is structure variable
ue
We can also declare multiple structure variables using a single line of code by using
following syntax:
Syntax:
struct structure_type variable1,variable2,………….variablen;
vt
m
Example: struct student
{
int roll_no, age;
char name[20], grade;
co
float collg_fee;
}student1,student2;
Structure name is student and we have declared two variables of type student: student1 and
student2.
Example: student1.roll_no;
ue
student1.name;
We can assign values to the members of the structure variables either all at once or one at a
time.
i. In first approach, the declaration of the structure variable and the initialization of
the structure members are done using a single line of code.
Example: struct student
{
int roll_no, age;
char name[20], grade;
float collg_fee;
};
struct student student1={50,18, “Rama”, ‘A’,35500.00};
Syntax : structure_variable_name.member_name=value;
m
Example: struct student
{
int roll_no, age;
char name[20],grade;
float collg_fee;
co
} student1;
student1.roll_no=50;
student1.age=18;
student1.name= “Rama”;
student1.name= ‘A’;
e.
student1.collg_fee=35500.00;
};
void main( )
{
printf(“Student Details:\n”);
printf(“Roll Number:%d\n”,student1.roll_no);
printf(“Age:%d\n”,student1.age);
printf(“Name:%s\n”,student1.name);
printf(“Grade:%c\n”,student1.grade);
printf(“College Fee:%f\n”,student1.collg_fee);
getch();
}
m
struct student
{
int roll_no, age;
char name[20], grade;
float collg_fee;
co
};
void main ( )
{
struct student st;
printf(“Enter the student Details:\n”);
printf(“Enter the student Roll_no:”);
e.
scanf(“%d”,&st.roll_no); OUTPUT:
printf(“Enter the student Age:”); Enter the student Details:
scanf(“%d”,&st.age); Enter the student Roll_no: 10
printf(“Enter the student Name:”); Enter the student Age: 18
dg
scanf(“%s”,st.name); Enter the student Name: Rama
printf(“Enter the student Grade:”); Enter the student Grade: A
scanf(“%c”,st.grade); Enter the College fee: 35500
printf(“Enter the College fee:”); Student details:
scanf(“%f”,&st.collg_fee); Roll_no: 10
print_details(st); Age: 18
ue
fee:%f”,st.roll_no,st.marks,st.name);
}
Here structure named ‘student’ is defined and then the variable of that structure st has been
declared. This structure variable st is then passed as a parameter to the print_details ()
function.
Nested Structures:
We can nest a structure inside another Structure.
The structures can be nested in two ways.
1. In first approach, the complete definition of a structure is placed inside the definition of
another structure.
Example: struct student
m
Example: struct date
{
int day, month, year;
} dob;
struct student
co
{
int roll_no,age;
char name[20],grade;
float collg_fee;
struct date dob;
} student1; e.
We can access the variables of a structure type that are nested inside another structure in the
same way as we access other members of that structure.
Example: Write a C program to print the student details using nested structures.
dg
#include <stdio.h>
#include<conio.h>
struct student
{ OUTPUT:
int roll_no; Enter the student Details:
ue
}; Student details:
Roll_no: 10
void main ( ) Name: Rama
{ Grade: A
College fee: 35500.00
struct student student1; Date of Birth: 13/05/1989
printf(“Enter the student Details:\n”);
printf(“Enter the student Roll_no:”);
scanf(“%d”,&student1.roll_no);
printf(“Enter the student Name:”);
m
printf(“College fee:%f\n”,student1.collg_fee);
printf(“Date_of_Birth:%d/%d/%d\n”,student1.dob.day,student1.dob.month,student1.do
b.year);
getch();
}
co
Array of Structures:
Similar to creating arrays of a predefined data type such as int, float and char, we can also
create an array of structure type.e.
Arrays of Structure type are required in situations when we need to apply the same
Structure to a set of Objects.
Example: Defining a Structure and then creating an array of Structure type:
struct student
dg
{
int roll_no,age;
char name[10],grade;
float collg_fee;
}students[20];
Here we have created a structure called ‘student’ with 5 fields: roll_no, age, name, grade
ue
and collg_fee and array of structure type of size 20(We can store the details of 20 students).
Example:
#include<stdio.h>
#include<conio.h>
struct student
{
int roll_no,age;
char name[10],grade;
float collg_fee;
}students[20];
void main()
{
int i;
OUTPUT:
Dr. Santosh K C, CSE dept., BIET, DVG Enter the details of 3 Students: 8
Enter the Roll_no:101
Enter the age: 18
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
printf(“Enter the details of 3 Students:\n”);
for(i=0;i<3;i++)
{
printf(“Enter the Roll_no:”);
scanf(“%d”,&students[i].roll_no);
printf(“Enter the age:”);
scanf(“%d”,&students[i].age);
printf(“Enter the Name:”);
scanf(“%s”,students[i].name);
printf(“Enter the Grade:”);
scanf(“%c”,students[i].grade);
m
printf(“Enter the College fee:”);
scanf(“%f”,&students[i].collg_fee);
}
printf(“Student details are:\n”);
co
for (i=0;i<3;i++)
{
printf(“Roll Number:%d\n”,students[i].roll_no);
printf(“Age:%d\n”,students[i].age);
printf(“Name:%s\n”,students[i].name);
printf(“Grade:%c\n”,students[i].grade);
e.
printf(“College fee:%f\n”,students[i].collg_fee);
}
getch();
}
dg
ue
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno,marks;
char name[20],grade;
};
void main()
{
int i,n,found=0;
struct student s[10];
char sname[20];
m
printf("Enter the grade:\n");
scanf("%c",&s[i].grade);
}
printf("\n Student details are:\n");
printf("\nRollno\t\tName\t\tMarks\t\tGrade\n");
co
for(i=0;i<n;i++)
{
printf("%d\t\t%s\t\t%d\t\t%c\n",s[i].rollno,s[i].name,s[i].marks,s[i].grade);
}
printf("Enter the student name to print the marks:");
scanf("%s",sname);
for(i=0;i<n;i++)
{
e.
if(strcmp(s[i].name,sname)==0)
{
dg
printf("Marks of the student is:%d",s[i].marks);//s[1].marks
found=1;
}
}
if(found==0)
printf("Given student name not found\n");
ue
getch();
}
OUTPUT:
Enter the number of student details n=3
Enter the 1 student details:
vt
m
Enter the student name to print the marks: Bharath
Marks of the student is: 65
co
The ‘typedef’ statement allows us to create a new data type from an existing data type.
The new data type has a different name but same characteristics as that of the existing data
type.
We create a new data type from both a predefined data types (int, float, char) and a user
defined data type, such as structure.
e.
We can use the new data type to declare variables and arrays of the original data type.
The Scope of the new data type is limited to the function in which it is to be created.
Syntax:
typedef old_data_type new_data_type;
dg
‘typedef’ is a keyword.
old_data_type: is the name of the original data type.
new_data_type: is the name of the new data type.
Example: typedef int biet;
biet a, b, c;
biet a[10];
Here first it creates a new data type called ‘integer’ from predefined data type int and
ue
Example: Write a C program to print the Employee Details using type def statement.
#include<stdio.h>
#include<conio.h>
vt
struct employee
{
int emp_id;
char name[20];
float salary;
};
void main()
{
m
}
OUTPUT:
Enter the Employee id: 100
Enter name of the Employee: manu
co
Enter salary of the Employee: 10000
Employee Details:
Employee ID: 100
Name: manu
Salary: 10000.00
e.
dg
ue
vt
FILE MANAGEMENT
File
“A File is a collection of data or information stored on computer memory or the
secondary device such as disk”.
An Input file (data file) contains the same item what we have typed in from the keyboard
during interactive data entry.
An Output file contains the same information that might have been sent to the screen as the
output from our program.
m
Basic Operations on Files
Declare a file pointer variable.
Opening a file. If it does not exists, then creating a new file.
Writing data to the file.
Reading the data from the file.
co
Determining the end of the file.
Closing the file.
File Management
“It refers to the process of writing data to a file, reading data from a file, and
performing other operations on files”.
ue
Streams in C
A stream is a logical interface to the device that is connected to the computer.
There are three standard streams in C language:
i. Standard Input (stdin): Standard input is the stream from which the program receives
its data. The requests transfers the data using the ‘read’ operation.
vt
Opening a file:
m
Opening a file is done by a call to the function “fopen()”, which tells the operating system
the name of a file and whether the file is to be opened for reading (input) or for writing
(output).
The function ‘fopen()’ associates a file with a stream and return a pointer to that stream.
co
The pointer is the name by which the stream is known in the program.
Syntax:
file_pointer = fopen (xyz.txt, w);
where,
e.
file name: It is a name of the disk file to be opened. If the file is not in the default directory, a
full path name must be provided.
mode: It defines the way in which the file is to be opened. Mode is a string not a character and
dg
it must be enclosed in double quotation marks.
Return values
The function may return the following:
i. File pointer of type FILE if successful.
ii. NULL if unsuccessful.
ue
File Modes
i. read mode (r)- open a text file for reading
If the mode is “r”, the program will read from the file. The file should already exist.
ii. write mode(w)- open a text file for writing or if it does not exist then create a text file
vt
for writing
If the mode is “w” the program will write to the file. If the file does not exist, it will be
created. If the file does exist, it will be over written.
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen (“student.txt”, “r”);
if(fp==NULL)
{
printf(“Error in opening a file\n”);
m
exit(0);
}
/* Using fp access file contents*/
…………..
…………..
co
}
Closing a File:
After a file has been used, it must be closed. This is done by a call to the function
“fclose()”.
Syntax:
e.
The ‘fclose’ function breaks the connection between the stream and the file.
fclose (file_pointer);
The function ‘fclose’ takes one parameter, which is a pointer to a file.
dg
Return values
The function may return the following:
i. 0 if successful.
ii. EOF (End of File) if unsuccessful. i.e. when if there is an error, such as trying to close a file
that is not open.
Example Program: Write a C program to demonstrate the usage of fclose() function.
ue
#include<stdio.h>
void main()
{
FILE * fp;
fp = fopen(“student.txt”, “r”);
vt
if ( fp==NULL)
{
printf (“Error in Opening file\n”);
exit(0);
}/* Using fp access file contents*/
…………..
if(fclose(fp)==EOF) //eof=end of file
{
printf(“Error in closing the file\n”);
return;
}
}
m
format string and list of variables- ‘format string’ (%d%c%s) and ‘list of variables’ specifies
which variable are to be read. i.e., the variables specified in the list will take the values from the
source file that may be either through keyboard or from the file specified by fp using
specifications provided in the format string.
co
Return values
fscanf() returns EOF if it attempts to read at end-of-file,
Otherwise it returns the number of items read in and successfully converted.
Examples:
1.fscanf (stdin, “%d”, &rollno); e.
and scanf(“%d”, &num);
Both the statements are exactly equivalent.
2. fscanf(fp, “%d%s%f”,&id,name,&salary);
Suppose fp points to the source file. After executing the above statement, the values
dg
for the variables id, name and salary are obtained from the file associated with the file pointer
fp. This function returns the number of items that are successfully read from the file.
Example Program:
1. Write a C program to demonstrate the usage of fscanf() function.
#include<stdio.h>
ue
#include<conio.h>
void main()
{
FILE *fp;
int n;
fp = fopen(“student.txt”, “r”);
vt
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
fscanf(fp, “%d”, &n);
fclose(fp);
getch();
}
where,
destfile- ‘destfile’ is the name of an output stream (stdout or stderr) or a pointer to a file which
has already been opened for writing.
m
format string and list of variables-‘format string’ (%d%c%s) and ‘list of variables’ specifies
which variable to be printed. i.e. values of the variables specified in the list will be written into
file associated with file pointer using specifications provided in the format string.
Return value
co
This function returns the number of items that are successfully written into the file.
Examples:
1.fprintf (stdout, “%d\n”,num); and printf(“%d\n”,num);
Both the statements are exactly equivalent. After executing fprintf, the value of the
e.
variable num is displayed on the standard output screen.
{
FILE *fp;
fp = fopen(“student.txt”,”r”);
if ( fp==NULL)
{
fprintf (stderr,“Error in Opening file\n”);
vt
exit (0);
}
fclose(fp);
getch();
}
‘stderr’ sends its output to the screen to alert the programmer to the error.
2. Write a C program to open a file for input, reads in a series of numbers until end-of-
file, and displays each number on the monitor.
#include<stdio.h>
void main()
m
fprintf(stdout,”%d\n”,num);
}
fclose (fp);
}
If the file does not exist, the program section prints an error message to ‘stderr’ and
co
terminates with a zero exit code, including error also.
If the file exists, the program reads numbers from the file, each time it reads a number,
fscanf() returns 1,storing the value in ‘num’.
The call to ‘fprintf()’ inside the while loop prints the numbers. If there are no numbers in
file or if it has read the last number, fscanf() returns EOF, which causes the loop to
terminate. e.
At the end of the program the program closes the opened file
3. Write a C program to read n numbers from the keyboard and write into a file
#include<stdio.h>
dg
#include<conio.h>
void main()
{
FILE * fp;
int num;
fp=fopen(“input.txt”, “w”);
ue
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while(scanf(“%d”,&num)!=EOF)
vt
{
fprintf(fp, “%d\n”,num);
}
fclose(fp);
getch();
}
File I/O Functions for Strings
String Input from a file: fgets()
fgets() reads characters from a file up to the maximum number of characters, which is
specified as a parameter.
fgets() function requires specifying the source of its input as a special case, ‘stdin’ may be
that source or a file specified by a file pointer.
where,
inputarea-The parameter ‘input area’ is the name of the character array which is to get the
data.
n- ‘n’ is an integer representing the size of the input field which is one more than the
maximum number of characters to be read in.
source- ‘source’ identifies the file from which to read. It can be stdin or pointer to a file. File
should already be open.
m
‘fgets()’ continues to read from ‘source’ until it has read ‘n-1’ characters or a new line
character, whichever comes first.
Return value
If the operation is successful, it returns a pointer to the string read in. The returned value is
co
copied into strptr.
Otherwise it returns NULL when it is unsuccessful.
Example Program:
e.
fp = fgets (inarea, 15, stdin);
1. Write a C program to read a line from the keyboard using the function fgets().
#include<stdio.h>
dg
#include<conio.h>
void main()
{
char str[15];
char *ps;
printf(“Enter the string:\n”);
ue
ps=fgets(str,10,stdin);
if(ps!=NULL)
{
printf(“The string is:”);
puts(str);
return;
vt
}
else
printf(“Reading is unsuccessful\n”);
}
Output:
Enter the string:
ABCD
The string is: ABCD
ps
A B C D \n \0
0 1 2 3 4 5 6 7 8 9
m
str
2. Write a C program to read a line from the file using the function fgets().
#include<stdio.h>
#include<conio.h>
co
void main()
{
FILE *fp;
char str[15];
char *ps;
fp=fopen(“input.txt”, “r”);
e.
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
dg
}
ps=fgets(str,10,fp);
if(ps!=NULL)
{
printf(“The string is:”);
puts(str);
ue
return;
}
else
printf(“Reading is unsuccessful\n”);
getch();
}
vt
Output:
Contents of file “input.txt”
ABCD
The string is: ABCD
ps
A B C D \n \0
0 1 2 3 4 5 6 7 8 9
str
The ‘fputs()’ function takes two parameters: a pointer to a string and destination of the
output, which may be either an output stream (stdout or stderr) or pointer to a file.
The ‘fputs()’ function sends the string to the output destination. If the destination is a
pointer to a file, the file should already be open.
The ‘fputs()’ function writes a new line only if the output string contains a newline
character.
m
Example: Write a C program to demonstrate the usage of fputs().
#include<stdio.h>
#include<conio.h>
void main()
co
{
char str[15];
char *ps;
printf(“Enter few lines till EOF:\n”);
ps = fgets (str, 10, stdin);
while (ps!=NULL)
{
e.
fputs(str, stdout);
ps = fgets (str, 10, stdin);
}
dg
getch();
}
fgetc():
Syntax: ch = fgetc (source);
fgetc() function reads a character from ‘source’, which is either stdin or a pointer to a file.
If ‘source’ is a pointer to a file, the file should already be open.
vt
Return vales
The fgetc() function returns the character read in, converted to integer pointed to by fp if
source is a file.
On reaching end-of-file fgetc() returns EOF.
fputc():
Syntax: fputc (ch, destfile);
fputc() function takes two parameters: a character and the destination of the output, which
may be either an output stream (stdout or stderr) or a pointer to a file.
fputc() function sends the character to th output destination.
If the destination is a pointer to a file, the file should already be open.
m
while (ch != EOF)
{
fputc (ch, fp);
ch= fgetc (stdin);
}
co
fclose (fp);
}
2. Write a C program to copy the contents from one file to another file.
#include<stdio.h>
void main()
{ e.
FILE *fp1,*fp2;
char file1[20],file2[20];
char ch;
clrscr();
dg
printf(“Enter the source file name:\n”);
scanf(“%s”,file1);
fp1=fopen(“file1.txt”, “r”);
if(fp1==NULL)
{
printf(“Error in opening the file\n”);
ue
exit(0);
}
printf(“Enter the output file name:\n”);
scanf(“%s”,file2);
fp2=fopen(“file2.txt”, “w”);
while(!feof(fp1))
vt
{
ch=fgetc(fp1);
fput(ch,fp2);
}
flcose(fp1);
flcose(fp2);
}
3. Write a C program to read and display a text from the file.
#include<stdio.h>
#include<conio.h>
void main()
{
m
}
fclose (fp);
getch();
}
co
4. Given two text documentary files “Ramayana.in” and “Mahabharatha.in”. Write a
C program to create a new file “Karnataka.in” that appends the content of the file
“Ramayana.in” to the file “Mahabharatha.in”. Also calculate the number of words
and new lines in the output file. Assume the following contents in the files:
“Ramayana.in” “Mahabharatha.in”
Rama
Sita
Ravana
Bharatha
e. Arjuna
Krishna
Bhima
Karna
dg
After executing the program the file “Karnataka.in” should contain the following
contents: Arjuna
“Karnataka.in” Krishna
Bhima
Karna
Rama
ue
Sita
Ravana
Bharatha
#include<stdio.h>
vt
#include<conio.h>
void main()
{
FILE *fp1,*fp2,*fp3,*fp;
int linecount=0,charcount=0,wordcount=0;
char ch;
char str1[20],str2[20],str[20];
clrscr();
fp1=fopen(“Ramayana.in”, “r”);
if(fp1==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
Dr. Santosh K C, CSE dept., BIET, DVG 23
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
}
fp2=fopen(“Mahabharatha.in”, “r”);
if(fp2==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
fp3=fopen(“Karnataka.in”, “w”);
while(!feof(fp2))
{
fscanf(fp2, “%s”,str2);
m
fprintf(fp3, “%s”,str2);
}
while(!feof(fp1))
{
fscanf(fp1, “%s”,str1);
co
fprintf(fp3, “%s”,str1);
}
flcose(fp1);
flcose(fp2);
flcose(fp3); Output:
fp3=fopen(“Karnataka.in”, “r”);
e. Number of words in the file is = 8
while(!feof(fp3)) Number of characters excluding newline and
{ tab space characters are = 45
fscanf(fp3, “%s”,str); Number of lines are = 8
printf(“\n%s”,str);
dg
}
flcose(fp3);
fp=fopen(“Karnataka.in”, “r”);
while((ch=getc(fp))!=EOF)
{
if(ch== ‘ ’||ch== ‘\n’||ch== ‘\t’)
ue
wordcount++;
if(ch!= ‘\n’||ch!= ‘\t’)
charcount++;
if(ch== ‘\n’)
linecount++;
}
vt