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

Structure, Union, Enumeration and File Concepts

The document discusses different concepts related to structures in C programming language. It defines a structure as a user-defined data type that groups variables of different types together under a single name. It provides the syntax to declare a structure and different methods to declare structure variables. It also discusses concepts like array of structures, passing structures as function arguments, accessing structures using pointers, self-referential structures, and dynamic data structures using pointers.

Uploaded by

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

Structure, Union, Enumeration and File Concepts

The document discusses different concepts related to structures in C programming language. It defines a structure as a user-defined data type that groups variables of different types together under a single name. It provides the syntax to declare a structure and different methods to declare structure variables. It also discusses concepts like array of structures, passing structures as function arguments, accessing structures using pointers, self-referential structures, and dynamic data structures using pointers.

Uploaded by

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

Unit IV

Structure, Union, Enumeration and File concepts


Structure: A structure is a user defined data type or derived data type
that can be used to group of variables of different types into a single type
• A structure is declared using the keyword
struct followed by a structure name. All the
variables of the structures are declared within
the structure. A structure type is defined by
using the given syntax.
Syntax:
struct struct-name Example struct student
{ {
data_type var-name; int r_no;
data_type var-name; char name[20];
... char course[20];
}; float fees;
};
Methods of Declaring a Structure
Variable 3
1 struct
struct student student
{ int r_no;
{ int r_no; char name[20];
char name[20]; char
char course[20];
course[20]; }; float fees;
float fees; struct student
}student1; student1,student2,student3;
4
2 struct
struct student
{ int r_no;
student
{ int r_no; char name[20];
char name[20]; char
char course[20];
course[20]; } float fees;
float fees;
}student1,student2,student3; struct student
student1={23456,”Priya”,”BCA”,25000.75};
#include<stdio.h> printf(“\n ***STUDENT’S DETAILS ***”);
int main() printf(“\n ROLL No. = %d”, stud1.roll_no);
{ printf(“\n NAME. = %s”, stud1.name);
struct student printf(“\n Fees. = %f”, stud1.fees); printf(“\
{ n DOB. = %s”, stud1.DOB);
int roll_no; }
char
name[80];
float fees;
char DOB[80];
};
Output:
struct student
Enter the roll number: 1234
stud1; Enter the name : Ajay
printf(“\n Enter the roll number : Enter the fees : 34500.78
“); scanf(“%d”, &stud1.roll_no); Enter the DOB :
printf(“\n Enter the name : “); 23.05.1998
scanf(“%s”, stud1.name); ***STUDENT’S DETAILS ***
printf(“\n Enter the fees : “); ROLL No. = 1234
scanf(“%f”, &stud1.fees); NAME. = Ajay
printf(“\n Enter the DOB : ROLL No. = 34500.781250
ROLL No. = 23.05.1998
“); scanf(“%s”, stud1.DOB);
Array of Structure
emp[0 emp[1
] ]

int id char float int id char float


name[5] salary name[5] salary
struct emloyee
{ int id; sizeof(emp) = 26 bytes
char name[5];
float salary; sizeof(emp[2]) = 4 + 5 + 4 = 13 bytes
}struct employee emp[2];
for(i = 0; i < 2; i++ )
{
printf("\nEnter details of student %d\n\n",
#include<stdio.h> i+1); printf("Enter name: ");
#include<string.h> scanf("%s", arr_student[i].name);
printf("Enter roll no: ");
Array
struct student
scanf("%d", &arr_student[i].roll_no);
{
Structur
char
printf("Enter marks: ");

e
name[20]; int }
scanf("%f", &arr_student[i].marks);

Program
roll_no; float printf("\n");
marks; printf("Name\tRoll no\tMarks\n");
}; for(i = 0; i < 2; i++ )
int main() {
{ printf("%s\t%d\t%.2f\n", arr_student[i].name,
arr_student[i].roll_no,
struct student
arr_student[i].marks);
arr_student[2]; int i; }
return 0;
#include<stdio.h> Output:
struct address ******
{ Enter employee information Name/ City/ PIN Code/
char Phone Number?
city[20]; int Kani
pin; Madurai
char 600009
999411
phone[14];
7284
Write a program }; Printing the employee information....
to read and struct employee name: Kani
display { City: Madurai
information of an
char name[20]; Pincode: 600009
employee using
structure within a struct address Phone:
add; 9994117284
structure
};
void
printf("Enter
main () employee information Name/ City/ PIN Code/ Phone Number?\
{ n"); scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin,
emp.add.phone);
struct employee printf("Printing the employee information....\n");
printf("name:
emp; %s\nCity: %s\nPincode: %d\nPhone:
%s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
}
#include<stdio.h>
typedef struct
{
int x;
int
y;
}POINT;
void
Passing display(POI
Structure NT);
void main()
as {
arguments POI
NT
p1 =
{2,
3};
displ
#include<stdio.h
> struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
main()
{ struct student stud1, *ptr_stud1;
Accessing ptr_stud1 = &stud1;
ptr_stud1->r_no = 01;
Structure strcpy(ptr_stud1->name, "Rahul");

using strcpy(ptr_stud1->course,
"BCA"); ptr_stud1->fees = 45000;
Pointer printf("\n DETAILS OF
STUDENT");
printf("\n -");
printf("\n ROLL NUMBER = %d", ptr_stud1->r_no);
printf("\n NAME =%s ", puts(ptr_stud1->name));
printf("\n COURSE = %s", puts(ptr_stud1->course));
} printf("\n FEES = %f", ptr_stud1->fees);
Self Referential Structures: contain reference to
data of its same type
struct Node
{
int data;
struct Node *next;
};
Dynamic data structures : Structures with pointer members that
refer to the same structure.
• Arrays and other simple variables are allocated at block
entry.
• But dynamic data structures require storage management
routine to explicitly obtain and release memory.
int main()
{
// A simple C program for traversal of a linked list struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
#include <stdio.h>
#include <stdlib.h> // allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
struct Node { second = (struct Node*)malloc(sizeof(struct Node));
int data; third = (struct Node*)malloc(sizeof(struct Node));
struct Node* next;
}; head->data = 1; // assign data in first node
head->next = second; // Link first node with second

void printList(struct Node* n) second->data = 2; // assign data to second node


{ second->next = third;
while (n != NULL) {
printf(" %d ", n->data); third->data = 3; // assign data to third node
n = n->next; third->next = NULL;
} // Function call
} printList(head);
return 0;
}
#include <stdio.h>
union point{
int x,y;
}p;
void main() {
printf("Enter the value of x or y:");
scanf("%d",p.x);
printf("\nDisplay the point:");
printf("%d %d",p.x,p.y);
}
• Accessing union through pointer:
#include <stdio.h>
Type defining union
#include <stdio.h>
union point{ typedef union
int x,y; {
int x,y;
}p; }POINT;
void main() {
union point *ptr=&p; void main() {
POINT p;
printf("Enter the value of x or y:"); printf("Enter the value of x or y:");
scanf("%d",&ptr->x); scanf("%d",&p.x);
printf("\nDisplay the point");
printf("\nDisplay the point:");
printf("%d %d",p.x,p.y);
printf("%d %d",ptr->x,ptr->y); }
}
Nested derived data types: either structure within union or union with structure or both

struct store { int main ( )


struct store double price; //8 Bytes
{ {
union {
double price; // struct { struct store s;
8 bytes char *title; // char *title; //8 Bytes s.item.book.title = “Programming in C”;
8 bytes char *author; // s.item.book.author= “bmkv”;
char *author; //8 Bytes s.iteam.book.num_pages = 786;
8 bytes int nt num_pages; //4 Bytes
num_pages; // 4 bytes printf(“%s \n ”, s.item.book.title);
} books; printf(“%ld \n ”, sizeof(s));
int color;
struct { return 0;
// 4 bytes
int color; //4 Bytes }
int size;
int size; //4 Bytes
// 4 bytes
char *design;//8 Bytes Output :
char *design;
} shirt; Programming in C
// 8 bytes
}item; 28
};
};
Enumeration:
An enumeration type (also called enum) is a data type that consists of integral constants. (Attaching name to
number) Enum used in looping
Syntax: enum enum_name{const1, const2=value, const3, ... }; for(int i=mon;i<=sun;i++)
printf(“%d”,&i);
default const1 has the value of 0
const2 has assigned value Enum used in switch
const3 has the value is const2+1 (next value of const2)
Example: switch(day)
#include<stdio.h> {
case mon:
enum week{mon=1,tue,wed,thu,fri,sat,sun}; case tue:
case wed:
void main() case thu:
{ case fri:
printf(“working day”);
    enum week day; break;
case sat:
    day = wed; case sun:
printf(“holiday”);
    printf("%d",day); Break;
}
}
File handling in C
• A file is a collection of data stored on a secondary storage device like
hard disk.
• A file is basically used in real life applications that involve large
amounts of data input and in such situations the console oriented I/O
operations pose two major problems:
• First, it becomes cumbersome and time consuming to handle huge
amount of data through terminals.
• Second, when doing I/O using terminal, the entire data is lost when
either the program is terminated or computer is turned off. Therefore,
it becomes necessary to store data on a permanent storage (the disks)
and read whenever necessary, without destroying the data
#include <stdio.h>
main()
{ Two kinds of files:
int i; – Textfile :: contains ASCII codes only EOF character can be
fprintf(stdout,"Give value of i \n"); checked
fscanf(stdin,"%d",&i); – Binaryfile :: can contain non-ASCII characters. Ex: Image,
fprintf(stdout,"Value of i=%d \n",i); audio, video, executable, etc.
fprintf(stderr,"No error: message.\n"); To check the end of file here, the file size value (also stored on
} disk) needs to be checked. feof
Function Description
fopen() opens new or existing file

fprintf() write data into the file


fscanf() reads data from the file

fputc() writes a character into the file

fgetc() reads a character from file

fgets() reads a string from file


fputs() writes a string to file
getw() Read integer from the file
putw() Write an integer into the file
fread() Reads data from the file

fwrite() Write data into the file

fseek() sets the file pointer to given position

ftell() returns current position

rewind() sets the file pointer to the beginning of


the file
fclose() closes the file
Steps in File handling
• Declare the File Pointer: FILE *fp=NULL;
Other file operations:
• Open the file with specified mode: fp=fopen(“filename.txt”, “mode”);
fseek( fp, Position, SEEK_SET ); 
• Process the file using following functions
ftell(fp)
• fscanf and fprintf
rewind(fp)
Syntax: fscanf(fp, “format specifiers”, &variables);
Example: fscanf(fp, “%s %d”,&name,&rollno);
#include<stdio.h>
Syntax: fprintf(fp, “format specifiers”, variables);
void main()
Example: fprintf(fp, “%s %d”,name,rollno);
{
• fgetc and fputc
FILE*fp=fopen("1.txt",“w");
Syntax: ch=fgetc(fp);
fseek(fp, 5,SEEK_SET);
Syntax:fputc(ch,fp);
fputs(“Soul”);
• fgets and fputs
printf(“Pos is %ld”,ftell(fp));
syntax: fgets(str,number of characters, fp);
rewind(fp);
syntax:fputs(str,fp);
printf(“Pos %ld”,ftell(fp));
• fread and fwrite
fclose(fp);
Syntax: fread(void *ptr, size_t size, size_t n, FILE *fp);
}
Example:int a[5];
Input:1.txt
fread(a,sizeof(int),2,fp);
Good is make happy
Syntax: fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
Output:1.txt
Example:
Good soul is make happy
int a[]={10,20};
Pos is 9
fwrite(a,sizeof(int),2,fp);
Pos is 0
• Close the file: fclose(fp);
1 2 3
#include<stdio.h> #include<stdio.h> #include<stdio.h>
void main() void main() void main()
{ { {
FILE*fp=fopen("1.txt","r"); FILE*fp1=fopen("1.txt","r"); FILE*fp1=fopen(“in.txt","r");
while(1) FILE*fp2=fopen("2.txt","w"); FILE*fp2=fopen("res.txt","w");
{ char line[100]; int a,b;
char ch=fgetc(fp); while(fgets(line,80,fp1)!=NULL) fscanf(fp1,"%d %d",&a,&b);
if(ch==EOF) { fprintf(fp2,"Result is %d",a+b);
break; fputs(line,fp2); fclose(fp1);
printf("%c",ch); fclose(fp2);
} } }
fclose(fp); fclose(fp1); #include<stdio.h>
} fclose(fp2); 4
void main()
} {
FILE*fp1=fopen("src.txt","r");
FILE*fp2=fopen("dst.txt","w");
1)Input: 2) 3) Input 4)input
char a[100];
1.txt in.txt src.txt
fread(a,sizeof(char),3,fp1);
Welcome to KCET 10 20 God is great
fwrite(a,sizeof(char),3,fp2);
CSE
fclose(fp1);
Output: output: 2.txt output: res.txt output: dst.txt
fclose(fp2);
Welcome to KCET Welcome to KCET Result is 30 God
}
CSE CSE

You might also like