Вы находитесь на странице: 1из 76

Advantages of Recursion:

1. Reduce unnecessary calling of function.


2. Through Recursion one can Solve problems in easy way while its iterative solution is very big
and complex.For example to reduce the code size for Tower of Honai application, a recursive
function is bet suited.
3. Extremely useful when applying the same solution.

Disadvantages of Recursion:
1. Recursive solution is always logical and it is very difficult to trace.(debug and understand).
2. In recursive we must have an if statement somewhere to force the function to return without
the recursive call being executed, otherwise the function will never return.
3. Recursion takes a lot of stack space, usually not considerable when the program is small and
running on a PC.
4. Recursion uses more processor time.
People use recursion only when it is very complex to write iterative code. For example, tree
traversal techniques like preorder, postorder can be made both iterative and recursive. But
usually we use recursive because of its simplicity. ...Recursion can be helpful when traversing
hierarchies in data structures.

At work I do a lot of image processing, and I rarely used recursion. But imho recursion is useful
in many ways
First of all, there are some classes of problems that are inherently recursive (a lot of
mathematical problems, for example, think of sequences like fibonaccis or the definition of
factorial) and some algorithms that are implemented using recursion (like binary search, or
quicksort. I think we'll probably implement them in one of the next lessons as they are standard
algorithms in computer science)
More important (at least for me), understanding recursion is good because it makes you a better
programmer, improving your understanding of algorithms and giving you a nice example of the
"divide et impera" approach.

Library functions:-
These library functions are created by the persons who designed and created Ccompilers.
All C standard library functions are declared in many header files which are saved as
file_name.h. Actually, function declaration, definition for macros are given in all header files.
C Library functions
PREV NEXT
Library functions in C language are inbuilt functions which are grouped together and placed in a
common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined output instead of writing our
own code to get those outputs.
These library functions are created by the persons who designed and created C compilers.
All C standard library functions are declared in many header files which are saved as
file_name.h.
Actually, function declaration, definition for macros are given in all header files.
We are including these header files in our C program using #include<file_name.h> command
to make use of the functions those are declared in the header files.
When we include header files in our C program using #include<filename.h> command, all C
code of the header files are included in C program. Then, this C program is compiled by
compiler and executed.
Please check the below links for actual C source code for the respective C header files.
1. C stdio.h source code
2. C conio.h source code
3. C string.h source code
4. C stdlib.h source code
5. C math.h source code
6. C time.h source code
7. C ctype.h source code
If you want to check source code for all header files, you can check inside include directory
after C compiler is installed in your machine.
For example, if you install DevC++ compiler in C directory in your machine, C:\Dev-
Cpp\include is the path where all header files will be available.
LIST OF MOST USED HEADER FILES IN C PROGRAMMING LANGUAGE:
Check the below table to know all the C library functions and header files in which they are
declared.
Click on the each header file name below to know the list of inbuilt functions declared inside
them.

Header
file Description

This is standard input/output header file in which


Input/Output
stdio.h functions are declared

conio.h This is console input/output header file

string.h All string related functions are defined in this header file

This header file contains general functions used in C


stdlib.h programs

math.h All maths related functions are defined in this header file

time.h This header file contains time and clock related functions

All character handling functions are defined in this


ctype.h header file

Variable argument functions are declared in this header


stdarg.h file

signal.h Signal handling functions are declared in this file

setjmp.h This file contains all jump functions

locale.h This file contains locale functions

errno.h Error handling functions are given in this file

assert.h This contains diagnostics functions

How to create union variables?


Union variables can be created in similar manner as structure variables.
union car
{
char name[50];
int price;
} car1, car2, *car3;
OR
union car
{
char name[50];
int price;
};

int main()
{
union car car1, car2, *car3;
return 0;
}

#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;

int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}

Output
size of union = 32
size of structure = 40
Accessing members of a union
Again, the member of unions can be accessed in similar manner as structures.
In the above example, suppose you want to access price for union variable car1, it can be
accessed as:
car1.price
Likewise, if you want to access price for the union pointer variable car3, it can be accessed as:
(*car3).price
or;
car3->price
More memory is allocated to structures than union
As seen in the above example, there is a difference in memory allocation between union and
structure.
The amount of memory required to store a structure variable is the sum of memory size of all
members.

But, the memory required to store a union variable is the memory required for the largest
element of an union.

Only one union member can be accessed at a time


In the case of structure, all of its members can be accessed at any time.
But, in the case of union, only one of its members can be accessed at a time and all other
members will contain garbage values.
#include <stdio.h>
union job
{
char name[32];
float salary;
int workerNo;
} job1;

int main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);
printf("Enter salary: \n");
scanf("%f", &job1.salary);

printf("Displaying\nName :%s\n", job1.name);


printf("Salary: %.1f", job1.salary);

return 0;
}

Output
Enter name
Hillary
Enter salary
1234.23
Displaying
Name: f%Bary
Salary: 1234.2
Note: You may get different garbage value for the name.
Initially in the program, Hillary is stored in job1.name and all other members of job1, i.e. salary,
workerNo, will contain garbage values.
But, when user enters the value of salary, 1234.23 will be stored in job1.salary and other
members, i.e. name, workerNo, will now contain garbage values.
Thus in the output, salary is printed accurately but, name displays some random string.

C - Unions
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain
a value at any given time. Unions provide an efficient way of using the same memory location
for multiple-purpose.

Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union 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 union's definition, before the
final semicolon, you can specify one or more union variables but it is optional. Here is the way
you would define a union type named Data having three members i, f, and str
union Data {
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of
characters. It means a single variable, i.e., same memory location, can be used to store multiple
types of data. You can use any built-in or user defined data types inside a union based on your
requirement.
The memory occupied by a union will be large enough to hold the largest member of the union.
For example, in the above example, Data type will occupy 20 bytes of memory space because
this is the maximum space which can be occupied by a character string. The following example
displays the total memory size occupied by the above union
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {

union Data data;

printf( "Memory size occupied by data : %d\n", sizeof(data));

return 0;
}
When the above code is compiled and executed, it produces the following result
Memory size occupied by data : 20

Accessing Union Members


To access any member of a union, we use the member access operator ... The member access
operator is coded as a period between the union variable name and the union member that we
wish to access. You would use the keyword union to define variables of union type. The
following example shows how to use unions in a program
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};

int main( ) {
union Data data;

data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");

printf( "data.i : %d\n", data.i);


printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);

return 0;
}
When the above code is compiled and executed, it produces the following result
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Here, we can see that the values of i and f members of union got corrupted because the final
value assigned to the variable has occupied the memory location and this is the reason that the
value of str member is getting printed very well.
Now let's look into the same example once again where we will use one variable at a time which
is the main purpose of having unions
#include <stdio.h>
#include <string.h>

union Data {
int i;
float f;
char str[20];
};
int main( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

return 0;
}
When the above code is compiled and executed, it produces the following result
data.i : 10
data.f : 220.500000
data.str : C Programming
Here, all the members are getting printed very well because one member is being used at a time.

Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily
with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without
using pointers. So it becomes necessary to learn pointers to become a perfect C programmer.
Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) operator, which denotes an address in
memory. Consider the following example, which prints the address of the variables defined
#include <stdio.h>

int main () {

int var1;
char var2[10];

printf("Address of var1 variable: %x\n", &var1 );


printf("Address of var2 variable: %x\n", &var2 );

return 0;
}
When the above code is compiled and executed, it produces the following result
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. Take a look at some of the valid pointer declarations
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is
the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a pointer
and (c) finally access the value at the address available in the pointer variable. This is done by
using unary operator * that returns the value of the variable located at the address specified by its
operand. The following example makes use of these operations
#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}
When the above code is compiled and executed, it produces the following
result
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have
an exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries.
Consider the following program
#include <stdio.h>

int main () {

int *ptr = NULL;

printf("The value of ptr is : %x\n", ptr );

return 0;
}
When the above code is compiled and executed, it produces the following result
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at address 0
because that memory is reserved by the operating system. However, the memory address 0 has
special significance; it signals that the pointer is not intended to point to an accessible memory
location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to
nothing.
To check for a null pointer, you can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */

Pointer and Arrays


When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address which gives location of the first element is also allocated by
the compiler.
Suppose we declare an array arr,
int arr[5]={ 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two byte, the five
element will be stored as follows

Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.

Pointer to Array
As studied above, we can use a pointer to point to an Array, and then we can use that pointer to
access the array. Lets have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We
can also use the Base address (a in above case) to act as pointer and print all the values.

Pointer to Multidimensional Array


A multidimensional array is of form, a[i][j]. Lets see how we can make a pointer point to such an
array. As we know now, name of the array gives its base address. In a[i][j], a will give the base
address of this array, even a+0+0 will also give the base address, that is the address
of a[0][0] element.
Here is the generalized form for using pointer with multidimensional arrays.
*(*(ptr + i) + j)
is same as
a[i][j]
Pointer and Character strings
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points
to the first character of the string "Hello". Another important thing to note that string created
using char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //thi is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to
use indirection operator *.

Array of Pointers
We can also have array of pointers. Pointers are very helpful in handling character array with
rows of varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
In the second approach memory wastage is more, hence it is prefered to use pointer in such
cases.

Pointer to Structure
Like we have array of integers, array of pointer etc, we can also have array of structure variables.
And to make the use of array of structure variables efficient, we use pointers of structure type.
We can also have pointer to a single structure variable, but it is mostly used with array of
structure variables.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;

struct Book b[10]; //Array of structure variables


struct Book* p; //Pointer of Structure type
p = &b;
}

Accessing Structure Members with Pointer


To access members of structure with structure variable, we used the dot . operator. But when we
have a pointer of structure type, we use arrow -> to access structure members.
struct Book
{
char name[10];
int price;
}
int main()
{
struct Book b;
struct Book* ptr = &b;
ptr->name = "Dan Brown"; //Accessing Structure Members
ptr->price = 500;
}

Macros vs Functions
Macros are pre-processed which means that all the macros would be processed before your
program compiles. However, functions are not preprocessed but compiled.
See the following example of Macro:
#include<stdio.h>
#define NUMBER 10
int main()
{
printf("%d", NUMBER);
return 0;
}
Run on IDE
Output:
10
See the following example of Function:
#include<stdio.h>
int number()
{
return 10;
}
int main()
{
printf("%d", number());
return 0;
}
Run on IDE
Output:
10
In macros, no type checking(incompatible operand, etc.) is done and thus use of micros can lead
to errors/side-effects in some cases. However, this is not the case with functions. Also, macros
do not check for compilation error (if any). Consider the following two codes:
Macros:
#include<stdio.h>
#define CUBE(b) b*b*b
int main()
{
printf("%d", CUBE(1+2));
return 0;
}
Run on IDE
Output: Unexpected output
7
Functions:
#include<stdio.h>
int cube(int a)
{
return a*a*a;
}
int main()
{
printf("%d", cube(1+2));
return 0;
}
Run on IDE
Output: As expected
27
Macros are usually one liner. However, they can consist of more than one line, Click here to see
the usage. There are no such constraints in functions.
The speed at which macros and functions differs. Macros are typically faster than functions as
they dont involve actual function call overhead.

Conclusion
Macros are no longer recommended as they cause following issues. There is a better way in
modern compilers that is inline functions and const variable. Below are disadvantages of macros:
a) There is no type checking
b) Difficult to debug as they cause simple replacement.
c) Macro dont have namespace, so a macro in one section of code can affect other section.
d) Macros can cause side effects as shown in above CUBE() example.
Difference between macro and function

No Macro Function

1 Macro is Preprocessed Function is Compiled

2 No Type Checking Type Checking is Done

3 Code Length Increases Code Length remains Same

4 Use of macro can lead No side Effect


to side effect

5 Speed of Execution is Speed of Execution is Slower


Faster

6 Before Compilation macro name is During function call , Transfer of


replaced by macro value Control takes place
7 Useful where small code appears many Useful where large code appears
time many time

8 Generally Macros do not extend beyond Function can be of any number of


one line lines

9 Macro does not Check Compile Errors Function Checks Compile Errors

#define preprocessor directive


It is also called as simple substitution macro as it simply removes the occurrences of the constant
and replace them using the expression
Syntax
#define macro_identifier value
where

Syntax part Explanation

#define It is preprocessor directive used to define constant

It is constant used in the program which we wish to declare using


macro_identifier
#define

value It is value of the constant

Important Note
#define Preprocessor defines a constant/identifier and a value that is substituted for
identifier/constant each time it is encountered in the source file
Generally macro-identifiers/constant defined using #define directive are written in the capital
case to distinguish it from other variables.
constants defined using #define directive are like a name-value pair.
Examples
#define PI 3.142
#define TRUE 1
#define AND &&
#define LESSTHAN <
#define MESSAGE "welcome to C"
In this case

Value of
Constant Expression
constant

PI 3.142 Each occurrence of PI will be replaced by 3.142

TRUE 1 Each occurrence of TRUE will be replaced by 1

Each occurrence of LESSTHAN will be replaced


LESSTHAN <
by >

MESSAGE welcome to C Each occurrence of TRUE will be replaced by 1

Live Example :
Step 1 : program.c [Program written by Programmer]
#include<stdio.h>
#define LESSTHAN <
int main()
{
int a = 30;
if(a LESSTHAN 40)
printf("a is Smaller");

return(0);
}
Step 2 : Program is processed by Pre-processor
int main()
{
int a = 30;
if(a < 40)
printf("a is Smaller");
return(0);
}
Step 3 : Program is processed by Compiler
a is Smaller

Precautions to be Taken while Writing Simple Preprocessor


Do not Write Semicolon After #define Statement.
#define MAX 20;
Dynamic Memory Allocation
The process of allocating memory at runtime is known as dynamic memory allocation. Library routines
known as "memory management functions" are used for allocating and freeing memory during
execution of a program. These functions are defined in stdlib.h.

Function Description

malloc() allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated
space

calloc() allocates space for an array of elements, initialize them to zero and then return a void pointer to the
memory

free releases previously allocated memory

realloc modify the size of previously allocated space

Memory Allocation Process


Global variables, static variables and program instructions get their memory in permanent storage area
whereas local variables are stored in area called Stack. The memory space between these two region is
known as Heap area. This region is used for dynamic memory allocation during execution of the
program. The size of heap keep changing.
Allocating block of Memory
malloc() function is used for allocating block of memory at runtime. This function reserves a block of
memory of given size and returns a pointer of type void. This means that we can assign it to any type of
pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.

Example using malloc() :

int *x;

x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x

free(x); //releases the memory allocated to variable x

calloc() is another memory allocation function that is used for allocating memory at
runtime. calloc function is normally used for allocating memory to derived data types such
as arrays and structures. If it fails to locate enough space it returns a NULL pointer.

Example using calloc() :

struct employee

char *name;

int salary;

};

typedef struct employee emp;

emp *e1;

e1 = (emp*)calloc(30,sizeof(emp));

realloc() changes memory size that is already allocated to a variable.

Example using realloc() :

int *x;

x=(int*)malloc(50 * sizeof(int));

x=(int*)realloc(x,100); //allocated a new memory to variable x

Diffrence between malloc() and calloc()

calloc() malloc()

calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with garbage
value. values.
calloc() malloc()

Number of arguments is 2 Number of argument is 1

Syntax : Syntax :

(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);

MALLO AND CALLOC


There are two major differences between malloc and calloc in C programming language: first, in
the number of arguments. The malloc() takes a single argument, while calloc() takess two.
Second, malloc() does not initialize the memory allocated, while calloc() initializes the allocated
memory to ZERO.
Both malloc and calloc are used in C language for dynamic memory allocation they obtain
blocks of memory dynamically. Dynamic memory allocation is a unique feature of C language
that enables us to create data types and structures of any size and length suitable to our programs.
Following are the major differences and similarities between malloc and calloc in detail with
their syntax and example usage.

Differences between malloc and calloc

malloc calloc

The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.

void *malloc(size_t n) returns a pointer void *calloc(size_t n, size_t size)returns a


to n bytes of uninitialized storage, pointer to enough free space for an array
or NULL if the request cannot be satisfied. If of n objects of the specified size, or NULL if
the space assigned by malloc() is overrun, the request cannot be satisfied. The storage is
the results are undefined. initialized to zero.

malloc() takes one argument that is, number calloc() take two arguments those
of bytes. are: number of blocks and size of each block.

syntax of malloc(): syntax of calloc():


void *malloc(size_t n); void *calloc(size_t n, size_t size);
Allocates n bytes of memory. If the Allocates a contiguous block of memory
allocation succeeds, a void pointer to the large enough to hold n elements of sizebytes
allocated memory is returned. each. The allocated region is initialized to
Otherwise NULL is returned. zero.

malloc is faster than calloc. calloc takes little longer than mallocbecause
of the extra step of initializing the allocated
memory by zero. However, in practice the
difference in speed is very tiny and not
recognizable.

Similarities Between Malloc and Calloc


The pointer returned by malloc or calloc has the proper alignment for the object in question, but
it must be cast into the appropriate type.
Proper alignment means the value of the returned address is guaranteed to be an even multiple of
alignment. The value of alignment must be a power of two and must be greater than or equal to
the size of a word.
The malloc(), calloc() functions will fail if:
The physical limits of the system are exceeded by n bytes of memory which cannot be allocated.
There is not enough memory available to allocate n bytes of memory; but the application could
try again later.
Syntax of Malloc
void *malloc(size_t n);
Allocates n bytes of memory. If the allocation succeeds, a void pointer to the allocated memory
is returned. Otherwise NULL is returned.
/* Allocate memory for an int. */
int *ptr = (int*) malloc(sizeof (int));
if (ptr == NULL)
{
printf("Could not allocate memory\n");
exit(-1);
}
else
printf("Memory allocated successfully.\n");
Syntax of Calloc
void *calloc(size_t n, size_t size);
Allocates a contiguous block of memory large enough to hold n elements of sizebytes each. The
allocated region is initialized to zero.
/* Allocating memory for an array of 10 elements of type int. */
int *ptr = (int*) calloc(10 ,sizeof (int));
if (ptr == NULL)
{
printf("Could not allocate memory\n");
exit(-1);
}
else
printf("Memory allocated successfully.\n");
Hope you have enjoyed reading differences and similarities between malloc and calloc. Both
functions in are used for dynamic memory allocation. Please do write us if you have any
suggestion/comment or come across any error on this page. Thanks for reading!
calloc() versus malloc()
malloc() allocates memory block of given size (in bytes) and returns a pointer to the beginning of
the block.
void * malloc( size_t size );
Run on IDE
malloc() doesnt initialize the allocated memory.
calloc() allocates the memory and also initializes the allocates memory to zero.
void * calloc( size_t num, size_t size );
Run on IDE
Unlike malloc(), calloc() takes two arguments: 1) number of blocks to be allocated 2) size of
each block.
We can achieve same functionality as calloc() by using malloc() followed by memset(),
ptr = malloc(size);
memset(ptr, 0, size);
If we do not want to initialize memory then malloc() is the obvious choice.
Please write comments if you find anything incorrect in the above article or you want to share
more information about malloc() and calloc() functions.

Command Line Argument

It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your program
especially when you want to control your program from outside instead of hard coding those values
inside the code.

The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly

#include <stdio.h>

int main( int argc, char *argv[] ) {

if( argc == 2 ) {

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 ) {

printf("Too many arguments supplied.\n");

else {

printf("One argument expected.\n");

When the above code is compiled and executed with single argument, it produces the following result.

$./a.out testing

The argument supplied is testing


When the above code is compiled and executed with a two arguments, it produces the following result.

$./a.out testing1 testing2

Too many arguments supplied.

When the above code is compiled and executed without passing any argument, it produces the
following result.

$./a.out

One argument expected


It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc
will be one, and if you pass one argument then argc is set at 2.

You pass all the command line arguments separated by a space, but if argument itself has a space then
you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write
above example once again where we will print program name and we also pass a command line
argument by putting inside double quotes

#include <stdio.h>

int main( int argc, char *argv[] ) {

printf("Program name %s\n", argv[0]);

if( argc == 2 ) {

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 ) {

printf("Too many arguments supplied.\n");

else {

printf("One argument expected.\n");

}
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.

$./a.out "testing1 testing2"

Progranm name ./a.out

The argument supplied is testing1 testing2

Command Line Argument


Command line argument is a parameter supplied to the program when it is invoked. Command line
argument is an important concept in C programming. It is mostly used when you need to control your
program from outside. command line arguments are passed to main() method.

Syntax :

int main( int argc, char *argv[])

Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which
holds pointers of type char which points to the arguments passed to the program.

Example for Command Line Argument

#include <stdio.h>

#include <conio.h>

int main( int argc, char *argv[] )

int i;

if( argc >= 2 )

printf("The arguments supplied are:\n");

for(i=1;i< argc;i++)

printf("%s\t",argv[i]);

}
}

else

printf("argument list is empty.\n");

getch();

return 0;

Remember that argv[0] holds the name of the program and argv[1] points to the first command line
argument and argv[n] gives the last argument. If no argument is supplied, argc will be one.

Console I/O Functions in C programming language

The screen and keyboard together are called a console. Console I/O functions can be further classified
into two categoriesformatted and unformatted console I/O functions. The basic difference between
them is that the formatted functions allow the input read from the keyboard or the output displayed on the
VDU to be formatted as per our requirements. For example, if values of average marks and percentage
marks are to be displayed on the screen, then the details like where this output would appear on the
screen, how many spaces would be present between the two values, the number of places after the
decimal points, etc. can be controlled using formatted functions. The functions available under each of
these two categories are shown in Figure 11.1. Now let us discuss these console I/O functions in detail
C programming language provides many of the built-in functions to read given input and write data on
screen, printer or in any file.

Formatted and Unformatted Input/Output

Unformatted Input/Output is the most basic form of input/output. Unformatted input/output


transfers the internal binary representation of the data directly between memory and the file.
Formatted output converts the internal binary representation of the data to ASCII characters which
are written to the output file. Formatted input reads characters from the input file and converts
them to internal form. Formatted I/O can be either "Free" format or "Explicit" format, as described
below.

Advantages and Disadvantages of Unformatted I/O

Unformatted input/output is the simplest and most efficient form of input/output. It is usually the
most compact way to store data. Unformatted input/output is the least portable form of
input/output. Unformatted data files can only be moved easily to and from computers that share
the same internal data representation. It should be noted that XDR (eXternal Data Representation)
files, described in Portable Unformatted Input/Output, can be used to produce portable binary data.
Unformatted input/output is not directly human readable, so you cannot type it out on a terminal
screen or edit it with a text editor.
Advantages and Disadvantages of Formatted I/O

Formatted input/output is very portable. It is a simple process to move formatted data files to
various computers, even computers running different operating systems, as long as they all use the
ASCII character set. (ASCII is the American Standard Code for Information Interchange. It is the
character set used by almost all current computers, with the notable exception of large IBM
mainframes.) Formatted files are human readable and can be typed to the terminal screen or edited
with a text editor.

However, formatted input/output is more computationally expensive than unformatted


input/output because of the need to convert between internal binary data and ASCII text. Formatted
data requires more space than unformatted to represent the same information. Inaccuracies can
result when converting data between text and the internal representation.

scanf() and printf() functions


#include<stdio.h>

#include<conio.h>

void main()

int i;

printf("Enter a value");

scanf("%d",&i);

printf( "\nYou entered: %d",i);

getch();

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it
will display the value you have entered.

NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number
of characters read by it.

int i = printf("studytonight");

In this program i will get 12 as value, because studytonight has 12 characters.

getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer. This function
reads only single character at a time. You can use this method in the loop in case you want to read more
than one characters. The putchar() function prints the character passed to it on the screen and returns
the same character. This function puts only single character at a time. In case you want to display more
than one characters, use putchar() method in the loop.

#include <stdio.h>

#include <conio.h>

void main( )

int c;

printf("Enter a character");

c=getchar();

putchar(c);

getch();

When you will compile the above code,it will ask you to enter a value. When you will enter the value, it
will display the value you have entered.

gets() & puts() functions


The gets() function reads a line from stdin into the buffer pointed to by s until either a terminating
newline or EOF (end of file). The puts() function writes the string s and a trailing newline to stdout.

#include<stdio.h>

#include<conio.h>

void main()

char str[100];

printf("Enter a string");

gets( str );

puts( str );

getch();

When you will compile the above code,it will ask you to enter a string. When you will enter the string, it
will display the value you have entered.
Difference between scanf() and gets()
The main difference between these two functions is that scanf() stops reading characters when it
encounters a space, but gets() reads space as character too.

If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part
after space. But gets() function will read it complete.

When we say Input, it means to feed some data into a program. An input can be given in the
form of a file or from the command line. C programming provides a set of built-in functions to
read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen as
well as to save it in text or binary files.

The Standard Files


C programming treats all the devices as files. So devices such as the display are addressed in the
same way as files and the following three files are automatically opened when a program
executes to provide access to the keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose. This section
explains how to read values from the screen and how to print the result on the screen.

The getchar() and putchar() Functions


The int getchar(void) function reads the next available character from the screen and returns it as
an integer. This function reads only single character at a time. You can use this method in the
loop in case you want to read more than one character from the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time. You can use this method in the loop
in case you want to display more than one character on the screen. Check the following example

#include <stdio.h>
int main( ) {

int c;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then the program proceeds and reads only a single character and
displays it as follows
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either
a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );
printf( "\nYou entered: ");
puts( str );

return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then the program proceeds and reads the complete line till end, and
displays it as follows
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or
read strings, integer, character or float respectively. There are many other formatting options
available which can be used based on requirements. Let us now proceed with a simple example
to understand the concepts better
#include <stdio.h>
int main( ) {

char str[100];
int i;

printf( "Enter a value :");


scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, i);


return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you
enter a text and press enter, then program proceeds and reads the input and displays it as follows

$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and
%d, which means you have to provide valid inputs like "string integer". If you provide "string
string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a
string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for
scanf().

When we enter the data, it is stored in computer's memory , it is processed and


result is displayed. The result can be either unformatted or formatted. The data
is assigned to the variable with the helps of scanf() and result is displayed with
printf(). These are the common statements to enter data and show result.
Beside it we also use some other statements. These functions which are used to
input and out put operations are called input output functions.
These function have two types:

1) Formatted Console i/o functions


The functions are used to input the data from standard input device and
displays the result to the standard output device. The functions can have space
between two values string with the values, we can place the value where we
want to show the data on the screen. We use scanf() for input and printf() for
output operations.

scanf()

It is used to accept input data from the input device keyboard.


Example:
scanf("format string",&variable);
scanf("%d%d",&a,&b);
Format string contains the format specifiers which begins with % sign followed
by specifier. After the format string we give arguments and & sign with each
argument.
Format specifiers are:
Integer
%d short int, int, signed int.
%u unsigned int.
%ld long signed int.
%lu long unsigned int.
%x unsigned hexadecimal integer
%o unsigned octal integer
Float
%f float
%lf double
Character
%c signed character, unsigned character.
%s string

printf

This function is an formatted output function. It is used to show the result on


the standard output screen. It displays a text mesege mixed with the integer /
float/ char values. We also use format specifiers which are discussed with
scanf() functions. Beside those specifiers we also use some additional which are
:
Specifiers for printf()-
%6d It will print the value of variable right justified leaving five blank spaces.
%.f (decimal) Decimal separates the values after the decimal point.
%-d It is used for left justify of the output.

int a=50;
float b=5.57;
printf("A=%d");
printf("A=%5d");
printf("A=%-5d");
printf("B=%10.2f",b);

Result
A=5 0
A= 50
A=5 0
B=5.57 //the value according to float is 5.570000

White spaces with printf() function

\n - New line
\b - Backspace
\f - Move to next page
\v - Vertical Tab
\t - Horizontal Tab
\\ - Back slash
\" - Double quote
\' - Single quote
\a - alert

2) Unformatted Console i/o functions


These statements deals with single character and with strings. There are six
unformatted console functions:

getch()

This function is an input function. In this function user do not need to press
enter key. Typed character is not displayed on computer screen. It is included in
<conio.h> file.

getche()

This is also an input function this is similar to getch() function except "e", "e" is
an echoed function. It means when we type a character it is visible on the
computer screen. There is no need to press enter. It is also included in
<conio.h> file.

getchar()

This is also an input function. It is used to read a single character from the
keyboard. After typing the character the user required to press enter the enter
key to shift the control to next statement.

putchar()
This is an output function. This is used to display single character on the screen.
Example:
putchar(a);

gets()

This function is an input function. This function is used to read a string from the
keyboard
Example:
gets(a);
It will assign the entered string to variable a.

puts()

This is an output function. This is used to print a string on the screen.


puts(a);
or
puts("jobcareindia");

FILES IN C
A file represents a sequence of bytes on the disk where a group of related data is stored. File is
created for permanent storage of data. It is a ready made structure.

In C programming, file is a place on your physical disk where information is stored.

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 few commands in C.
You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files

1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple
text editors.

When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better
security than text files.

File Operations
In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration is
needed for communication between the file and program.

FILE *fptr;
Opening a file - for creation and edit
Opening a file is performed using the library function in the "stdio.h" header file:
fopen().

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The
first function creates a new file named newprogram.txt and opens it for writing as per
the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
Now let's suppose the second binary file oldprogram.bin exists in the
location E:\cprogram. The second function opens the existing file for reading in binary
mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.

Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

If the file does not exist, fopen() returns


r Open for reading.
NULL.
Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

If the file does not exist, fopen() returns


rb Open for reading in binary mode.
NULL.

If the file exists, its contents are overwritten.


w Open for writing.
If the file does not exist, it will be created.

If the file exists, its contents are overwritten.


wb Open for writing in binary mode.
If the file does not exist, it will be created.

Open for append. i.e, Data is


a If the file does not exists, it will be created.
added to end of file.

Open for append in binary mode.


ab If the file does not exists, it will be created.
i.e, Data is added to end of file.

If the file does not exist, fopen() returns


r+ Open for both reading and writing.
NULL.

Open for both reading and writing If the file does not exist, fopen() returns
rb+
in binary mode. NULL.

If the file exists, its contents are overwritten.


w+ Open for both reading and writing.
If the file does not exist, it will be created.

Open for both reading and writing If the file exists, its contents are overwritten.
wb+
in binary mode. If the file does not exist, it will be created.

Open for both reading and


a+ If the file does not exists, it will be created.
appending.
Opening Modes in Standard I/O

File
Meaning of Mode During Inexistence of file
Mode

Open for both reading and


ab+ If the file does not exists, it will be created.
appending in binary mode.

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be


closed.

Reading and writing to a text file


For reading and writing to a text file, we use the functions fprintf() and fscanf().

They are just the file versions of printf() and scanf(). The only difference is that, fprint
and fscanf expects a pointer to the structure FILE.

Writing to a text file


Example 1: Write to a text file using fprintf()

#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}

This program takes a number from user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.

Reading from a text file


Example 2: Read from a text file using fscanf()

#include <stdio.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

This program reads the integer present in the program.txt file and prints it onto the
screen.

If you succesfully created the file from Example 1, running this program will get you the
integer you entered.

Other functions like fgetchar(), fputc() etc. can be used in similar way.

Reading and writing to a binary file


Functions fread() and fwrite() are used for reading from and writing to a file on the
disk respectively in case of binary files.

Writing to a binary file


To write into a binary file, you need to use the function fwrite(). The functions takes four
arguments: Address of data to be written in disk, Size of data to be written in disk,
number of such type of data and pointer to the file where you want to write.

fwrite(address_data,size_data,numbers_data,pointer_to_file);

Example 3: Writing to a binary file using fwrite()


#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;

if ((fptr = fopen("C:\\program.bin","wb")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);

return 0;
}
In this program, you create a new file program.bin in the C drive.

We declare a structure threeNum with three numbers - n1, n2 and n3, and define it in the
main function as num.

Now, inside the for loop, we store the value into the file using fwrite.

The first parameter takes the address of num and the second parameter takes the size of
the structure threeNum.

Since, we're only inserting one instance of num, the third parameter is 1. And, the last
parameter *fptr points to the file we're storing the data.

Finally, we close the file.

Reading from a binary file


Function fread() also take 4 arguments similar to fwrite() function as above.

fread(address_data,size_data,numbers_data,pointer_to_file);

Example 4: Reading from a binary file using fread()

#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

In this program, you read the same file program.bin and loop through the records one by
one.

In simple terms, you read one threeNum record of threeNum size from the file pointed
by *fptr into the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()


If you have many records inside a file and need to access a record at a specific position,
you need to loop through all the records before it to get the record.

This will waste a lot of memory and operation time. An easier way to get to the required
data can be achieved using fseek().

As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)

The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location where
the offset starts.

Different Whence in fseek

Whence Meaning

SEKK_SET Starts the offset from the beginning of the file.

SEKK_END Starts the offset from the end of the file.

SEKK_CUR Starts the offset from the current location of the cursor in the file.

Example of fseek()
#include <stdio.h>

struct threeNum
{
int n1, n2, n3;
};

int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

// Moves the cursor to the end of the file


fseek(fptr, sizeof(struct threeNum), SEEK_END);

for(n = 1; n < 5; ++n)


{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);

return 0;
}

This program will start reading the records from the file program.bin in the reverse order
(last to first) and prints it.

The last chapter explained the standard input and output devices handled by
C programming language. This chapter cover how C programmers can create,
open, close text or binary files for their data storage.

A file represents a sequence of bytes, regardless of it being a text file or a


binary file. C programming language provides access on high level functions
as well as low level (OS level) calls to handle file on your storage devices.
This chapter will take you through the important calls for file management.
Opening Files
You can use the fopen( ) function to create a new file or to open an existing
file. This call will initialize an object of the type FILE, which contains all the
information necessary to control the stream. The prototype of this function
call is as follows

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

Here, filename is a string literal, which you will use to name your file, and
access mode can have one of the following values

Mode Description

r Opens an existing text file for reading purpose.

w Opens a text file for writing. If it does not exist, then a new file is created.
Here your program will start writing content from the beginning of the file.

a Opens a text file for writing in appending mode. If it does not exist, then a
new file is created. Here your program will start appending content in the
existing file content.

r+ Opens a text file for both reading and writing.

w+ Opens a text file for both reading and writing. It first truncates the file to
zero length if it exists, otherwise creates a file if it does not exist.

a+ Opens a text file for both reading and writing. It creates the file if it does
not exist. The reading will start from the beginning but writing can only be
appended.

If you are going to handle binary files, then you will use following access
modes instead of the above mentioned ones

"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"


Closing a File
To close a file, use the fclose( ) function. The prototype of this function is

int fclose( FILE *fp );

The fclose(-) function returns zero on success, or EOF if there is an error in


closing the file. This function actually flushes any data still pending in the
buffer to the file, closes the file, and releases any memory used for the file.
The EOF is a constant defined in the header file stdio.h.

There are various functions provided by C standard library to read and write
a file, character by character, or in the form of a fixed length string.

Writing a File
Following is the simplest function to write individual characters to a stream

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the
output stream referenced by fp. It returns the written character written on
success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced by
fp. It returns a non-negative value on success, otherwise EOF is returned in
case of any error. You can use int fprintf(FILE *fp,const char *format,
...) function as well to write a string into a file. Try the following example.

Make sure you have /tmp directory available. If it is not, then before
proceeding, you must create this directory on your machine.

#include <stdio.h>

main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new


file test.txt in /tmp directory and writes two lines using two different
functions. Let us read this file in the next section.

Reading a File
Given below is the simplest function to read a single character from a file

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp.
The return value is the character read, or in case of any error, it returns EOF.
The following function allows to read a string from a stream

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n-1 characters from the input stream
referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.

If this function encounters a newline character '\n' or the end of the file EOF
before they have read the maximum number of characters, then it returns
only the characters read up to that point including the new line character.
You can also use int fscanf(FILE *fp, const char *format, ...) function to
read strings from a file, but it stops reading after encountering the first space
character.

#include <stdio.h>

main() {

FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);

When the above code is compiled and executed, it reads the file created in
the previous section and produces the following result

1 : This
2: is testing for fprintf...

3: This is testing for fputs...

Let's see a little more in detail about what happened here.


First, fscanf() read just This because after that, it encountered a space,
second call is for fgets() which reads the remaining line till it encountered
end of line. Finally, the last call fgets() reads the second line completely.

Binary I/O Functions


There are two functions, that can be used for binary input and output

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements,


FILE *a_file);

Both of these functions should be used to read or write blocks of memories -


usually arrays or structures.
n C language, we use a structure pointer of file type to declare a file.
FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the
functions,

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point


Opening a File or Creating a File
The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);

Here filename is the name of the file to be opened and mode specifies the purpose of opening the
file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.

mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode


wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );

Here fclose() function closes the file and returns zero on success, or EOF if there is an error in
closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading and writing
on file. getc() and putc() are simplest functions used to read and write individual characters to a
file.
#include<stdio.h>

#include<conio.h>

main()

FILE *fp;

char ch;

fp = fopen("one.txt", "w");

printf("Enter data");

while( (ch = getchar()) != EOF) {

putc(ch,fp);

fclose(fp);

fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)

printf("%c",ch);
fclose(fp);

Reading and Writing from File using fprintf() and fscanf()


#include<stdio.h>

#include<conio.h>

struct emp

char name[10];

int age;

};

void main()

struct emp e;

FILE *p,*q;

p = fopen("one.txt", "a");

q = fopen("one.txt", "r");

printf("Enter Name and Age");

scanf("%s %d", e.name, &e.age);

fprintf(p,"%s %d", e.name, e.age);

fclose(p);

do

fscanf(q,"%s %d", e.name, e.age);

printf("%s %d", e.name, e.age);

while( !feof(q) );

getch();

In this program, we have create two FILE pointers and both are refering to the same file but in
different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which
can then be printed on console usinf standard printf() function.
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to
write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in
deletion of any data already present in the file. While in append mode this will not happen. Append
mode is used to append or add data to the existing data of file(if any). Hence, when you open a file
in Append(a) mode, the cursor is positioned at the end of the present data in the file.

Reading and Writing in a Binary File


A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes
are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements,

number_of_elements, pointer-to-file);

fread() is also used in the same way, with the same arguments like fwrite() function. Below
mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";

FILE *bfp= fopen("test.txt", "wb");

if (bfp) {

fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;

fclose(bfp) ;

fseek(), ftell() and rewind() functions

fseek() - It is used to move the reading control to different positions using fseek function.

ftell() - It tells the byte location of current position of cursor in file pointer.

rewind() - It moves the control to beginning of the file.


C - Error Handling
As such, C programming does not provide direct support for error handling
but being a system programming language, it provides you access at lower
level in the form of return values. Most of the C or even Unix function calls
return -1 or NULL in case of any error and set an error code errno. It is set
as a global variable and indicates an error occurred during any function call.
You can find various error codes defined in <error.h> header file.

So a C programmer can check the returned values and can take appropriate
action depending on the return value. It is a good practice, to set errno to 0
at the time of initializing a program. A value of 0 indicates that there is no
error in the program.

errno, perror(). and strerror()


The C programming language provides perror() and strerror() functions
which can be used to display the text message associated with errno.

The perror() function displays the string you pass to it, followed by a colon, a
space, and then the textual representation of the current errno value.

The strerror() function, which returns a pointer to the textual representation of


the current errno value.

Let's try to simulate an error condition and try to open a file which does not
exist. Here I'm using both the functions to show the usage, but you can use
one or more ways of printing your errors. Second important point to note is
that you should use stderr file stream to output all the errors.

#include <stdio.h>
#include <errno.h>
#include <string.h>

extern int errno ;

int main () {
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");

if (pf == NULL) {

errnum = errno;
fprintf(stderr, "Value of errno: %d\n", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %s\n", strerror( errnum ));
}
else {

fclose (pf);
}

return 0;
}

When the above code is compiled and executed, it produces the following
result

Value of errno: 2
Error printed by perror: No such file or directory
Error opening file: No such file or directory

Divide by Zero Errors


It is a common problem that at the time of dividing any number,
programmers do not check if a divisor is zero and finally it creates a runtime
error.

The code below fixes this by checking if the divisor is zero before dividing

#include <stdio.h>
#include <stdlib.h>

main() {
int dividend = 20;
int divisor = 0;
int quotient;

if( divisor == 0){


fprintf(stderr, "Division by zero! Exiting...\n");
exit(-1);
}

quotient = dividend / divisor;


fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(0);
}

When the above code is compiled and executed, it produces the following
result

Division by zero! Exiting...

Program Exit Status


It is a common practice to exit with a value of EXIT_SUCCESS in case of
program coming out after a successful operation. Here, EXIT_SUCCESS is a
macro and it is defined as 0.

If you have an error condition in your program and you are coming out then
you should exit with a status EXIT_FAILURE which is defined as -1. So let's
write above program as follows

#include <stdio.h>
#include <stdlib.h>

main() {

int dividend = 20;


int divisor = 5;
int quotient;

if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}

quotient = dividend / divisor;


fprintf(stderr, "Value of quotient : %d\n", quotient );

exit(EXIT_SUCCESS);
}

When the above code is compiled and executed, it produces the following
result

Value of quotient : 4

Error Handling
C language does not provide direct support for error handling. However few method and variable
defined in error.h header file can be used to point out error using return value of the function call. In
C language, a function return -1 or NULL value in case of any error and a global variable errno is set
with the error code. So the return value can be used to check error while programming.
C language uses the following functions to represent error

perror() return string pass to it along with the textual represention of current errno value.

strerror() is defined in string.h library. This method returns a pointer to the string representation

of the current errno value.

Example
#include <stdio.h>

#include <errno.h>
#include <stdlib.h>

#include <string.h>

extern int errno;

main( )

char *ptr = malloc( 1000000000UL); //requesting to allocate 1gb memory space

if ( ptr == NULL ) //if memory not available, it will return null

puts("malloc failed");

puts(strerror(errno));

exit(EXIT_FAILURE); //exit status failure

else

free( ptr);

exit(EXIT_SUCCESS); //exit status Success

Here exit function is used to indicate exit status. Its always a good practice to exit a program with a
exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of
program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit.
It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.

Unit 4
VDU:-

VDU
Stands for "Visual Display Unit." A VDU displays images generated by a
computer or other electronic device. The term VDU is often used
synonymously with "monitor," but it can also refer to another type of
display, such as a digital projector. Visual display units may
be peripheral devices or may be integrated with the other components.
For example, the Apple iMac uses an all-in-one design, in which the
screen and computer are built into a single unit.
Early VDUs were primarily cathode ray tube (CRT) displays and typically
had a diagonal size of 13 inches or less. During the 1990s, 15" and 17"
displays became standard, and some manufacturers began producing
displays over 20" in size. At the turn of the century, flat panel displays
became more common, and by 2006, CRT displays were hard to find.
Today, it is common for computers to come with VDUs that are 20" to
30" in size. Thanks to the recent growth in LCD, plasma,
and LED technology, manufacturing large screens is much more cost
effective than before.

ntroduction

Computer graphics is a powerful and interesting feature of the any computer


system. Use of graphics makes the computer applications beautiful and effective.
In this tutorial we are going to learn about the c graphics programming.
Graphics programming in C is very simple and interesting. It is mainly used to
develop games, create projects and for putting the animation..
Before going further it is necessary to get familiar about some of the basic terms of
graphics which are as follows:

a.Pixels
b.Resolution
c.Video Display Unit
d.Display Screens (Monitors)

Pixels:

Pixel is a basic unit of any image in computer graphics. In other words one can say
images are made up of small dots or squares which are termed as picture elements
or pixels.
Pixels are generally used for the representation of any picture in computers
memory.

Resolution:

Resolution is number of distinct pixels present in one dimension that can be


displayed.
Screen resolution is the number of pixels present on the screen.
The display resolution is defined by the number of rows called scan lines from top
to bottom (Y-axis) and number of pixels from left to right (X-axis).
For example if an image has a resolution of 640480 on the screen it means that
640480 screen is capable of displaying distinct dots on 480 scan lines and about
300,000 pixels.

Video Display Unit:

Video Display Unit is used to provide the interface between computer and user.
User can operate on the computer system without printer, disk driver but without
VDU he would be operate blind means it is impossible to operate on the computer
system without video display unit.
Video display unit is a combination of two components:
(a) Video screen
(b) Video display adapter

(a) Video screen is the screen on which we actually see the images in either text or
graphics.

(b) Video display adapter is a special printed circuit board that plugs into the one
of the several expansion slots present on the mother board of a computer system.

How are the images either text or graphics, produced on the screen?
This Task is done by the display adapter because it is not possible for the
microprocessor to send signal necessary to produce the image on the screen. So in
this case display adapter acts as an agent between the video screen and the
microprocessor.
Video display adapter done this work with the help of following components:
(1) VDU memory on which microprocessor writes the information to be produced
on the screen.
(2) Display Adapter circuitry which transfers the information from video memory to
screen.
In this way image is produced on the screen.

There are various types of Display adapters which are supported by 8086
microprocessor family:
(a) Monochrome display adapter (MA)
(b) Hercules display adapter
(c) Color Graphics adapter (CGA)
(d) Enhanced Graphics Adapter (EGA)
(e) Multicolor Graphics Adapter (MCGA)
(f) Video Graphics Adapter (VGA)
(g) Super Video Graphics Adapter (SVGA)
(h) Extended Graphics Adapter (XGA)

Monochrome display adaptor (MA) was the first display adapter. This is a simple
adapter which can only operates on text mode. It has no capability to operates on
the Graphics mode.

Hercules Display Adapter is an advance version of the MA. It has all the features of
the MA but in additionally it can also operate in Graphics mode.

Color Graphics Adapter (CGA)was in demand for several years but for todays
perspectives it has very limited qualities. This adapter can also operate on both text
and graphics mode like Hercules Display Adapter. In text mode it operates in 25
rows by 80 columns mode with 16 colors. In Graphics mode two resolutions are
available medium resolutions graphics mode (320200) with four colors available
from a palette of 16 and two colors mode (640200).

Multicolor Graphics Adapter (MCGA) This display adapter is an advance version of


the EGA. It also includes all the functionality and display modes of MA, CGA and
EGA. It additionally includes two more graphics modes one is 640480 pixel mode
in 2 colors and second is 320200 pixel mode in 256 color.
Video Graphics Array (VGA)The VGA supports all the display modes of MA, CGA,
EGA and MCGA. In addition it also supports the graphics mode of resolution
640480 in 16 colors.

SVGA and XGA are also includes all the functions and display modes of all already
discussed display adapters. SVGA includes two more display modes of resolution
800600 and 1024768 and XGA also includes two new modes: 640480 pixel
mode with 65536 colors and 1024768 pixel mode with 256 color.

Display Screens (Monitors)

Any graphical image is also influenced by the Display screen or monitor. Many
monitors cannot produce color or graphics, some produce poor quality of images
and some are also there to produce good quality of images. Each display adapter
supports certain type of monitors. There are various monitor used with the 8086
microprocessor based computer system which are mentioned below:
(a) Monochrome monitors
(b) Composite monochrome monitors
(c) Composite color monitors
(d) TV sets
(e) RGB monitors
(f) VGA monitors
(g) VGA color monitors

Monochrome monitors use to display high resolution text, but these monitors have
not any ability to display graphics. These types of monitors can only work with the
Monochrome Adapter (MA).

Composite monochrome monitors work with the Color Graphics Adapter (CGA).
These monitors provide a fairly good one color image. These types of monitors can
display text or graphics but not able to generate colors.

Composite color monitors produce not only text and graphics but also colors. The
demerit of these types of monitors is that these have some serious limitations like a
80-column display is often unreadable and these have very short number of color
combinations and images produce through these type of system are not good in
quality and resolutions.
TV SETS are almost same as the composite color monitor technically. These types of
monitor produce very low quality of images. "Text displays must be in 40 column or
20 colors mode to ensure that text is readable"

RGB Monitors are the best monitors among the all types of monitors. These
monitors produce high quality of text as well as images of high quality and high
resolution with a big number of color combinations. These monitors operate on
three input signal to encode the primary colors Red, Green, Blue.

VGA Mono Monitors are used to produces output on VGA or MCGA system. VGA
Color Monitors are typically used in computers equipped with VGA card.

display modes
The term display mode refers to the characteristics of a computer display, in
particular the maximum number of colors and the maximum
image resolution (in pixels horizontally by pixels vertically). There are several
display modes that can be found in personal computer (PC) systems today.

The earliest displays for personal computers were monochrome monitors that
were used in word processors and text-based computer systems in the 1970s.
In 1981, IBM introduced the Color Graphics Adapter (CGA). This display
system was capable of rendering four colors, and had a maximum resolution
of 320 pixels horizontally by 200 pixels vertically. While CGA was all right for
simple computer games such as solitaire and checkers, it did not offer
sufficient image resolution for extended sessions of word processing, desktop
publishing, or sophisticated graphics applications.

In 1984, IBM introduced the Enhanced Graphics Adapter (EGA) display. It


allowed up to 16 different colors and offered resolution of up to 640 x 350.
This improved the appearance over earlier displays, and made it possible to
read text easily. Nevertheless, EGA did not offer sufficient image resolution for
high-level applications such as graphic design and desktop publishing. This
mode has become essentially obsolete, although it is sometimes found in old
word processors and PCs in private homes.

In 1987, IBM introduced the Video Graphics Array (VGA) display system. This
has become the accepted minimum standard for PCs. Some VGA monitors
are still in use today. The maximum resolution depends on the number of
colors displayed. You can choose between 16 colors at 640 x 480, or 256
colors at 320 x 200. All IBM-compatible computers support the VGA standard.

In 1990, IBM intoduced the Extended Graphics Array (XGA) display as a


successor to its 8514/A display. A later version, XGA-2 offers 800 x 600 pixel
resolution in true color (16 million colors) and 1024 x 768 resolution in 65,536
colors. These two image resolution levels are perhaps the most popular in use
today by individuals and small businesses.

The Video Electronics Standards Assocation (VESA) has established a


standard programming interface for Super Video Graphics Array (SVGA)
displays, called the VESA BIOS Extension. Typically, an SVGA display can
support a palette of up to 16,000,000 colors, although the amount of video
memory in a particular computer may limit the actual number of displayed
colors to something less than that. Image-resolution specifications vary. In
general, the larger the diagonal screen measure of an SVGA monitor, the
more pixels it can display horizontally and vertically.

Recently, new specifications have arisen. These include Super Extended


Graphics Array (SXGA) and Ultra Extended Graphics Array (UXGA). The
SXGA specification is generally used in reference to screens with 1280 x 1024
resolution; UXGA refers to a resolution of 1600 by 1200. Nowadays, the older
specifications (VGA and SVGA) are often used simply in reference to their
typical resolution capabilities. The table shows display modes and the
resolution levels (in pixels horizontally by pixels vertically) most commonly
associated with each.
Display Mode Resolution (pixels)

VGA 640 x 480

SVGA 800 x 600

XGA 1024 x 768

SXGA 1280 x 1024

UXGA 1600 x 1200