Module 5
Module 5
Structure:
Structure:
Example:
struct student
{
char name[50];
int age;
float marks;
};
Example:
struct student s1, s2;
1. Syntax:
struct struct_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};
struct struct_name list_of_variables;
Example:
struct student
{
char name[50];
int age;
float marks;
};
struct student s1, s2;
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};
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;
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;
return 0;
}
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;
} DOB;
}std;
return 0;
}
ARRAY STRUCTURE
Array uses subscripts or “[ ]” (square bracket) Structure uses “.” (Dot operator) for element
for element access access
Array elements are stored in continuous Structure elements may or may not be stored in a
memory locations. continuous memory location.
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;
};
Syntax:
union union_name
{
datatype member 1;
datatype member 2;
-------
-------
datatype member n;
};
union union_name list_of_variables;
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;
{
union student
{
int rollno;
char name[10];
};
union student std;
return 0;
}
Enumeration:
Enumeration (or enum) is a user defined data type in C. An enumeration consists of a set of named
integer constant.
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
#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);
avg=sum/n;
printf("average marks is %f\n",avg);
{
if(st[i].marks>avg)
{
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
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.
#include <stdio.h>
int main()
{
FILE* fptr;
printf("Size of FILE is %d bytes", sizeof(FILE));
return 0;
}
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,
The different modes in which a file can be opened for processing are given in Table below.
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.
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.
Closing a file:
To close an open file, the fclose() function is used which disconnects a file pointer from a file.
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.
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, …);
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);
}
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:
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");
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,
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);
}
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;
}
3) fputc() function
The fputc() function is used to write a single character into file. It outputs a character
to a stream.
Syntax:
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:
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t num, FILE *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);
}
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 :
#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");
if (feof(fp))
printf("\n End of file reached.");
else
printf("\n Something went wrong.");