Unit I
Introduction to C Programming
Constants
Constants are the fixed values that never change during the execution of a program. Following are the various types of constants:
Integer constants
An integer constant is nothing but a value consisting of digits or numbers. These values never change during the execution of a program. Integer constants can be octal, decimal and hexadecimal.
Example, 111, 1234
Above are the valid decimal constants.
2. Octal constant contains digits from 0-7, and these types of constants are always preceded by 0.
Example, 012, 065
Above are the valid decimal constants.
3. Hexadecimal constant contains a digit from 0-9 as well as characters from A-F. Hexadecimal constants are always preceded by 0X.
Example, 0X2, 0Xbcd
Above are the valid hexadecimal constants.
The octal and hexadecimal integer constants are very rarely used in programming with 'C'.
Character constants
A character constant contains only a single character enclosed within a single quote (''). We can also represent character constant by providing ASCII value of it.
Example, 'A', '9'
Above are the examples of valid character constants.
String constants
A string constant contains a sequence of characters enclosed within double quotes ("").
Example, "Hello", "Programming"
These are the examples of valid string constants.
Real Constants
Like integer constants that always contains an integer value. 'C' also provides real constants that contain a decimal point or a fraction value. The real constants are also called as floating point constants. The real constant contains a decimal point and a fractional value.
Example, 202.15, 300.00
These are the valid real constants in 'C'.
A real constant can also be written as,
Mantissa e Exponent
For example, to declare a value that does not change like the classic circle constant PI, there are two ways to declare this constant
#include <stdio.h>
int main() {
const double PI = 3.14;
printf("%f", PI);
//PI++; // This will generate an error as constants cannot be changed
return 0;}
2. By using the #define pre-processor directive which doesn't use memory for storage and without putting a semicolon character at the end of that statement
#include <stdio.h>
#define PI 3.14
int main() {
printf("%f", PI);
return 0;}
Variable
A variable is an identifier which is used to store some value. Constants can never change at the time of execution. Variables can change during the execution of a program and update the value stored inside it.
A single variable can be used at multiple locations in a program. A variable name must be meaningful. It should represent the purpose of the variable.
Example: Height, age, are the meaningful variables that represent the purpose it is being used for. Height variable can be used to store a height value. Age variable can be used to store the age of a person
A variable must be declared first before it is used somewhere inside the program. A variable name is formed using characters, digits and an underscore.
Following are the rules that must be followed while creating a variable:
Following are the examples of valid variable names in a 'C' program:
height or HEIGHT
_height
_height1
My_name
Following are the examples of invalid variable names in a 'C' program:
1height
Hei$ght
My name
For example, we declare an integer variable my_variable and assign it the value 48:
int my_variable;
my_variable = 48;
By the way, we can both declare and initialize (assign an initial value) a variable in a single statement:
int my_variable = 48;
Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in the C language.
A list of 32 keywords in the c language is given below:
auto | break | case | char | Const | continue | default | do |
double | else | enum | extern | Float | for | goto | if |
int | long | register | return | Short | signed | sizeof | static |
struct | switch | typedef | union | Unsigned | void | volatile | while |
Operators
An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
Arithmetic Operators
Relational Operators
Shift Operators
Logical Operators
Bitwise Operators
Ternary or Conditional Operators
Assignment Operator
Misc Operator
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* & sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | << >> | Left to right |
Relational | < <= > >= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Bitwise Operators: These operators are used to work on the each bits of data. These operators can work on the binary data. If the data is non binary then computer first of all convert it into binary form and then perform the operation. Following are the list of logical operator in C language. To understand the operation assume variable A contains value 10 and variable contains value 5. So the binary values of
A = 0000 1010 and
B = 0000 0101
Sr. No. | Operator | Description | Example |
1. | & | This is bitwise AND | Result of (A&B) is 0000 0000 |
2. | | | This is bitwise OR | Result of (A|B) is 0000 1111 |
3. | ^ | This is bitwise Exclusive | Result of (A^B) is 0000 1111 |
4. | << | This is used to shift bit on left side | Result of (A<<B) is |
5. | >> | This is used to shift bit on right side | Result of (A>>B) is |
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter two numbers");
scanf("%d %d",&a,&b);
printf("\n Result of bitwise and operator of %d and %d is %d",a,b,a&b);
printf("\n Result of bitwise or operator of %d and %d is %d",a,b,a|b);
printf("\n Result of bitwise exclusive operator of %d and %d is %d",a,b,a^b);
printf("\n Result of bitwise left shift operator of %d and %d is %d",a,b,a<<b);
printf("\n Result of bitwise right shift operator of %d and %d is %d",a,b,a>>b);
getch();
}
Output:
Output:
Enter two numbers
5
3
Result of bitwise and operator of 5 and 3 is 1
Result of bitwise or operator of 5 and 3 is 7
Result of bitwise exclusive operator of 5 and 3 is 6
Result of bitwise left shift operator of 5 and 3 is 40
Result of bitwise right shift operator of 5 and 3 is 0
Decision Control
Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of the programming languages −
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
Sr.No. | Statement & Description |
1 | An if statement consists of a boolean expression followed by one or more statements. |
2 | An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. |
3 | You can use one if or else if statement inside another if or else if statement(s). |
4 | A switch statement allows a variable to be tested for equality against a list of values. |
5 | You can use one switch statement inside another switch statement(s). |
The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
Looping Statements
You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
C programming language provides the following types of loops to handle looping requirements.
Sr.No. | Loop Type & Description |
1 | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
2 | Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
3 | It is more like a while statement, except that it tests the condition at the end of the loop body. |
4 | You can use one or more loops inside any other while, for, or do..while loop. |
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
Sr.No. | Control Statement & Description |
1 | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
2 | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
3 | Transfers control to the labeled statement. |
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.
Array:
Array is a data structure which stores the collection of similar types of element in consecutive memory locations. Indexing of array always start with ‘0’ where as non-graphical variable ‘\0’ indicates the end of array. Syntax for declaring array is
data type array name[Maximum size];
Example:
Sr. No. | Instructions | Description |
#include<stdio.h> | Header file included | |
2. | #include<conio.h> | Header file included |
3. | void main() | Execution of program begins |
4. | { | Memory is allocated for variable i,n and array a |
5. | int i,n,a[10]; | |
6. | clrscr(); | Clear the output of previous screen |
7. | printf("enter a number"); | Print “enter a number” |
8. | scanf("%d",&n); | Input value is stored at the addres of variable n |
9. | for(i=0;i<=10;i++) | For loop started from value of i=0 to i=10 |
10. | { | Compound statement(scope of for loop starts) |
11. | a[i]=n*i; | Result of multiplication of n and I is stored at the ith location of array ieas i=0 so it is stores at first location. |
12. | printf("\n %d",a[i]); | Value of ith location of the array is printed |
13. | } | Compound statement(scope of for loop ends) |
14. | printf("\n first element in array is %d",a[0]); | Value of first element of the array is printed |
15. | printf("\n fifth element in array is %d",a[4]); | Value of fifth element of the array is printed |
16. | printf("\n tenth element in array is %d",a[9]); | Value of tenth element of the array is printed |
17. | getch(); | Used to hold the output screen |
18. | } | Indicates end of scope of main function |
Function:
Similar to other languages C language also provides the facility of function. Function is the block of code which is used to perform a specific task. In c language the complete program is composed of function.
Functions are useful to divide c programs into smaller modules. Programmer can invoked these modules anywhere inside c program for any number of times.
Functions are used to increase readability of the code. Size of program can be reduce by using functions. By using function, programmer can divide complex tasks into smaller manageable tasks and test them independently before using them together.
Functions of C language are defined with the type of function. The type of functions indicates the data type of value which will return by function. In order to use function in the program, initially programmer have to inform compiler about the function. This is also called as defining a function.
In C program all the function definition present outside the main function. All function need to be declared and defined before use. Function declaration requires function name, argument list, and return type.
The syntax for defining a function is as follows.
Return Type Function name (Argument list)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
In the above syntax, return type indicates the data type of value return by the function. If return type is not written then by default “int” data type is consider.
Function name can be any alphanumeric value which is satisfying the rules used to define variable name and can be as long as 31 characters.
The argument list is a formal list that includes data type and variable name combination. Each argument must be separated by comma.
The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket “{“ and ends with a closing curly bracket “}”. Everything between these two curly brackets belongs to the function.
There are two types of functions in c language.
1. Library Functions
A function which is predefined in c language is called library function. Library function is also called as built in function of C language. The definition of library function is stored in respective header file. Library functions are used to perform dedicated operation like taking input from user, displaying output, string handling operation, etc. Library functions are readily available and programmer can directly use it without writing any extra code. For example, printf () and scanf () are library function and their definition is stored in stdio header file.
2. User Defined Functions
User define function is the block of code written by programmer to perform a particular task. As compiler doesn’t have any idea about the user define function so programmer has to define and declare these functions inside the program body. Programmer can define these function outside the main function but declaration of user define function should present in main function only. Whenever compiler executes function call (function declaration) then compiler shift the flow of program execution to the definition part of user define function.
Example
#include <stdio.h>
#include<conio.h>
int add (int x, int y)
{
int sum;
sum = x + y;
return (sum);
}
main ()
{
int a,b,c;
a = 15;
b = 25;
c = add(a,b);
printf ("\n Addition is %d ", c);
}
Output:
Addition is 40
There are two ways to pass the parameters to the function
1. Parameter Passing by value
In this mechanism, the value of the parameter is passed while calling the function.
2. Parameter Passing by reference
In this mechanism, the address of the parameter is passed while calling the function.
Recursive Functions
A recursive function performs the tasks by dividing it into the subtasks. There is a termination condition defined in the function which is satisfied by some specific subtask. After this, the recursion stops and the final result is returned from the function.
The case at which the function doesn't recur is called the base case whereas the instances where the function keeps calling itself to perform a subtask, is called the recursive case. All the recursive functions can be written using this format.
Pseudocode for writing any recursive function is given below.
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
Enter the value of n?12
144
Memory allocation of Recursive method
Each recursive call creates a new copy of that method in the memory. Once some data is returned by the method, the copy is removed from the memory. Since all the variables and other stuff declared inside function get stored in the stack, therefore a separate stack is maintained at each recursive call. Once the value is returned from the corresponding function, the stack gets destroyed. Recursion involves so much complexity in resolving and tracking the values at each recursive call. Therefore we need to maintain the stack and track the values of the variables defined in the stack.
Let us consider the following example to understand the memory allocation of the recursive functions.
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained which prints the corresponding value of n until n becomes 0, Once the termination condition is reached, the stacks get destroyed one by one by returning 0 to its calling stack. Consider the following image for more information regarding the stack trace for the recursive functions.
Pointers
One of the vital and heavily used feature ‘C’ is pointer. Most of the other programming languages also support pointers but only few of them use it freely. Support pointers but only few of them use it freely.
When we declare any variable in C language, there are three things associated with that variable.
1. Data type of variable : Data type defines the type of data that variable can hold. Data type tells compiler about the amount of memory allocate to the variable.
2. Address of Variable : Address of variable represent the exact address of memory location which is allocated to variable.
3. Value of variable : It is the value of variable which is store at the address of memory location allocated to variable.
Example : int n = 5;
In the above example ‘int’ is the data type which tells compiler to allocate 2 bytes of memory to variable ‘n’.
Once the variable is declare compiler allocated two bytes of memory to variable ‘n’. Suppose the address of that memory location is 1020. At the address of memory location 1020 the value 5 is store.
Memory map for above declaration is as follows.
use of &,/and ‘*’ operator
Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,
printf (“Enter two numbers”);
scanf (“%d%d”, & a,&b);
c=a+b;
printf(“/n Addition is %d”, C);
printf(“/n Address of variable C is %d”, &C);
getch ();
}
of above program we used operator ‘%’ and ‘&’ ‘%d’ is the access specifier which tells compiler to take integer value as a input whereas. ‘&a’ tells compile to store the taken value at the address of variable ‘a’.
In the ninth instruction compiler will print me value of ‘C’ so the output of 9th instruction is as follows.
Addition is 5 [Note : considering a = 2 and b = 3]
In the tenth instruction compiler will print me address of variable C.
So the output of lenth instruction is as follows. Address of variable C is 1020.
Now consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf(“Enter two numbers”);
scanf(“%d %d”, & a, &b);
c=a+b;
printf(“\n Addition is %d”,C);
printf(“\n Address of variable C is %d”,&C);
printf(‘\n value of variable C is %d”, *(&C));
getch();
}
Now, we all are clear about the output of instruction 9 and 10.
In the 11th instruction, operator *and & is used. ‘*’ operator tells compile to pickup the value which is stored at the address of variable C. So the output of 11th instruction is as follow. Value of variable C is 5 [considering a = 24 b = 3;]
Declaration of Pointer
Pointers are declare with the help of operator ‘*’. ‘*’ is known as ‘value at address’. Pointers are the variables which are used to store the address of another variable As the address of variable is always whole numbers so pointer always contains whole numbers. The declaration of pointer are as follows.
Syntax : Data type * pointer Name.
Example: int *I;
Data type defines the type of value defined at the address of pointer variable. In the above example value at the address of ‘I’ is of type integer.
Consider the following program.
# include<stdio.h>
# include<conio.h>
void main()
{
int a,b,c;
int *p,*q,*r;
p=&a;
q=&b;
r=&c;
printf(“Enter two numbers”);
scanf(“%d%d,&a,&b);
c=a + b;
printf(“\n Address of variable C is %d”,&C);
printf(“\n Address of variable C is %d,r);
printf(“\n Address of variable r is %d”,&r);
printf(“\n value of variable C is %d”,C);
printf(“\n value of variable C is %d,*^);
getch ();
}
In the above program variable ‘r’ is the integer pointer which holds the address of variable ‘C’
Case 1: In ‘printf’ statement whenever we used (“%d”,r) men me value of r is printed but ‘r’ is holding the address of variable ‘C’. so, address of variable C is copied to the value of ‘r’ and it is printed on output screen
Case 2: Whenever we used (“%d”,&r) in ‘printf’ function men the address of variable ‘r’ is pointed on o/p screen.
Case 3: When we used (“%d”,*r) in pointf function at mat time value which is stored at the address which holds by variable ‘r’ is printed.
Now me variable ‘r’ is holding the address of variable ‘C’. So, the value which is stored at the address of ‘C’ is printed on the output screen.
Consider the following example.
#include<stdio.h>
#include<conio.h>
void main()
{
int a=3;
int *p;
p=&a;
printf(“\n%d”,a);
printf(“\n%d”,&a);
printf(“\n%d”,P);
printf(“\n%d”,&P);
printf(“\n%d”,*P);
printf(“\n%d”,*(&a));
}
Run the above program on the computer system so that you will familiar with the basic use of pointers. Following is the explanation O/p of above program.
Data type of pointer variable can be anything. Such as char *C;
In the above instruction pointer ‘C’ is of type character so the variable ‘C’ can store the address of variable which contains character type of value. Consider the following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int I,*ip;
char C, *cp;
I = 3;
ip = & I;
c=’M’;
cp=&c;
printf(“%d”,I);
printf(“\n%d”,*ip);
printf(“\n%C;,C);
printf(“\n%c”, *cp);
getch();
}
The output of above program is.
3
3
m
m
Advantages of pointer
1. With the help of pointer, programmer can pass the value to the function by using call be reference.
2. Dynamic memory allocation is positive because of pointer.
3. Pointers are useful in designing linked list and other algorithmic data structure.
4. Faster access of data is positive because of pointer as pointer points to physical memory locations.
String Manipulations
Strings are also called as the array of character.
Char string name[size of string];
Char is the data type, user can give any name to the string by following all the rules of defining name of variable. Size of the string is the number of alphabet user wants to store in string.
Example:
Sr. No. | Instructions | Description |
#include<stdio.h> | Header file included | |
2. | #include<conio.h> | Header file included |
3. | void main() | Execution of program begins |
4. | { | String is declare with name str and size of storing 10 alphbates |
5. | char str[10]; | |
6. | clrscr(); | Clear the output of previous screen |
7. | printf("enter a string"); | Print “enter a string” |
8. | scanf("%s",&str); | Entered string is stored at address of str |
9. | printf("\n user entered string is %s",str); | Print: user entered string is (string entered by user) |
10. | getch(); | Used to hold the output screen |
11. | } | Indicates end of scope of main function |
Following are the list of string manipulation function
Sr. No. | String Function | Purpose |
strcat | use to concatenate (append) one string to another | |
2. | strcmp | use to compare one string with another. (Note: The comparison is case sensitive) |
3. | strchr
| use to locate the first occurrence of a particular character in a given string |
4. | strcpy | use to copy one string to another. |
5. | strlen | use to find the length of a string in bytes, |
Structure:
1. It is the user define data type. With the help of structure user can define different types of variables under the shelter of one common name. Syntax for defining structure is as follows
struct structure_name
{
structure element1;
structure element1;
structure element1;
:
:
:…..
};
Example:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[100];
int roll_no;
};
void main()
{
struct student s;
printf("Enter name of student");
scanf("%s",&s.name);
printf("\n Enter roll number");
scanf("%d",&s.roll_no);
printf("\n Roll number of %s is %d",s.name,s.roll_no);
getch();
}
Output:
Enter name of student
Raushan
Enter roll number
92
Roll number of Raushan is 92
Union:
It is the user define data type. With the help of union user can define different types of variables under the shelter of one common name. Syntax for defining union is as follows
union union _name
{
union element1;
union element1;
union element1;
:
:
:…..
};
Difference between structure and union
Structure | Union |
1. Size of structure is summation of all elements of structure. | 1. Size of union is size of largest element is union. |
2. ‘struct’ keyword is used to define structure. | 2. ‘union’ keyword is used to define union |
3. All members are initialized with its own memory. | 3. Only first member is initialize. |
4. Size of structure is more than union. | 4. Size of union is less than structure. |
In the above syntax union is a keyword, which is used to define the union. union name can be anything according to the rules of defining names of variable. Within curly brackets user can define the several variables. Size of union is the size of largest element of the union. User can access the elements of union by creating the object of the union.
Example:
#include<stdio.h>
#include<conio.h>
union student
{
char name[100];
int roll_no;
};
void main()
{
union student s;
printf("Enter name of student");
scanf("%s",&s.name);
printf("\n Enter roll number");
scanf("%d",&s.roll_no);
printf("\n Roll number of %s is %d",s.name,s.roll_no);
getch();
}
Output:
Enter name of student
Raushan
Enter roll number
92
Roll number of \ is 92
Enumeration:
Dictionary meaning of enumeration is the ‘act of counting’. Enumeration is the user define data type which is defined by using keyword ‘enum’. Enumeration consists of integer values which are carried out by symbolic names. Enum variable are easy to compare as compiler assign integer values to the enum variable. Enumeration allows user to assign numbers to the names. Enumeration is helpful to increase readability of the code. By default indexing of enumeration starts with ‘0’. Enumeration is used to create numbered list. Syntax for the declaration of enumeration is as follows
enum identifier {enumerator list};
enum identifier object-name;
In the above syntax ‘enum’ is the keyword which is followed by identifier. Identifier is used to define enumeration type but it is not directly used. Enumerator list contains the variables which are used under the tag name identifier. In the enumerator list first name has the value zero, next name has value one and so on, until the explicit values are specified.
Second line in the above syntax represents the definition of enumeration. In the definition of enumeration user need to create the object of enumeration identifier. With the help of this object user can user the variables declare in enumerated list.
Example:
#include<stdio.h> a
#include<conio.h>
void main()
{
enum Friends{Debu,Rani,Tini,Chintu,Pinki};
clrscr();
printf("\n Debu: %d",Debu);
printf("\n Rani: %d",Rani);
printf("\n Tini: %d",Tini);
printf("\n Chintu: %d",Chintu);
printf("\n Pinki: %d",Pinki);
getch();
}
Output:
Debu: 0
Rani: 1
Tini: 2
Chintu: 3
Pinki: 4
MACROS:
Macros are majorly used to allocate names for frequently used constant values.. Macro represents the majorly used instruction in the program. Whenever there is a call for macro then processor replaces the complete definition of macro at the place of macro call, this procedure is known as macro expansion. Macros are expanded by the C preprocessor. Macros are majorly used in assembly language programming. Macros are define before the main function of program. In ‘C’ language ‘#define’ directives are used to define macros. Syntax for defining macro is as follows
# define symbolic-name constant
In the above syntax ‘#define’ is the preprocessor directives which used to define macros. Symbolic name represents the name which is going to allocate for the constant quantity.
Example: # define pi 3.14
In the above instruction macro pi is define for 3.14 value. Whenever compiler get the variable ‘pi’ it will replace it with the value 3.14.
Difference between Macro and Function
Macro | Function |
1. Code execution is faster | 1. Code execution is slower. |
2. Macro cannot be passed as parameter to another macro. | 2. Function can be passed as parameter to another function. |
3. Macro cannot return value. | 3. Function returns value. |
4. Required more memory space. | 4. Required less memory space. |
File:
A file is defined as a collection of records where each record consists of one or more fields. Fields of a file represents attribute of an entity. The primary objective of file organization is to provide a means for record retrieval and update.
Suppose we want to store information of students, then student file could contain following fields.
Roll no | Name | Division | Branch |
Sample data for such file is given in following table
Roll no
| Name | Division | Branch |
1001 | Morris | A | Computer |
1002 | John | C | I.T. |
1003 | Austin | D | Civil |
1004 | David | B | Mechanical |
Table 2.1: Sample data for Student file.
Each row in table represents record while columns represent fields. Operations that can be performed on files are as follows.
If we want to perform I/O file operations in C++ we must include header<fstream> which defines several classes like ifstream, ofstream, and fstream. There are three types of streams, input, output and input/output. Class ifstream is used for input stream, ofstream for output stream and ifstream for input/output stream.
Opening and Closing Files:
First we will see how these files can be opened in c++. File in C++ can be opened in two ways.
Before opening a file it should be linked to appropriate stream i.e input, output or input/output. If we want to create input stream we will write ifstream infile;
For output stream we will write ofstream outfile;
For Input/Output stream we will write fstream iofile;
Assume we want to write data to file named “Example” so we will use output stream. Then file can be opened as follows,
ofstream outfile;
outfile.open(“Example”);
Now if we want to read data from file, so we will use input stream. Then file can be opened as follows,
ifstream infile;
infile.open(“Example”);
File Opening Modes:
The ‘open’ function actually takes 2 arguments. First is filename and second is mode in which we are opening file. This second argument is optional and default values are provided for it if we do not specify it explicitly. The default values are ios::in for ifstream and ios::out for ofstream.
Various file opening modes are
Modes | Description |
ios::in | Open file for read only |
ios::out | Open file for write-only |
ios::app | Append to end of file |
ios::ate | Move to end of file |
ios::nocreate | Open fails if the file does not exits |
ios::noreplace | Open fails if the file already exits |
ios::binary | Open in binary mode. |
ios::trunc | Delete the contents of the existing file. |
2. Using Constructor:
Here we create a file stream object using the appropriate class. Then we initialize the file stream object with the filename.
Eg. ofstream outfile(“Example”)
This opens a file named Example for writing only.
Similarly, ifstream infile(“Example”) opens the file for reading only.
We use member function close() to close a file. The close function neither takes parameters nor returns any value.
Eg. outfile.close();
Program to illustrate working with files.
#include<iostream.h>
#include<fstream.h>
void main()
{
char str1[50];
ofstream out; // create out stream
out.open(“Sample”); //opening file named “Sample” with open function
cout<<”Enter string”;
cin>>str; //accepting string from user
out<<str<<\n”; //writing string to “Sample”file
out.close(); //closing “Sample” file
ifstream in; //create in stream
in.open(“Sample”); // open “Sample” file for reading”
in>>str; reading string from “Sample” file
cout<<”String is”<<str; // display string to user
in.close();
}
Output:
Broadly speaking, there are two types of files: text files and binary files.
3.1: Text Files: A text file is a file of characters that is, letters, numbers, spaces, tabs, and punctuation. If any other data of different data types are present, text file stores them into character equivalent formats. The character may either be encoded in ASCII or EBCDIC. Thus they are also called ASCII(American Standard Code for Information Interchange)files. Text files are generally human-readable. Source code, XML files, HTML files, email, etc can be termed as text files.
Reading and Writing Text Files:
We can perform read and write operations on text files by creating an appropriate stream that is linked to file.
Program to illustrate I/O operations on text files
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream out(“Example”); // opening “Example” file with constructor
out<<1 <<”John”<<”\n”; // writing data to file “Example”
out<<2 <<”Smith”<<”\n”;
out<<3 <<”Jack”<<”\n”;
out.close();
}
Thus we have created a text file “Example” with the following contents.
Example file
Now we will read text file “Example” and display its contents to screen.
#include<iostream.h>
#include<fstream.h>
void main()
{
ifstream in(“Example”); // opening “Example” file for reading
int rollno;
char name[10];
in>>rollno>>name; // reading data from file example
cout<<rollno<<” ”<<name<<”\n” //display data to screen
in>>rollno>>name;
cout<<rollno<<” ”<<name<<”\n”
in>>rollno>>name;
cout<<rollno<<” ”<<name<<”\n”
in.close();
}
Text File Computer Screen
put() and get() functions
put():put()function is used to write an unformatted character.
get():get()function is used to read a unformatted character.
Program to illustrate put() and get() functions. This program writes to file characters entered by user until 0 is typed.
#include <iostream.h>
#include <fstream.h>
void main()
{
char ch;
ofstream out("Example");
do {
ch = cin.get();
out.put(c);
} while (c != '0');
out.close();
}
3.2: Binary Files: Binary file contains text, images, graphics, and even sound. It can contain any type of data encoded in binary form. They are used for computer storage or processing. Object files, images, movies, executables, proprietary document formats, etc. are binary files.
Reading and writing Binary files
I/O operations on binary files are performed with the help of read and write function. The read and write functions can be written as follows.
in.read((char *)&S, sizeof(S));
out.write((char *)&S, sizeof(S));
wherein and out are input and output streams.
Program to illustrate I/O operations on binary files.
#include<iostream.h>
#include<fstream.h>
void main()
{
int marks[5],i;
cout<<”Enter marks”;
for(i=0;i<=5;i++)
cin>>marks[i];
ofstream out;
out.open(“Example”);// open file for writing
out.write((char*)& marks, sizeof(marks));// write data to file
out.close();
ifstream in;
in.open(“Example”); // open file for reading
in.read((char*)& marks, sizeof (marks));// reading data from file
cout<<”Marks are”;
for(i=0;i<=5;i++)
cout<<marks[i]; //displaying data to screen
in.close();
}
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 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.
Writing to a file
To write the file, we must open the file in a mode that supports writing. For example, if you open a file in “r” mode, you won’t be able to write the file as “r” is read only mode that only allows reading.
Example: C Program to write the file
This program asks the user to enter a character and writes that character at the end of the file. If the file doesn’t exist then this program will create a file with the specified name and writes the input character into the file.
#include <stdio.h>
int main()
{
char ch;
FILE *fpw;
fpw = fopen("C:\\newfile.txt","w");
if(fpw == NULL)
{
printf("Error");
exit(1);
}
printf("Enter any character: ");
scanf("%c",&ch);
/* You can also use fputc(ch, fpw);*/
fprintf(fpw,"%c",ch);
fclose(fpw);
return 0;
}
Append a file
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file.
In order to append a new line to the existing file, open the file in append mode.
Program to append file
Let's first see what should be the step-by-step procedure to compare two integers−
START
Step 1 → Take two integer variables, say A & B
Step 2 → Assign values to variables
Step 3 → Compare variables if A is greater than B
Step 4 → If true print A is greater than B
Step 5 → If false print A is not greater than B
STOP
Flow Diagram
We can draw a flow diagram for this program as given below −
Pseudocode
Let's now see the pseudocode of this algorithm −
procedure compare(A, B)
IF A is greater than B
DISPLAY "A is greater than B"
ELSE
DISPLAY "A is not greater than B"
END IF
end procedure
Implementation
Assuming we have file with name file_append.txt with this content −
This text was already there in the file.
Now, we shall see the actual implementation of the program −
#include <stdio.h>
int main()
{
FILE *fp;
char ch;
char *filename = "file_append.txt";
char *content = "This text is appeneded later to the file, using C programming.";
/* open for writing */
fp = fopen(filename, "r");
printf("\nContents of %s -\n\n", filename);
while ((ch = fgetc(fp) )!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
fp = fopen(filename, "a");
/* Write content to file */
fprintf(fp, "%s\n", content);
fclose(fp);
fp = fopen(filename, "r");
printf("\nContents of %s -\n", filename);
while ((ch = fgetc(fp) )!= EOF)
{
printf ("%c", ch);
}
fclose(fp);
return 0;
}
Output
Output of this program should be −
Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.
Reference Books:
1. E Balgurusamy, “Programming in ANSI C”, Tata McGraw-Hill, 3rd Edition.
2. Yedidyah Langsam, Moshe J Augenstein and Aaron M Tenenbaum “Data structures using C and C++” PHI Publications, 2nd Edition.
3. Reema Thareja, “Data Structures using C”, Oxford University Press, 2
nd Edition.