C Programming Unit5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

What is structure :

structure is user defined data type available in C that allows to combine data items of
different data types. Structures are used to represent a record. While arrays allow to define
type of variables that can hold several data items of the same data type.

How to define structure : The struct keyword is used to define the structure. Each element of a
structure is called a member. Defining structure does not occupy any memory.

Syntax :

struct [structure tag]


{

member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such
as int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.

For example :

struct employee
{
int id;
char name[50];
float salary;
};

Declaring structure variables :

struct employee e1,e2;


Initializing structure variables :

struct employee e1={1,”AMIT”},e2={2,”VIPUL”};

Accessing members of the structure


There are two ways to access structure members:

1.By . (member or dot operator)

2.By -> (structure pointer operator)

Q. Write a program to define a structure having two members employee number and employee name.
Input values in structure and print them.

#include <stdio.h>
struct emp
{
int eno;
char ename[30];
};
void main()
{
struct emp e;
printf("Input emp no : ");
scanf("%d",&e.eno);
printf("Input emp name : ");
scanf("%s",e.ename);
printf("Employee Record \n");
printf("%d, %s \n",e.eno,e.ename);
}
Array of Structures

Q. Write a program to input 5 employee records using array of structure and print them.
#include <stdio.h>
struct emp
{
int eno;
char ename[30];
};
void main()
{
struct emp e[5];
int i;
printf("Input employee Records : \n");
for(i=0;i<5;i++)
{
printf("Employee No : ");
scanf("%d",&e[i].eno);\
printf("Employee name : ");
scanf("%s",e[i].ename);
}
printf("Printing Records\n");
for(i=0;i<5;i++)
{
printf("%d,%s \n",e[i].eno,e[i].ename);
}
}
Structure with Pointers
#include <stdio.h>
struct emp
{
int eno;
char ename[20];
};

void main()
{
struct emp e={1,"xyz"};
struct emp *p;
p=&e;
printf(" e1= %d %s \n",e.eno,e.ename);
printf(" e2= %d %s \n",p->eno,p->ename);

Union

Like Structures, union is a user defined data type. In union, all members share the
same memory location. At once, only one member of the union can occupy the memory. In
other words, we can say that the size of the union in any instance is equal to the size of its
largest element. We will use union keyword instead of struct to define union.

Difference between structure and Union


* Union and structure in C are same in concepts, except allocating memory for their members.
* Structure allocates storage space for all its members separately Whereas, Union allocates one
common storage space for all its members

* We can access only one member of union at a time. We can’t access all member values at the
same time in union. But, structure can access all member values at the same time. This is because,
Union allocates one common storage space for all its members. Where as Structure allocates storage
space for all its members separately.
Syntax :

union union_name

{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};

Union example

#include <stdio.h>
union emp
{
int eno;
char ename[20];
};

void main()
{
union emp e;
e.eno=1;
printf("size of union : %d \n",sizeof(e));
printf("eno = %d \n",e.eno);
strcpy(e.ename,"ABC");
printf("eno = %d \n",e.eno); // Garbage Value
printf("ename = %s \n",e.ename);
e.eno=2;
printf("eno = %d \n",e.eno);
printf("ename = %s \n",e.ename); // Garbage Value

}
C File Handling
A file is used to store data on secondary storage. A file is nothing but a source of storing
information permanently in the form of a sequence of bytes on a disk.

Why files are needed?


•When a program is terminated, the entire data is lost. Storing in a file will preserve
your data even if the program terminates.

•If you have to enter a large number of data, it will take a lot of time to enter them
all. However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.

•You can easily move your data from one computer to another without any changes.

Types of Files : there are two types of files in C Language


1. Text files : Text files are the normal .txt files. You can easily create text files using
any simple text editors such as Notepad.

2. Binary files : In binary files data is stored in binary form (0's and 1's). We can’t
open binary files in text editor.

File handling functions:


There are many functions in the C library to open, read, write, search and close the file. A list
of file functions are given below:

Functio
No. Description
n
1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file


7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

12 feof() To check end of file

The following operations can be performed on a file.

•Create a file

•Opening a file

•Reading from the file

•Writing to the file

•Close a file

(I) Create/open a File : To use a file in C program we have to create a file pointer. File pointer is a
pointer which is used to handle and keep track on the files being accessed. A new data type called “FILE” is used to
declare file pointer. This data type is defined in stdio.h file. File pointer is declared as FILE *fp. Where, ‘fp’ is a file
pointer.

Syntax to create/open a file

FILE *fopen(char *filename, char *mode);


Mode Description
r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode


For example : To open a file in write mode

fp=fopen(“fileName.txt”, “w”)

where fileName.txt file will be created on secondary storage

(II) Read from file : We can read content of a file in c using the fscanf() and fgets() and fgetc()
functions. All are used to read contents of a file.

Syntax of fscanf :

int fscanf(file pointer,”format codes”,variables);

(iii) Write to File : We can write data to a file in C using the fprintf(), fputs(), fputc() functions.
All are used to write contents to a file.

Syntax of fprintf

int fprintf(file pointer,”format codes”,variables);

(iv) Close a file : The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.

fclose(file pointer)

Q. Write a program to read five lines from keyboard and store them in a file “a.txt”
#include <stdio.h>
void main()
{
FILE *fp;
char str[30];
int i;
fp=fopen("a.txt","w");
for(i=1;i<=5;i++)
{
printf("Input a string");
scanf("%s",str);
fprintf(fp,"%s\n",str);
}
fclose(fp);
}
Q. Write a program to open a text file and print it.
#include <stdio.h>
void main()
{
FILE *fp;
char str[30],fname[30];
int i;
printf("Input file name : ");
scanf("%s",fname);
fp=fopen("a.txt","r");
while (!feof(fp))
{
fscanf(fp,"%s",str);
printf("%s\n",str);
}
fclose(fp);
}

You might also like