2. UNIT-V STRUCTURES, UNIONS
AND FILES
Structures and Unions: Defining a Structure –
Processing a Structure – User defined data types
(Typedef) – Unions, Files: Opening and Closing a
Data File – Reading and writing a data file –
Processing a data file – Unformatted data files –
Concept of binary files – Accessing a file
randomly using fseek() & ftell().
3. Introduction to Structure
Problem:
How to group together a collection of data items of
different types that are logically related to a particular
entity??? (Array)
5. structure
• a collection of variables (can be of different
types) under a single name.
• The values are called members of the
structure.
• The structure is also called a user-defined data
type.
9. Create struct variables
• When a struct type is declared, no storage or
memory is allocated.
• To allocate memory of a given structure type
and work with it, we need to create variables.
10. Create struct variables
struct Person
{
char name[50];
int age;
float salary;
};
int main()
{
struct Person person1, person2, p[20];
return 0;
}
11. Create struct variables
• Another way of creating a struct variable is:
struct Person
{
char name[50];
int age;
float salary;
} person1, person2;
14. Structure initialization
Syntax:
struct structure_name structure_variable={value1, value2, … , valueN};
There is a one-to-one correspondence between the members and their initializing
values.
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
}s1={“Hari”,1007,90,’M’,9678901561};
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
}s1={“Hari”,1007,90,’M’,9678901561};
struct student
{
char name[20];
int roll_no;
float marks;
char gender;
long int phone_no;
}
void main()
{
struct student s1={“Hari”,1007,90,’M’,9678901561};
}
15. Accessing member of structure / Processing a structure
By using dot (.) operator or member operator.
Syntax:
structure_variable.member
• Here, structure_variable refers to the name of a struct type variable and
member refers to the name of a member within the structure.
struct student
{
char name[20];
int roll;
float mark;
}s={“Ram”,501,95.34};
s.Name
s.Roll
s.mark
17. C program to read and print employee's record using
structure
#include
<stdio.h>
struct
employee
{
char
name[30];
int empId;
float salary;
};
int main()
{
struct employee emp;
printf("nEnter details
:n");
printf("Name ?:");
gets(emp.name);
printf("ID ?:");
scanf("%d",&emp.empId);
printf("Salary ?:");
scanf("%f",&emp.salary);
printf("nEntered detail is:");
printf("Name: %s" ,emp.name);
printf("Id: %d" ,emp.empId);
printf("Salary: %fn",emp.salary);
18. Array of structure
Two ways to declare an array of structure:
struct student
{
char name[20];
int roll;
char remarks;
float marks;
}st[100];
struct student
{
char name[20];
int roll;
char remarks;
float marks;
};
struct student st[100];
19.
20. #include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
for(i=0; i<2; i++)
{
printf(" Records of STUDENT : %d n", i+1);
printf(" Id is: %d n", record[i].id);
printf(" Name is: %s n", record[i].name);
printf(" Percentage is: %fnn",record[i].percentage);
}
return 0;
}
OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
35. • So far the operations using C program are done on a
prompt / terminal which is not stored anywhere.
• But in the software industry, most of the programs are
written to store the information fetched from the program.
• One such way is to store the fetched information is in a file.
File Processing in C
37. Different operations that can be performed on a file are:
Basic File Handling
• Creation of a new file (fopen with attributes as “a” or “a+”
or “w” or “w++”)
• Opening an existing file (fopen)
• Reading from file (fscanf or fgets)
• Writing to a file (fprintf or fputs)
• Moving to a specific location in a file (fseek, rewind)
• Closing a file (fclose)
Random Access File and Sequential Access File
• Writing a Structure Data to a file
• Reading a Structure Data from a file
38. File opening modes in C:
Mode Description
r If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the first character in it. If the file cannot be opened
fopen( ) returns NULL.
w If the file exists, its contents are overwritten. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
a If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer that points to the last character in it. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
39. File opening modes in C:
Mode Description
r+ f is opened successfully fopen( ) loads it into memory and sets up a pointer
which points to the first character in it. Returns NULL, if unable to open the
file.
w+ If the file exists, its contents are overwritten. If the file doesn’t exist a new
file is created. Returns NULL, if unable to open file.
a+ If the file is opened successfully fopen( ) loads it into memory and sets up a
pointer which points to the last character in it. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open file.
40. File Handling Functions C:
Functions Declaration & Description
fopen() – To
open a file
FILE *fp;
fp=fopen (“filename”, ”‘mode”);
Where,
fp – file pointer to the data type “FILE”.
filename – the actual file name with full path of the file.
mode – refers to the operation that will be performed on the file.
Example: r, w, a, r+, w+ and a+.
fclose() – To
close a file
int fclose(FILE *fp);
fclose() function closes the file that is being pointed by file pointer
fp. In a C program, we close a file as below.
fclose (fp);
Returns 0 if successfully closed
41. Functions Declaration & Description
fgets() – To read
a file
char *fgets(char *string, int n, FILE *fp)
fgets (buffer, size, fp);
where,
buffer – buffer to put the data in.
size – size of the buffer
fp – file pointer
fprintf() – To
write into a file
int fprintf(FILE *fp, const char *format, …);
fprintf() function writes string into a file pointed by fp.
In a C program, we write string into a file as below.
fprintf (fp, “some data”); or
fprintf (fp, “text %d”, variable_name);
42. Functions Declaration & Description
fscanf() Declaration: int fscanf(FILE *fp, const char *format, …)
fscanf (fp, “%d”, &age);
Where, fp is file pointer to the data type “FILE”.
Age – Integer variable
This is for example only. You can use any specifiers with any data type as
we use in normal scanf() function.
ftell() Declaration: long int ftell(FILE *fp)
ftell function is used to get current position of the file pointer. In a C
program, we use ftell() as below.
ftell(fp);
rewind() Declaration: void rewind(FILE *fp)
rewind function is used to move file pointer position to the beginning of
the file. In a C program, we use rewind() as below.
rewind(fp);
43. File Handling Programs in C:
S.no Program
1 Read Content from a File and Print the same
2 Get input from User and Write in a File
3 Read Numbers from a file and find their Sum
and Average
4 Search for a particular word in text file
44. C Program to Read Content from a File and Print the
same
45. C Program to Read Content from a File and Print the
same
46. C Program to Read Numbers from a file and find their
Sum and Average
52. File Handling Functions C:
Functions Declaration & Description
fseek int fseek(FILE *stream, long int offset, int whence)
stream − This is the pointer to a FILE object that identifies the
stream.
offset − This is the number of bytes to offset from whence.
whence − This is the position from where offset is added.
fwrite size_t fwrite(const void *ptr, size_t size, size_t nmemb, 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.
nmemb − 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.