Unit 5
Unit 5
UNIT V
UNION
A union is a special data type available in C to store different data types in the same memory
location. We can define a union with many members, but only one member can contain a value at a
time. Unions provide an efficient way of using the same memory location for multi-purpose.
DEFINITION
Defining a union, is very similar as like defining structure but keyword union is used. The
union statement defines a new data type, with more than one member for your program.
Syntax:
union
member definition;
member definition;
...
member definition;
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 union's definition, before the final semicolon, union
variables are declared.
Example:
union sample
{
int marks;
float avg;
char grade;
};
Now, a variable of sample type can store an integer, a floating-point number, or a string of
U23CSTC01–Programming In C Regulation 2023
characters. This means that a single variable ie. same memory location can be used to store multiple
types of data. We can use any built-in or user defined data types inside a union based on requirement.
Memory allocation
In structure
struct student
{
int rollno;
char gender;
float marks;
};
In union
union student
{
int rollno;
char gender;
float marks;
};
U23CSTC01–Programming In C Regulation 2023
The initialization of a union is the initialization of its members by simply assigning the value to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.
ACCESSING UNION MEMBERS
To access any member of a union, the member access operator (.) is used. The union keyword to define
variables of union type. Following is the example to explain usage of union:
#include <stdio.h>
#include <conio.h>
union number
{
int n1; float n2;
}union number x;
void main()
{
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
Output:
U23CSTC01–Programming In C Regulation 2023
FILE HANDLING
Definition of Files
“A file is a collection of related information that is permanently stored onthe disk and allows
us to access and alter the information whenever necessary.”
Need of Files:
In order to efficiently analyze all the data that has been collected from differentsources.
Storing data as files in permanent storage devices like hard disk so to make availability of data for
future use.
Definition:
A file is a collection of related data stored on a secondary storage device likehard disk. Every
file contains data that is organized in hierarchy as fields, records, and databases Stored as sequence of
bytes, logically contiguous (may not be physicallycontiguous on disk).
Streams
Stream is a Sequence of data bytes, which is used to read and write data toa file. A Stream acts
as an interface between a program and an input/outputDevice.
Input and Output stream:
Input streams get the data from different input devices such as keyboardand mouse and provide
input data to the program.
Output Streams obtain data from the program and write that on different
Output Devices such as Memory or print them on the Screen.
Buffer in files:
A buffer is a block of memory that is used for temporary storage of data that has to be read from or
written to a file. The buffer acts as an interface between the stream (which is character-oriented) and
the disk hardware (which is block oriented).
U23CSTC01–Programming In C Regulation 2023
File attributes.
The various file attributes are:
Filename - String of characters to store the name of files.
File Position -Pointer that points the position at which next read and writeoperation to be performed.
File Structure -It indicates whether file is text or binary file
File Access Methods- Indicates whether file can be accessed sequentially orrandomly
Attributes flag: Specifies that hidden or read-only or archive file.
File operations.
Creating a new file
Opening an existing file
Reading from a file
Writing to a file
Moving to a specific location in a file (seek)
Closing a file
FILE *fptr;
Syntax:
FILE *fptr;
fptr = fopen(“filename”, ”mode”);
Description: filename – Assigned as an identifier to the filefptr – Acts as a pointer to the data
FILE - defined Data type.
Example: fptr = fopen(“computer”, ”r”); //*r- opens the file in readmode*//
“w+b” Creates and opens binary file for read and writeoperations.
or “wb+”
“a+b” Opens a binary file for for read and write operations.
or “ab+”
CLOSING A FILE
A file is closed when no more Input/Output operations is to be performed on it.Closing a file is
U23CSTC01–Programming In C Regulation 2023
fclose(fptr);
Example:
FILE *book;
book = fopen(“computer”, ”r”);.
fclose(book);
Output
The content of the file will be printed.
int main( )
{
FILE *fp; int rno , i;
float avg;
char name[20] , filename[15];
clrscr();
printf("\nEnter the filename:\n");
scanf("%s",filename);
fp=fopen(filename,"w");
for(i=1;i<=3;i++)
{
printf("Enter rno,name,average of student no%d:",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);
fp=fopen ( filename, "r" );
printf(“The Students details”);
for(i=1;i<=3;i++)
{
fscanf(fp,"%d %s %f",&rno,name,&avg);
printf("\n%d %s %f",rno,name,avg);
}
fclose(fp);
getch();
return 0;
}
Output:
Enter the filename:
test.txt
Enter rno,name,average of student no:1 101ram 75
U23CSTC01–Programming In C Regulation 2023
Once a file is opened, an Input/Output operations is performed on file, source of thefunctions which
facilitate single character Input/Output for file getc() & putc().
The single character Input function fgetc() receives a single argument, a file pointer for the file from
which a character is read.
that indicates the end-of-file reached on afile. To get character from a file terminating character (^z)
is entered.
Example: WRITING TO AND READING FROM A FILE.
#include <stdio.h>main()
{
FILE *f1;
char c;
printf("Data Input\n\n");
/* Open the file INPUT */
f1 = fopen("INPUT", "w");
/* Get a character from keyboard */
while((c=getchar()) != EOF)
/* Write a character to INPUT */
putc(c,f1);
/* Close the file INPUT */
fclose(f1);
printf("\nData Output\n\n");
/* Reopen the file INPUT */
f1 = fopen("INPUT","r");
/* Read a character from INPUT*/
while((c=getc(f1)) != EOF)
/* Display a character on screen */
printf("%c",c);
/* Close the file INPUT */
fclose(f1);
}
Output:
Data Input
This is a program to test the file handling features on this system^Z
Data Output
This is a program to test the file handling features on this system
U23CSTC01–Programming In C Regulation 2023
The ferror() function reports the status of the file indicated. It also takes a FILE pointer as its only
argument and returns a non zero integer if an error has been detected up to that point, during
processing. It returns zero otherwise.
RANDOM ACCESS TO FILES
Sequential Files are generally used in cases where the program processes the data in a
sequential fashion.
Eg: counting words in a text file
Random Access File functions
To access a particular part of a file randomly and not in reading the other parts. This is done by using
the I/O library functions, namely
fseek()
U23CSTC01–Programming In C Regulation 2023
ftell()
rewind()
fseek() FUNCTION
The fseek() function allows us to read from or write to any point in the stream of bytes opened by
using the fopen() function. It is used to move the position of the file pointer to the desired location in
the file.
fseek(fptr,5L,0)
;
5 byte
ftell() FUNCTION
Function returns the current position of the file pointer in the file.
Syntax
Example
rewind() FUNCTION
Function resets the file pointer to the beginning of the file.
Syntax
rewind(fptr);
A program employing ftell and fseek functions is shown. We have created a file RANDOM with the
following contents:
Position ----> 0 1 2 25
Character
stored ----> A B C Z
(ILLUSTRATION OF fseek & ftell FUNCTIONS)
#include <stdio.h>
main()
{
FILE *fp;
long n;
char c;
fp = fopen("RANDOM", "w");
while((c = getchar()) != EOF)
putc(c,fp);
printf("No. of characters entered = %ld\n", ftell(fp));
fclose(fp);
U23CSTC01–Programming In C Regulation 2023
fp = fopen("RANDOM","r");
n = 0L;
while(feof(fp) == 0)
{
fseek(fp, n, 0);/* Position to (n+1)th character*/
printf("Position of %c is %ld\n", getc(fp),ftell(fp));
n = n+5L;
}
putchar('\n');
fseek(fp,-1L,2); /* Position to the last character */
do
{
putchar(getc(fp));
}
while(!fseek(fp,-2L,1));
fclose(fp);
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
No. of characters entered = 26 Position of A is 0
Position of F is 5 Position of K is 10 Position of P is 15 Position of U is 20 Position of Z is 25 Position
of is 30
ZYXWVUTSRQPONMLKJIHGFEDCBA
n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file.
rewind ( )
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);
For example,
FILE *fp;
rewind (fp);
n = ftell (fp);
printf ("%d”, n);
Output
The output is as follows −
0 (always).
fseek ( )
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
Offset
The no of positions to be moved while reading or writing.
If can be either negative (or) positive.
U23CSTC01–Programming In C Regulation 2023
Argument argc
An argument argc counts total number of arguments passed from command prompt. It returns a value
which is equal to total number of arguments passed through main().
Argument argv
It is a pointer to an array of character strings which contains names of arguments. Each word is an
argument.
int main ( int argc, char *argv[] )
U23CSTC01–Programming In C Regulation 2023
Command line argument is a parameter supplied to a program when the program is invoked.
This parameter represents filename of the program that should process.
In general, execution of C program starts from main() function. It has two arguments like argc
and argv. The argc is an argument counter that counts the number of arguments on the command line.
The argv is an argument vector. It represents an array of character pointer that point to command line
arguments.
The size of the array will be equal to the value of argc. Information contained in command line
is passed to program through these arguments whenever main is called. The first parameter in
command line is program name. Here argv[0] represents the program name.
To access command line arguments, declare the main function and parameter as
1. auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be
only accessed within the block/function they have been declared and not outside them (which defines
their scope). Of course, these can be accessed within nested blocks within the parent block/function in
which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers given
here by pointing to the very exact memory location where the variables reside. They are assigned a
garbage value by default whenever they are declared.
2. extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well. So an extern variable is nothing but a global variable
initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed
within any function/block.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword
before its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead, we are using/accessing the global variable only. The main
U23CSTC01–Programming In C Regulation 2023
purpose of using extern variables is that they can be accessed between two different files which are
part of a large program.
3. static
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after they are
out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can
say that they are initialized only once and exist till the termination of the program. Thus, no new
memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
4. register
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of register variables to be much faster
than that of the variables stored in the memory during the runtime of the program.
If a free registration is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program are declared with the register keyword
which improves the running time of the program. An important and interesting point to be noted here
is that we cannot obtain the address of a register variable using pointers.
Syntax
To specify the storage class for a variable, the following syntax is to be followed:
Example
Functions follow the same syntax as given above for variables. Have a look at the following C
example for further clarification:
// A C program to demonstrate different storage // classes
#include <stdio.h>
int x;
void autoStorageClass()
{
printf("\nDemonstrating auto class\n\n");
U23CSTC01–Programming In C Regulation 2023
PREPROCESSOR
Definition
The Preprocessor, as the name implies, is a program that processes the source code before it
passes through the complier. This is known as preprocessor.
Important Points
It operates under the control of preprocessor command lines or directives. Preprocessor
directives are placed in the source program before the main line. Before the source code passes through
the compiler, it is examined by the preprocessor for any preprocessor directives. Preprocessor
directives begin with the symbol # in column one and do not require a semicolon at the end.
Three Categories
Macro substitution directives
File Inclusion directives
Compiler control directives (or) Conditional inclusion directives
U23CSTC01–Programming In C Regulation 2023
Examples
Simple Macro Sub for Expressions
#define AREA 5 * 12.46
#define SIZE sizeof(int) * 7
#define TWO-PI 2.0 * 3.14
#define A (55 – 33)
#define B (55 + 33)
Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming, the predefined macros should not be directly modified.
Macro Description
STDC Defined as 1 when the compiler complies with the ANSI standard.
Example
#include <stdio.h>
main()
{
printf("File :%s\n", FILE; printf("Date :%s\n",DATE );
printf("Time :%s\n",TIME);
printf("Line :%d\n",LINE );
printf("ANSI :%d\n",STDC);
}
Output
File :C:\Users\Documents\sample.c Date :Aug 5 2015
Time :19:03:18
Line :7
ANSI :1
Miscellaneous Directives:
There are two more pre-processor directives, though they are not very commonly used.
They are #undef and #pragma
#undef
On some occasion, it may b desirable to cause a defined name to become „undefined‟. This can
be accomplished by means of the 3undef directive.
Eg: #undef PENTIUM would cause the definition of PENTUM to be removed from the system. All
subsequent #ifdef PENTUM statements became false.
#include<stdio.h>
#define height 100
void main()
{
printf (“First defined height value: %d”,height); #undef height
//undefined variable
#define height 700//redefining the same for new value
printf(“Height value after redefining %d”,height );
}
Output
First defined count value:100
U23CSTC01–Programming In C Regulation 2023
#pragma startup
This directive executes function named
1.
“function_name_1”before starting of the program
<function_name_1>
This directive executes function named
#pragma exit
2. “function_name_2”before termination of
<function_name_2>
the program
If function doesn‟t return a value, then
3. #pragma warn-rvl
warnings are suppressed by this directive while compiling.
Example Program
#include<stdio.h>
int display();
#pragma startup display
#pragma exit display
int main()
{
printf("\nI am in main function");
return 0;
}
int display()
{
printf("\nI am in display function");
U23CSTC01–Programming In C Regulation 2023
return 0;
}
Output:
Enter the filename: test.txt
Enter rno,name,average of student no:1 101 ram 75
Enter rno,name,average of student no:2 102 raj 79.4
Enter rno,name,average of student no:3 103 rahul 92.3
The Students details 101 ram 75.000000
102 raj 79.400002
103 rahul 92.300003
DYNAMIC MEMORY FUNCTIONS.
Dynamic Memory Allocation refers to the process of allocating or deallocating memory blocks during
a program’s runtime. This is achieved through the use of four functions:
Method Description
These functions are located in the <stdlib.h> header file. Dynamic memory allocation can also be
considered as a method of utilizing heap memory, where the size of variables or data structures (such
as arrays) can be changed during a program’s execution with the help of these library functions.
Now, Let us look at the definition, syntax and C example of each of the above-mentioned functions:
Malloc() Method
malloc() is a function in C that dynamically allocates a block of memory of a specified size (in
bytes) in the heap section of memory during the runtime of a C program. It can be found in
the <stdlib.h> header file.
Syntax
The syntax of malloc() function in C is shown below:
cast-type is the type you want to cast the allocated memory to (for example, int* or float*)
n is the number of blocks to be allocated
size is the size of each block in bytes
Realloc() Method
realloc() is a function in C that allows you to change the size of a previously allocated memory
block. This function can be used to increase or decrease the size of a block of memory that was
previously allocated using either malloc() or calloc(). It can also be used to completely allocate or de-
allocate a memory block on its own.
Syntax
The syntax of realloc() function in C is shown below:
ptr is a pointer to the memory block previously allocated using malloc() or calloc().
size is the new size for the memory block, in bytes. The function returns a pointer to the newly
allocated memory block. If the reallocation fails, the function returns NULL.
Free() Method
The free() method in C is used to deallocate a memory block previously allocated
by malloc() or calloc() functions during the execution of the program. It frees up the occupied memory
so that it can be reused again.
Syntax
The syntax of free() function in C is shown below: