[go: up one dir, main page]

0% found this document useful (0 votes)
13 views17 pages

Module 5

MODULE 5 NOTES_BPOPS203

Uploaded by

bhavya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views17 pages

Module 5

MODULE 5 NOTES_BPOPS203

Uploaded by

bhavya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Module 5

Structure:
Structure:

The general format of structure is given below:


Synatx
struct tstruct_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};

 The keyword struct defines a structure.


 Struct_name indicates name of structure.
 The structure is enclosed within a pair of flower brackets and terminated with a
semicolon.

Example:
struct student
{
char name[50];
int age;
float marks;
};

Declaring a stucture variable

Syntax: struct struct_name list_of_variables;

Example:
struct student s1, s2;

 The complete syntax can be given as

1. Syntax:
struct struct_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};
struct struct_name list_of_variables;

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 1


Module 5

Example:
struct student
{
char name[50];
int age;
float marks;
};
struct student s1, s2;

Accessing structure members:

A structure member variable is accessed using a ‘.’(dot) operator.


Syntax:
Struct_var.member_name
Ex:
i. book1.price - Indicates the price of book1.
ii. book2.author - Indicates the author of book2.

Structure initialization:

Initializing a structure means assigning some constants to the members of the structure.

Syntax:
struct struct_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};
struct struct_name struct_var={constant1, constant2,…….constant n};

Eg:
struct bookbank
{
char author[50];
char title[50];
int year;
float price;
};
struct bookbank book1 = {“Balaguruswamy”, “CPPS”, 2021, 200.0};

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 2


Module 5

typedef declarations:

 The typedef keyword enables the programmer to create a new data type name for an existing data
type.
Syntax: typedef existing_data_type new_data_type;

Eg: typedef int INTEGER;

 When we proceed a struct name with typedef keyword, then the struct becomes a new type.
Example:
typedef struct
{
char title[50];
char author[50];
int year;
float price;
};
bookbank book1, book2;

Example programs :
1. write a C program to using structures to read and display the information about a
student.

#include<stdio.h>
#include <string.h>
int main()
{
struct student
{
int rollno;
char name[10];
};
struct student std;

printf(“enter the student detail\n”);


printf("Enter Rollno:\n");
scanf("%d",&std.rollno);
printf("Enter Name:\n");
scanf("%s",&std.name);

printf("Student Information List is :");


printf("Rollno:%d\n, Name:%s\n",std.rollno,std.name);

return 0;
}

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 3


Module 5

Array of structures:

Example:
#include<stdio.h>
#include <string.h>
int main()
{
struct student
{
int rollno;
char name[10];
};
struct student std[5];
int i;
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("Enter Rollno:\n");
scanf("%d",&std[i].rollno);
printf("Enter Name:\n");
scanf("%s",&std[i].name);
}
printf("Student Information List is :");
for(i=0;i<5;i++)
{
printf("Rollno:%d\n, Name:%s\n",std[i].rollno,std[i].name);
}
return 0;
}

Nested structure:
A structure that contains another structure as its member is called a nested structure.

Example:
#include <stdio.h>

int main()
{
struct student
{
char name[30];
int rollNo;

struct dateOfBirth
{
int dd;
int mm;
int yy;

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 4


Module 5

} DOB;

}std;

printf("Enter name: ");


gets(std.name);

printf("Enter roll number: ");


scanf("%d", &std.rollNo);

printf("Enter Date of Birth:\n ");


scanf("%d%d%d", &std.DOB.dd, &std.DOB.mm, &std.DOB.yy);

printf("\nName : %s \nRollNo : %d \nDate of birth : %d/%d/%d\n", std.name, std.rollNo,


std.DOB.dd, std.DOB.mm, std.DOB.yy);

return 0;
}

Differences between array and structure:

ARRAY STRUCTURE

Array refers to a collection consisting of Structure refers to a collection consisting of


elements of homogeneous data type. elements of heterogeneous data type.

Syntax: struct tstruct_name


{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
Syntax: datatype arrayname[]; };

Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for element
for element access access

Arrays is a non-primitive datatype Structure is a user-defined datatype.

Structure traversal and searching is complex and


Array traversal and searching is easy and fast. slow.

Array elements are stored in continuous Structure elements may or may not be stored in a
memory locations. continuous memory location.

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 5


Module 5

UNION:

Similar to structure, Union is a collection of variables of different data type. But unlike structures, all
the members in the C union are stored in the same memory location.

Syntax:

union union_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};

Declaring union variables:

Syntax:

union union_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};
union union_name list_of_variables;

Access Union Members

We can access the members of a union by using the ( . ) dot operator just like structures.

Var_name.member_name;

Union initialization :

The initialization of a union is the initialization of its members by simply assigning the value to it.
Var_name.member_name = some_value;

Example program for union :


#include<stdio.h>
int main()

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 6


Module 5

{
union student
{
int rollno;
char name[10];
};
union student std;

printf(“enter the student detail\n”);


printf("Enter Rollno:\n");
scanf("%d",&std.rollno);
printf("Enter Name:\n");
scanf("%s",&std.name);

printf("Student Information List is :");


printf("Rollno:%d\n, Name:%s\n",std.rollno,std.name);

return 0;
}

Enumeration:

Enumeration (or enum) is a user defined data type in C. An enumeration consists of a set of named
integer constant.

Syntax: enum enum_name { identifier1, identifier 2,….. identifier n};

Example: enum colour{Red, Blue, Black};

In this example, colour is the name given to the set of constants. The default value for first one in the
list - Red, has the value of 0. So, in the above example:

Red = 0
Blue = 1
Black = 2
Example program for enum:

#include<stdio.h>
enum week {Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;+
printf("%d",wed);
return 0;
}

Output:
2

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 7


Module 5

1. Implement structures to read, write and compute average- marks of the


students, list the students scoring above and below the average marks for a class
of N students.

#include <stdio.h>
struct student
{
char name[20];
int rollno;
int marks;
};
int main()
{
int i, n;
float sum=0,avg = 0;
struct student st[100];
printf("enter the number of students\n");
scanf("%d",&n);

printf("enter the students details\n");


for(i=1;i<=n;i++)
{
printf("the student %d detail is\n",i);
scanf("%s", st[i].name);
scanf("%d", &st[i].rollno);
scanf("%d", &st[i].marks);
sum = sum + st[i].marks;
}

avg=sum/n;
printf("average marks is %f\n",avg);

printf("the students details are\n");


for(i=1;i<=n;i++)
{
printf("the student %d detail is\n",i);
printf("%s\t\t", st[i].name);
printf("%d\t\t", st[i].rollno);
printf("%d\n\n", st[i].marks);

printf("list of the students who scored above average marks\n");


for (i=1;i<=n;i++)

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 8


Module 5

{
if(st[i].marks>avg)
{

printf("\tname=%s\t\t rollno=%d\t\t marks=%d\n\n ",


st[i].name,st[i].rollno,st[i].marks);
}
}
printf("list of the students who scored below average marks\n");
for (i = 1; i<=n; i++)
{
if(st[i].marks<avg)
{

printf("\tname=%s\t\t rollno=%d\t\t marks=%d\n\n ",


st[i].name,st[i].rollno,st[i].marks);
}
}

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 9


Module 5

Files

 A file is a collection of data stored on secondary storage devices such as a hard disk.

Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as follows:
 Text Files
 Binary Files

1. Text Files

A text file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
 Each line in a text file ends with a new line character (‘\n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.

2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters.
 The binary files can be created only from within a program and their contents can
only be read by a program.
 More secure as they are not easily readable.
 They are generally stored with .bin file extension.

USING FILES IN C

To use files in C, we must use the following steps:

 declare a file pointer variable


 open the file
 process the file
 close the file

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 10


Module 5

Declaring a File Pointer Variable:

There can be a number of files on the disk. A file pointer is a variable that is used to refer to
an opened file in a C program.

The syntax for declaring a file pointer is,

FILE *file pointer

Eg: FILE *fptr;


where, fptr is declared as a file pointer.
Example:

#include <stdio.h>
int main()
{
FILE* fptr;
printf("Size of FILE is %d bytes", sizeof(FILE));
return 0;
}

Open the file:

A file must first be opened before data can be read from or written to it. In order to open a file, the
fopen() function is used. The prototype of fopen() can be given as,

FILE *fopen(const char *file_name, const char *mode);

The method accepts two parameters of character pointer type:


 file_name: This is of C string type and accepts the name of the file that is needed to be opened.
 mode_of_operation: This is also of string type and refers to the mode of the file access.

fopen() returns pointer to FILE strcture if successful and a NULL otherwise.

The different modes in which a file can be opened for processing are given in Table below.

File mode Description

Open a text file for reading(The file must exist.). If the file does not exist then error
r
will be reported.

Open a text file for writing. If the file does not exist, then it is created Otherwise, if
w
the file already exists, its contents are deleted.

a Append to a text file. If the file does not exist, it is created.

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 11


Module 5

rb Open a binary file for reading. (The file must exist.)

wb Open a binary file for writing.

ab Append to a binary file.

r+ Open a text file for both reading and writing(The file must exist.)

Open a text file for both reading and writing If the file does not exist, then it is
w+
created Otherwise, if the file already exists, its contents are deleted.

a+ Open a text file in append mode for reading and writing at the end of the file.

r+b or rb+ Open a binary file for read/write.

w+b or wb+ Create a binary file for read/write.

a+b or ab+ Append a binary file for read/write.

Closing a file:
To close an open file, the fclose() function is used which disconnects a file pointer from a file.

The prototype of the fclose() function can be given as

int fclose(FILE *fp);

Here, fp is a file pointer which points to the file that has to be closed. The function returns an integer
value. A zero is returned if the function was successful; and a non-zero value is returned if an error
occurred.

Reading data from files:

C provides following set of functions to read data from a file.

1. fgetc()– This function is used to read a single character from the file.
2. fgets()– This function is used to read strings from files.
3. fscanf()– This function is used to read formatted input from a file.
4. fread()– This function is used to read the block of raw bytes from files. This is used to
read binary files.
fscanf() :
 This function is used to read formatted input from a file and store them according to the
parameter format into the location pointed by additional arguments.

Syntax:
int fscanf(FILE *ptr, const char *format, …);

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 12


Module 5

Example program:
#include<stdio.h>>
int main()
{
char str[50];
FILE* ptr ;
ptr=fopen("abc.txt", "r");
if (ptr == NULL)
{
printf("no such file.");
return 0;
}
fscanf(ptr,"%s",str);
printf("%s",str);
fclose(ptr);
}
fgets():
 This function is used to read strings from files.
 It reads one string at a time from the file.
 fgets() returns a string if it is successfully read by function or returns NULL if cannot read.
Syntax:
char * fgets(char *str, int size, FILE * ptr);
Here,
str: It is string in which fgets() store string after reading it from file.
size: It is maximum characters to read from stream.
ptr: It is file pointer.

 Example program:
#include<stdio.h>>
int main()
{
char str[50];
FILE* ptr ;
ptr=fopen("abc.txt", "r");
if (ptr == NULL)
{
printf("no such file.");
return 0;
}
fgets(str,50,ptr);
printf("%s", str);
fclose(ptr);
}

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 13


Module 5

fgetc():
 This function is used to read a single character from the file.
 On each successful read, it returns the character read from the file and advances the read
position to the next character.
 This function returns EOF if end of file is reached, or if there is any error.
Syntax:

int fgetc(FILE *ptr);

Example:

#include <stdio.h>
int main()
{
char ch;
FILE* ptr ;
ptr=fopen("abc.txt", "r");
if (ptr == NULL)
{
printf("no such file.");
return 0;
}
printf("content of this file are \n");

while (ch != EOF)


{
ch = fgetc(ptr);
printf("%c", ch);
}
fclose(ptr);
return 0;
}

fread():
 Fread() function is used to read data from a file.
Syntax:
size_t fread(void *ptr, size_t size, size_t num, FILE *stream);
where,

ptr: This is the pointer to a block of memory .


size: This is the size in bytes of each element to be read.
num: This is the number of elements, each one with a size of size bytes.
stream: This is the pointer to a FILE object that specifies an input stream.

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 14


Module 5

Example program:
#include<stdio.h>
int main()
{
char str[50];
FILE* ptr ;
ptr=fopen("abc.txt", "r");
if (ptr == NULL)
{
printf("no such file.");
return 0;
}
fread(str,1,9,ptr);
printf("%s", str);
fclose(ptr);
}

Writing data to files:


1) fprintf:
It is used to print content in file instead of stdout console.
Syntax:
int fprintf(FILE *fptr, const char *str, ...);

Example:
#include<stdio.h>>
int main()
{
FILE* ptr ;
ptr=fopen("abc.txt", "w");
fprintf(ptr,"%s","hello");
}
2) fputs():

The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:
int fputs(const char *s, FILE *stream)

Example program:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("abc","w");
fputs("hello c programming",fp);
fclose(fp);
return 0;
}

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 15


Module 5

3) fputc() function

The fputc() function is used to write a single character into file. It outputs a character
to a stream.

Syntax:

int fputc(int c, FILE *stream)

Example program:

include <stdio.h>
main()
{
FILE *fp;
fp = fopen("abc.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}

4) fwrite() function:

This function is used to write data to a file.

Syntax:

size_t fwrite(const void *ptr, size_t size, size_t num, FILE *stream)

ptr − This is the pointer to the array of elements to be written.


size − This is the size in bytes of each element to be written.
num − This is the number of elements, each one with a size of size bytes.
stream − This is the pointer to a FILE object that specifies an output stream.

Example :

#include<stdio.h>
int main ()
{
FILE *fp;
char str[] = "hello";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return(0);
}

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 16


Module 5

Detecting the end of file:

 The feof() function is used to check whether the file pointer to a stream is pointing to the
end of the file or not.
 It returns a non-zero value if the end is reached, otherwise, it returns 0.

Syntax :

int feof(FILE* stream);

#include <stdio.h>
int main()
{
char ch;
FILE* ptr ;
ptr=fopen("abc.txt", "r");
if (ptr == NULL)
{
printf("no such file.");
return 0;
}
printf("content of this file are \n");

while (ch != EOF)


{
ch = fgetc(ptr);
printf("%c", ch);
}

if (feof(fp))
printf("\n End of file reached.");
else
printf("\n Something went wrong.");

Bhavya P.S.,Asst Prof.,KVGCE.,Sullia Page 17

You might also like