Beruflich Dokumente
Kultur Dokumente
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
string.h All string related functions are defined in this header file
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
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.
int main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);
printf("Enter salary: \n");
scanf("%f", &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( ) {
return 0;
}
When the above code is compiled and executed, it produces the following result
Memory size occupied by data : 20
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");
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( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
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];
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.
int main () {
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 () {
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 */
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.
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;
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
9 Macro does not Check Compile Errors Function Checks Compile Errors
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
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
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
int *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.
struct employee
char *name;
int salary;
};
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
int *x;
x=(int*)malloc(50 * sizeof(int));
calloc() malloc()
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with garbage
value. values.
calloc() malloc()
Syntax : Syntax :
malloc calloc
The name malloc stands for memory The name calloc stands for contiguous
allocation. allocation.
malloc() takes one argument that is, number calloc() take two arguments those
of bytes. are: number of blocks and size of each block.
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.
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>
if( argc == 2 ) {
else {
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
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>
if( argc == 2 ) {
else {
}
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
Syntax :
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.
#include <stdio.h>
#include <conio.h>
int i;
for(i=1;i< argc;i++)
printf("%s\t",argv[i]);
}
}
else
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.
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.
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.
#include<conio.h>
void main()
int i;
printf("Enter a value");
scanf("%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");
#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.
#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 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.
#include <stdio.h>
int main( ) {
int 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];
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;
$./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().
scanf()
printf
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
\n - New line
\b - Backspace
\f - Move to next page
\v - Vertical Tab
\t - Horizontal Tab
\\ - Back slash
\" - Double quote
\' - Single quote
\a - alert
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()
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.
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:
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().
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.
File
Meaning of Mode During Inexistence of file
Mode
File
Meaning of Mode During Inexistence of file
Mode
Open for both reading and writing If the file does not exist, fopen() returns
rb+
in binary mode. NULL.
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.
File
Meaning of Mode During Inexistence of file
Mode
Closing a File
The file (both text and binary) should be closed after reading/writing.
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.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
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.
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fscanf(fptr,"%d", &num);
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.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *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.
fread(address_data,size_data,numbers_data,pointer_to_file);
#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");
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.
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.
Whence Meaning
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");
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.
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
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.
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
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
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
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);
}
Reading a File
Given below is the simplest function to read a single character from a file
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
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 );
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...
C provides a number of functions that helps to perform basic file operations. Following are the
functions,
Function description
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
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.
#include<conio.h>
main()
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
putc(ch,fp);
fclose(fp);
fp = fopen("one.txt", "r");
printf("%c",ch);
fclose(fp);
#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");
fclose(p);
do
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.
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";
if (bfp) {
fclose(bfp) ;
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.
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.
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.
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>
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
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;
exit(0);
}
When the above code is compiled and executed, it produces the following
result
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() {
if( divisor == 0) {
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
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
Example
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
main( )
puts("malloc failed");
puts(strerror(errno));
else
free( ptr);
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
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:
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).
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.
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 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.