Module-5-Pop - Pesce Engineering C Programming
Module-5-Pop - Pesce Engineering C Programming
Principles of
Programming
Using C
MODULE- 5
➢ STRUCTURES
➢ FILE MANAGEMENT
1
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
MODULE-5
STRUCTURES AND FILES
LEARNING OBJECTIVES
Basics of Structure:
➢ “A Structure is a user defined data type, which is used to store the values of different
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.
➢ 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.
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:
struct structure_name
{
data_type1 variable1;
data_type2 variable2;
………………………… structure members
…………………………
data_typen variablen;
};
2
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Examples:
1. struct employee
{
int emp_id, emp_age;
char name[20], grade;
float emp_salary;
};
2. struct book
{
char book_title[20];
char author[20];
float cost_of_book;
int pages;
};
Syntax:
struct structure_name variable_name;
Example:
struct student
{
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
➢ We can also declare multiple structure variables using a single line of code by using
following syntax:
Syntax:
struct structure_type variable1,variable2,… ............ variablen;
3
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Syntax:
struct structure_name
{
data_type1 variable1;
data_type2 variable2;
…………………………
…………………………
data_type n variablen;
} structure_variable1, structure_variable2,………, structure_variablen;
➢ Structure name is student and we have declared two variables of type student: student1 and
student2.
Syntax:
structure_variable_name.member;
Example: student1.roll_no;
student1.name;
4
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
ii. In the second approach, we first need to declare the structure variables and then
initialize each member of the structure variable one by one.
➢ Initializing each structure members separately requires us to access individually structure
members. We can access a structure member by dot (.) operator.
Syntax : structure_variable_name.member_name=value;
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
6
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
{
int roll_no,age;
char name[20],grade;
float collg_fee;
struct date
{
int day, month, year;
} dob;
}student1;
2. In the second approach, the structures are defined separately and a variable of a Structure
type is declared inside the definition of another Structure.
Example: struct date
{
int day, month, year;
} dob;
struct student
{
int roll_no,age;
char name[20],grade;
float collg_fee;
struct date dob;
} student1;
➢ 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.
#include <stdio.h>
#include<conio.h>
struct student
{ OUTPUT:
int roll_no; Enter the student Details:
char name[20], grade; Enter the student Roll_no: 10
float collg_fee; Enter the student Name: Rama
struct date Enter the student Grade: A
{ Enter the College fee: 35500
int day,month,year; Enter the Date of Birth in dd/mm/yyyy
}dob; format: 13 05 1989
}; 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:”);
7
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
scanf(“%s”,student1.name);
printf(“Enter the student Grade:”);
scanf(“%c”,student1.grade);
printf(“Enter the College fee:”);
scanf(“%f”,&student1.collg_fee);
printf(“Enter the Date of Birth in dd/mm/yyyy format:”);
scanf(“%d%d%d”,&student1.dob.day, &student1.dob.month, &student1.dob.year);
printf(“Student Details:\n”);
printf(“Roll_no:%d\n”,student1.roll_no);
printf(“Name:%s\n”,student1.name);
printf(“Grade:%c\n”,student1.grade);
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();
}
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.
➢ 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
{
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
and collg_fee and array of structure type of size 20(We can store the details of 20 students).
Example:
void main()
{
int i;
OUTPUT:
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);
printf(“Enter the College fee:”);
scanf(“%f”,&students[i].collg_fee);
}
printf(“Student details are:\n”);
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);
printf(“College fee:%f\n”,students[i].collg_fee);
}
getch();
}
9
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
printf("Enter the number of student details n=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d student details:\n",i+1);
printf("Enter the Roll number:\n");
scanf("%d",&s[i].rollno);
printf("Enter the student name:\n");
scanf("%s",s[i].name);
printf("Enter the marks:\n");
scanf("%d",&s[i].marks);
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");
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++)
{
if(strcmp(s[i].name,sname)==0)
{
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");
getch();
}
OUTPUT:
Enter the number of student details n=3
Enter the 1 student details:
Enter the Roll number: 123
Enter the student name: Abhi
Enter the marks: 90
Enter the grade: A
10
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Enter the Roll number: 125
Enter the student name: Chethan
Enter the marks: 50
Enter the grade: C
Example: Write a C program to print the Employee Details using type def statement.
#include<stdio.h>
#include<conio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};
void main()
{
11
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
printf(“Enter the Employee id:\n”);
scanf(“%d”,&emp.emp_id);
printf(“Enter name of the Employee:\n”);
scanf(“%s”,emp.name);
printf(“Enter salary of the Employee:\n”);
scanf(“%s”,emp.salary);
printf(“Employee Details:\n”);
printf(“Employee ID:%d\n”,emp.emp_id);
printf(“Name:%s\n”,emp.name);
printf(“Salary:%f\n”,emp.salary);
getch();
}
OUTPUT:
Enter the Employee id: 100
Enter name of the Employee: manu
Enter salary of the Employee: 10000
Employee Details:
Employee ID: 100
Name: manu
Salary: 10000.00
12
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
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.
File Management
➢ “It refers to the process of writing data to a file, reading data from a file, and
performing other operations on files”.
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.
Example: Keyboard, Mouse
ii. Standard Output(stdout): It is the stream where a program writes its output data. The
program requests data transfer using the ‘write’ operation.
Example: Monitor, printer.
iii. Standard Error (stderr): It is an output stream used by programs to report the error
messages or diagnostics.
✓ A stream is linked to a file using an ‘open’ operation and disassociated with ‘close’
operation.
13
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Opening a file:
➢ 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.
The pointer is the name by which the stream is known in the program.
Syntax:
file_pointer = fopen (xyz.txt, w);
where,
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
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.
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
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.
14
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Example Program: Write a C program to demonstrate the usage of fopen() function.
#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”);
exit(0);
}
/* Using fp access file contents*/
…………..
…………..
}
Closing a File:
➢ After a file has been used, it must be closed. This is done by a call to the function
“fclose()”.
➢ The ‘fclose’ function breaks the connection between the stream and the file.
Syntax:
fclose (file_pointer);
➢ The function ‘fclose’ takes one parameter, which is a pointer to a file.
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.
#include<stdio.h>
void main()
{
FILE * fp;
fp = fopen(“student.txt”, “r”);
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;
}
}
15
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
File Input and Output Operations
Input Using fscanf():
➢ While the scanf() function reads input only from stdin that is from keyboard, the ‘fscanf()’
allows a program to receive input from either the keyboard or a file.
➢ The ‘fscanf ()’ function specifiesas the first parameter the source of the input, that can be
either stdin or file.
Syntax:
fscanf(sourcefile, “format string”, list of variables);
Where,
sourcefile- ‘sourcefile’ is either stdin or a pointer to a file which has already been opened.
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.
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); 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
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>
#include<conio.h>
void main()
{
FILE *fp;
int n;
fp = fopen(“student.txt”, “r”);
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
fscanf(fp, “%d”, &n);
fclose(fp);
getch();
}
16
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Output using fprintf():
➢ While printf() sends output to stdout (screen), the function fprintf () allows a program to
send output to many different places: screen, printer or file on a disk.
➢ fprintf () specify as the first parameter, the destination of the output. This destination can be
an I/O stream stdout or stderr or it can be a file.
Syntax:
fprintf (destfile, “format string”, list of variables);
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.
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
➢ 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
variable num is displayed on the standard output screen.
Example programs:
1. Write a C program to demonstrate the usage of fprintf().
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
fp = fopen(“student.txt”,”r”);
if ( fp==NULL)
{
fprintf (stderr,“Error in Opening file\n”);
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()
17
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
{
FILE * fp;
int num;
fp = fopen(“student.txt”, “r”);
if ( fp==NULL)
{
printf (stderr,“Error in Opening file\n”);
exit (1);
}
while (fscanf (fp,”%d”,&num)>0)
{
fprintf(stdout,”%d\n”,num);
}
fclose (fp);
}
➢ If the file does not exist, the program section prints an error message to ‘stderr’ and
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.
➢ 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>
#include<conio.h>
void main()
{
FILE * fp;
int num;
fp=fopen(“input.txt”, “w”);
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while(scanf(“%d”,&num)!=EOF)
{
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.
18
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
Syntax:
strptr = fgets (inputarea, n, source);
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.
➢ ‘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
copied into strptr.
➢ Otherwise it returns NULL when it is unsuccessful.
Example Program:
1. Write a C program to read a line from the keyboard using the function fgets().
#include<stdio.h>
#include<conio.h>
void main()
{
char str[15];
char *ps;
printf(“Enter the string:\n”);
ps=fgets(str,10,stdin);
if(ps!=NULL)
{
printf(“The string is:”);
puts(str);
return;
}
else
printf(“Reading is unsuccessful\n”);
}
19
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
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
str
2. Write a C program to read a line from the file using the function fgets().
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char str[15];
char *ps;
fp=fopen(“input.txt”, “r”);
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
ps=fgets(str,10,fp);
if(ps!=NULL)
{
printf(“The string is:”);
puts(str);
return;
}
else
printf(“Reading is unsuccessful\n”);
getch();
}
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
20
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
String output to a file: fputs()
➢ The fputs() designed to print strings.
Syntax:
fputs (string, destfile);
➢ 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.
➢ 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.
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.
21
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
➢ This function writes a characterstored in ch to the stream(stdout) or t a file pointed by the
file pointer fp. If there is any error or end-of-file is encountered the function returns EOF.
Example Programs:
1. Write a C program to demonstrate the usage of fgetc() and fputc().
#include<stdio.h>
void main()
{
FILE * fp;
int ch;
fp = fopen(“student.txt”, “w”);
ch = fgetc (stdin);
while (ch != EOF)
{
fputc (ch, fp);
ch= fgetc (stdin);
}
fclose (fp);
}
2. Write a C program to copy the contents from one file to another file.
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char file1[20],file2[20];
char ch;
clrscr();
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”);
exit(0);
}
printf(“Enter the output file name:\n”);
scanf(“%s”,file2);
fp2=fopen(“file2.txt”, “w”);
while(!feof(fp1))
{
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()
{
22
PRINCIPLES OF PROGRAMMING Using C Module-5 BPOPS103
FILE * fp;
char str[20];
fp = fopen(“file1.txt”, “r”);
if(fp==NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
while(fscanf(fp, “%s”,str)!=EOF)
{
printf(“%s”,str);
}
fclose (fp);
getch();
}
#include<stdio.h>
#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);
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);
fprintf(fp3, “%s”,str2);
}
while(!feof(fp1))
{
fscanf(fp1, “%s”,str1);
fprintf(fp3, “%s”,str1);
}
flcose(fp1);
flcose(fp2);
flcose(fp3); Output:
fp3=fopen(“Karnataka.in”, “r”); 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);
}
flcose(fp3);
fp=fopen(“Karnataka.in”, “r”);
while((ch=getc(fp))!=EOF)
{
if(ch== ‘ ’||ch== ‘\n’||ch== ‘\t’)
wordcount++;
if(ch!= ‘\n’||ch!= ‘\t’)
charcount++;
if(ch== ‘\n’)
linecount++;
}
printf(“Number of words in the file is=%d\n”,wordcount);
printf(“Number of characters excluding newline and tab space characters
are=%d\n”,charcount);
printf(“Number of lines are=%d”,linecount+1);
flcose(fp);
getch();
}
24