0% found this document useful (0 votes)
22 views

12_Structure & files in c

Uploaded by

ayusssssh100
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)
22 views

12_Structure & files in c

Uploaded by

ayusssssh100
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/ 37

‘STRUCTURE & FILES IN C’

P.Sharma,Dept. Of CSE,SMIT 1
‘STRUCTURE IN C’

P.Sharma,Dept. Of CSE,SMIT 2
What is a structure ?
● Array is collection of items with identical data type
● C Supports a constructed data type known as
structure.
● It is user-defined data type
● It wraps different data type
● It is way of extending new programming language

P.Sharma,Dept. Of CSE,SMIT 3
Definition:
- collection of variables under a single name.
- variables can be of different types
- a convenient way of grouping several pieces of related
information together.

 A structure is a collections of more than one variables with


different data type like int, float & char

Example :
struct record A structure is a collections of more
{ than one variables with different data
char name[25]; type like int, float & char
int sci, eng, maths;
float per;
};

P.Sharma,Dept. Of CSE,SMIT
Defining a structure
 General form or syntax:-
struct tag_name Structure tag name
{
datatype variable;
datatype variable;
datatype variable; //structure elements /members
---------------------
---------------------
};

P.Sharma,Dept. Of CSE,SMIT 5
Defining structure variables
Method 1:-
General form or syntax
struct tag_name Structure tag name
{
datatype variable;
datatype variable;
datatype variable; //structure elements
---------------------
---------------------
} list of variables; //Structure Variables
P.Sharma,Dept. Of CSE,SMIT 6
Defining structure variables
Method2:
General form or syntax
struct tag_name
{
datatype member1;
datatype member2;
datatype member3
------- --------
};
void main()
{
struct tag_name var_name; //Structure Variable
}

P.Sharma,Dept. Of CSE,SMIT 7
Accessing Structure Members
 The link between a member and a variable is established using the
member operator ‘.’
 Which is known as dot operator or period operator.
Example:
Book.price

Book.price is the variable representing the price of book and can be


treated like any other ordinary variable.
We can use scanf statement to assign values like:-
syntax:-
Tag_name.member ;
Example:-
scanf(“%s”,book.file);
scanf(“%d”,&book.pages);

P.Sharma,Dept. Of CSE,SMIT 8
Accessing Structure Members
 We can assign variables to the members of book :-

strcpy(book.title,”Programming ANSI C”);


strcpy(book.author,”Balagurusamy”);
Structure member

book.pages=250;
book.price=28.50;
Structure name

P.Sharma,Dept. Of CSE,SMIT 9
#include <stdio.h>
#include <string.h>
Example of a structure
struct student
{
int id;
char name[20]; //array within a structure
float percentage;
};
void main()
{
struct student record ; //method 2

record.id=1; Output
Id is: 1
strcpy(record.name, "Raju");
Name is: Raju
record.percentage = 86.5;
Percentage is: 86.500000

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
getch( );
} P.Sharma,Dept. Of CSE,SMIT 10
#include <stdio.h>
#include <string.h>

struct student
Example of a structure
{
int id;
char name[20]; //array within a structure
float percentage;
} record; //method 1

int main()
{ Output
Id is: 1
record.id=1; Name is: Raju
strcpy(record.name, "Raju"); Percentage is: 86.500000
record.percentage = 86.5;

printf(" Id is: %d \n", record.id);


printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
getch( );
}

P.Sharma,Dept. Of CSE,SMIT 11
Structure member vs variable
struct book_bank
{
char title[20];
char author[15]; Structure
int pages; member
float price;
};

void main()
{
struct book_bank x; //x is structure variable
int i,j;
clrscr();
---------------
---------------
--------------- getch();

P.Sharma,Dept. Of CSE,SMIT 12
Guidelines for declaring structure
variables :-
 We can declare a structure variable only when a
structure is defined.
 Declaration of structure variable is similar to the
declaration of variable of any other data type.
 It includes following points:
- The keyword struct
- The structure tag name
- List of variable names separated by commas.
- A terminating semicolon
For example :
struct book_bank book1, book2, book3;

P.Sharma,Dept. Of CSE,SMIT 13
Guidelines for using Structures in C
 Members of the structure are themselves not a
variable.
 They do not occupy any memory and till associate with
structure variable.
 The memory for structure member is not allocated
when they are declared, memory is allocated only
when the structure variable is declared.

 A structure is usually defines before main along with


macro definitions.

 In such cases the structure assumes global status


and all the functions can access the structure.
P.Sharma,Dept. Of CSE,SMIT 14
Structure Initialization
We can initialize structure when we declare them.
A structure variable can be initialized at compile time.
struct book_bank
{
char title[20]; Initialization of these
char author[15]; variables cannot be
done here .
int pages;
float price;
} book1={“ANSI C”,”Balaguruswamy”,430,200.0}; // structure
initialization

Note : structure members cannot be initialized within the


structure definition.

P.Sharma,Dept. Of CSE,SMIT 15
Compile time Initialization
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
void main()
{
struct book_bank book1 = {“ANSI C”,
”Balaguruswamy”,430,200.0}; // structure initialization
}
Note : structure members cannot be initialized within the
structure definition.

P.Sharma,Dept. Of CSE,SMIT 16
Structure Initialization
 C language does not permit the initialization of individual
structure members within the template.
 At compile time initialization of structure variable must
have the following elements

1. The Keyword struct


2. The structure tag name
3. The name of the variable to be declared
4. The assignment operator
5. A set of values for the members of the structure variable,
separated by commas and enclosed in braces
6. A terminating semicolon
P.Sharma,Dept. Of CSE,SMIT 17
Rules for initializing structure
 We cannot initialize individual members inside the
structure template
 The order of values enclosed in braces must match the
order of members in the structure definition
 It is permitted to have partial initilization. We can initialize
only the first few members and leave the remaining blank.
 The uninitialized members should be only at the end of the
list.
 The uninitialized members will be assigned default values
as follows :-
- Zero for integer and floating point numbers
- ‘\0’ for characters and strings

P.Sharma,Dept. Of CSE,SMIT 18
Copying and Comparing Structure Variables
 Two variables of the same structure type can be copied
the same way as ordinary variables
book1 = book2; //allowed
 There is no way to compare entire structure, we can
only compare element by element
/* this is not allowed */
 if(book1==book2) /* this is not allowed */;

/* where as we can compare element by element */


 if(book1.pages == book2.pages); //alowed

P.Sharma,Dept. Of CSE,SMIT 19
ARRAY OF STRUCTURE
 Like array of int, float or char, we can also have array of structure
 We can use single-dimensional or multi-dimensional arrays
Example
struct student
{
char name[20];
char city[15]; int subject[3]; float per;
} stud[10]; // array of structure

Subject contains three elements :-


subject[0], subject[1] and subject[2].
These elements can be accessed as followed :-
stud[1].subject[2]; // This will refer to the marks of third subject of
second student
Accessing name of 2nd student :-
stud[1].name;
P.Sharma,Dept. Of CSE,SMIT 20
// 3rd student's record
#include <stdio.h> record[2].id=3;
#include <string.h> strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;
struct student for(i=0; i<3; i++)
{ {
int id; printf(" Records of STUDENT : %d \n", i+1);
char name[30]; printf(" Id is: %d \n", record[i].id);
float percentage; printf(" Name is: %s \n", record[i].name);
}; printf(" Percentage is:
%f\n\n",record[i].percentage);
}
void main() getch(0;
{ }
int i; Output
struct student record[2]; Records of STUDENT : 1
Id is: 1
// 1st student's record Name is: Raju
record[0].id=1; Percentage is: 86.500000
strcpy(record[0].name, "Raju"); Records of STUDENT : 2
Id is: 2
record[0].percentage = 86.5;
Name is: Surendren
Percentage is: 90.500000
// 2nd student's record Records of STUDENT : 3
record[1].id=2; Id is: 3
strcpy(record[1].name, "Surendren"); Name is: Thiyagu
record[1].percentage = 90.5; Percentage is: 81.500000

P.Sharma,Dept. Of CSE,SMIT 21
#include <stdio.h>
#include <string.h>

struct student OUTPUT


{ Records of STUDENT1:
int id; Id is: 1
char name[30];
Name is: Raju
float percentage;
}; Percentage is: 90.500000
Records of STUDENT2:
void main() Id is: 2
{ Name is: Mani
int i;
Percentage is: 93.500000
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);

printf("Records of STUDENT2: \n");


printf(" Id is: %d \n", record2.id);
printf(" Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
getch();
}

P.Sharma,Dept. Of CSE,SMIT 22
Array vs Structure
Array:-
 Collection of elements of same data type (Homogeneous
elements)
 Elements referred by subscripts
 Derived data type in C
 Array elements are accessed by it's position or subscript.

Structure:-
 Collection of elements of more that one data type.
(Heterogeneous elements)
 Elements are referred by structure variable.
 Structure elements are accessed by its object as '.' operator.
 User-defined data type in C.
P.Sharma,Dept. Of CSE,SMIT 23
Important question related to
structures :-
1. Array vs structure
2. Structure member vs variable.
3. Array within a structure and array of structures.

P.Sharma,Dept. Of CSE,SMIT 24
Class Assignment:-
1. Write a program in C to create a structure named
student and store the following details, using run-time
initialization method:-
1. Name
2. Reg no
3. Semester
Also, display the above details.

2. Implement the above program using the concept of


array of structures.

P.Sharma,Dept. Of CSE,SMIT 25
THANK YOU !!

P.Sharma,Dept. Of CSE,SMIT 26
FILE MANAGEMENT IN C

P.Sharma,Dept. Of CSE,SMIT 27
Definition of a File
 A file is a place on the disk where a group of related data is
stored.
 FILE is a defined data type, i.e is a structure that is defined
in the I/O library.

Topics to be covered:-
1. Open a file
2. Write data into the file
3. Read the content of the file
4. Display the content of the file
5. Close a file
P.Sharma,Dept. Of CSE,SMIT 28
Why do we need files?
1. Scanf and printf are console oriented functions.
2. These functions work fine as long as data is small.
3. The entire data is lost when either the program is
terminated or the computer is turned off.
Advantage of using files:-
1. Can handle large amount of data
2. Flexible approach where data can be stored on a disk.
3. Data are not destroyed when the program is terminated or
the computer is turned off.

P.Sharma,Dept. Of CSE,SMIT 29
Declaring and opening a file
 Syntax:-
 FILE *fp; //pointer to the data type FILE
 Fp=open(“filename”,”mode”);

Name of the file Mode in which file is to be opened:-


you want to r -> open the file in read only mode
create. w -> open the file in write only mode
Example: a -> open the file in append mode.
Myfile.c (allows to add more data to an existing file.)
Mydata.c

P.Sharma,Dept. Of CSE,SMIT 30
Declaring and opening a file
 Filename: is a string of characters that make up a valid
filename.
 It contains two parts a primary name and an optional
period with an extension.
 Modes are also specified as strings

Example:-
 Myfile . txt

Primary Extension
name

period

P.Sharma,Dept. Of CSE,SMIT 31
File Modes
 Write mode:
- If file does not exist a file with specified name is created.
- If file already exists, its contents are deleted and the file is
opened.
 Read mode:
- If the file already exists then the file is opened with the
current contents safe.
- If the file does not exists error occurs.
 Append mode:
- The file is opened with the current contents safe, and
allows the user to add more data into the file, but cannot
change the existing content.
- If file doe not exist it is created.
P.Sharma,Dept. Of CSE,SMIT 32
Closing a file
 Syntax:-
fclose(file_pointer);

Example:-
void main()
{ FILE *fp;
fp=open(“myfile.txt”,”w”);
--------
---------
--------
fclose(fp);
}

P.Sharma,Dept. Of CSE,SMIT 33
getc() and putc()
 getc()
Used to read a character from file, opened in read mode.
c=getc(fp);
Character is read from the file associated with fp and
store din c
putc()
Writes the character into the file
putc(c,fp);
Content of variable c is written into the file associated
with fp

P.Sharma,Dept. Of CSE,SMIT 34
Example:-
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f1;
Char c;
printf(“opening in write mode\n”);
f1=fopen(“myfile”,”w”);
//get character from keyboard
while((c=getchar()) != EOF)
putc(c,f1);
//Close the file
fclose(f1);
P.Sharma,Dept. Of CSE,SMIT 35
printf(“displaying file content”);
//reopening the file
f1=fopen(“myfile”,”r”);
//read character
while((c=getc(f1)) !=EOF)

//display the content in the console


printf(“%c”,c);
fclose(fp);
}

P.Sharma,Dept. Of CSE,SMIT 36
THANK YOU !!

P.Sharma,Dept. Of CSE,SMIT 37

You might also like