0% found this document useful (0 votes)
3 views

C Project Work 3rd-Page

This document provides an introduction to the C programming language, highlighting its history, advantages, and applications. It covers basic commands, data types, operators, control structures, and the use of structures and arrays in C programming. Additionally, it includes examples and explanations of algorithms and flowcharts, as well as input and output handling for strings.

Uploaded by

seasonaryan80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C Project Work 3rd-Page

This document provides an introduction to the C programming language, highlighting its history, advantages, and applications. It covers basic commands, data types, operators, control structures, and the use of structures and arrays in C programming. Additionally, it includes examples and explanations of algorithms and flowcharts, as well as input and output handling for strings.

Uploaded by

seasonaryan80
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

CHAPTER ONE

PROJECT WORK ON C

1.1 INTRODUCTION TO C
C programming is a general-purpose, procedural computer
programming language developed in 1972 by Dennis M. Ritchie at
the Bell Telephone Laboratories to develop the UNIX operating
system. C is the most widely used computer language.
Why to Learn C Programming?
C programming language is a must for students and working
professionals to become a great Software Engineer specially when
they are working in Software Development Domain. I will list down
some of the key advantages of learning C Programming:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

Applications of C Programming
C was initially used for system development work, particularly the
programs that make-up the operating system. C was adopted as a
system development language because it produces code that runs
nearly as fast as the code written in assembly language. Some
examples of the use of C are -
⏯ Operating Systems
⏯ Language Compilers
⏯ Assemblers
⏯ Language Interpreters
⏯ Modern Programs
⏯ Databases
⏯ Utilities

1
C Basic Commands
Following are the basic commands in C programming language:

C Basic commands Explanation

This command includes standard input output


#include <stdio.h> header file(stdio.h) from the C library before
compiling a C program

It is the main function from where C program


int main()
execution begins.

{ Indicates the beginning of the main function.

Whatever written inside this command “/* */”


/*_some_comments_*/ inside a C program, it will not be considered for
compilation and execution.

printf(“Hello_World!
This command prints the output on the screen.
“);

This command is used for any character input


getch();
from keyboard.

This command is used to terminate a C program


return 0;
(main function) and it returns 0.

It is used to indicate the end of the main


}
function.

2
1.2 Algorithm and Flowchart
Definition of algorithm and flowchart as below:

Algorithm
It is well known that the programs are used to solve the various kinds
of problems by computerized technique. The algorithm is a step-by-
step procedure that guarantees a solution if followed correctly.

Flowchart
The pictorial representation of a sequence of events that describe
activities required in the program to solve the particular problem is
called a flowchart. Therefore, a flowchart is a pictorial representation
of an algorithm.

Example of algorithm and flowchart:

3
1.3 Structures of C Program
Structure is a group of variables of different data types represented
by a single name. Let’s take an example to understand the need of a
structure in C programming.

How to create a structure in C Programming


We use struct keyword to create a structure in C. The struct
keyword is a short form of structured data type.
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

};

Here struct_name is the name of the structure, this is chosen by the


programmer and can be anything. However, always choose
meaningful, short and easy to read names and avoid using keywords
and reserved words as structure names as those are not allowed.
Members data type can be same or different. Once we have declared
the structure we can use the struct name as a data type like int, float
etc.
First we will see the syntax of creating struct variable, accessing
struct members etc and then we will see a complete example.
How to declare variable of a structure?
struct struct_name {
DataType member1_name;
DataType member2_name;
DataType member3_name;

} var_name;

4
C Structure example
Let's see a simple example of structure in C language.

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Santosh Aryal");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Output:

employee 1 Id : 101
employee 1 Name : Santosh Aryal

5
1.4 Data Type in C
Data type is an instruction that is used to declare the category or
type of variable being used in the program. Any variable used in
the program must be declared before using it.It determines the way
a computer organizes data in memory. It determines how much
space it occupies in storage.

Int: Int represent integer (numbers without fraction). It requires 2


bytes of memory space. It can be either signed or unsigned.
Derived data types from int are short int, long int.

Float: float represents real number (numbers with fraction). It


requires 4 bytes memory space. It can also be signed or unsigned.
Derived data types from float are double, long double.

Char: Char represents single alphabet and symbols (A,f,@,). It


requires 1 byte memory space. It can also be signed or unsigned.

Void : Void data type has no values. It is used as return type for
function that does not return a value.
Example of Data types in c

#include <stdio.h>
int main()
{
int a = 1;
char b = 'G';
double c = 3.14;
printf("Santosh Aryal!\n");
// printing the variables defined
// above along with their sizes
printf("Hello! I am Santosh Aryal. My value is %c and "
"my size is %lu byte.\n",
b, sizeof(char));
// can use sizeof(b) above as well
printf("Hello! I am Santosh Aryal. My value is %d and "

6
"my size is %lu bytes.\n",
a, sizeof(int));
// can use sizeof(a) above as well
printf("Hello! I am Santosh Aryal."
" My value is %lf and my size is %lu bytes.\n",
c, sizeof(double));
// can use sizeof(c) above as well
printf("See you! Have a good day. :)\n");
return 0; }

Output:
Hello Santosh Aryal!
Hello! Santosh Aryal. My value is G and my size is 1 byte.
Hello! Santosh Aryal. My value is 1 and my size is 4 bytes.
Hello! Santosh Aryal floating point variable My value is 3.140000
and my size is 8 bytes.
See you! Have a good day. :)

7
1.5 Arithmetic and Logical Operator in C
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical
operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic
operators are of two types:
a) Unary Operators: Operators that operate or work with a single
operand are unary operators. For example: Increment(++) and
Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two
operands are binary operators. For example: Addition(+),
Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For
example, checking if one operand is equal to the other operand or
not, whether an operand is greater than the other operand or not, etc.
Some of the relational operators are (==, >= , <= )(See this article for
more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b

3. Logical Operators:
Logical Operators are used to combine two or more
conditions/constraints or to complement the evaluation of the
8
original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C
or C++ returns true when both the conditions under consideration
are satisfied. Otherwise, it returns false. Therefore, a && b returns
true when both a and b are true (i.e. non-zero)(See this article for
more reference).
(4 != 5) && (4 < 5); // true

4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the
operands. The operators are first converted to bit-level and then the
calculation is performed on the operands. Mathematical operations
such as addition, subtraction, multiplication, etc. can be performed at
the bit-level for faster processing. For example, the bitwise
AND represented as & operator in C or C++ takes two numbers as
operands and does AND on every bit of two numbers. The result of
AND is 1 only if both bits are 1. (See this article for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010

9
Arithmetic Operators in C
Example
Try the following example to understand all the arithmetic operators
available in C −
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

Output
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

10
Logical Operators in C
Example
Try the following example to understand all the logical operators
available in C −
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 - Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf("Line 3 - Condition is true\n" );
} else {
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 - Condition is true\n" );
}
}

Output:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

11
1.6 Control Structures in Programming Languages

Control Structures are just a way to specify flow of control in


programs. Any algorithm or program can be more clear and
understood if they use self-contained modules called as logic or
control structures. It basically analyzes and chooses in which
direction a program flows based on certain parameters or
conditions.

Program: Write a program to print the given number is even or


odd.

# include<stdio.h>
# include<conio.h>
void main( )
{
int a,b;
clrscr( );
printf(“Enter Two numbers:”);
scanf(“%d%d”, &a,&b);
if( a>b )
printf(“\n %d is largest number”,a);
else
printf(“\n %d is largest number”,b);
getch( );
}

Output:
Enter Two numbers: 13 30
30 is largest number

Program: Write a program to print the given number is even or


odd.

# include<stdio.h>
# include<conio.h>
main( )
{
int n;
clrscr( );
printf(“Enter a number :”);
12
scanf(“%d”, &n);
if( (n%2)==0 )
printf(“\n The given number is EVEN ”);
else
printf(“\n The given number is ODD ”);
getch( );
}

Output :
Run 1 :
Enter a number : 24
The given number is EVEN
Run 2: /* that means one more time we run the program */
Enter a number : 17
The given number is ODD

13
1.7 Array of Structures in C

An array of structres in C can be defined as the collection of multiple


structures variables where each variable contains information about
different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array
of structures is also known as the collection of structures.

Let's see an example of an array of structures that stores information


of 5 students and prints it.

#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}

Output:

Enter Records of 5 students


Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
14
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

15
1.8 Array and Structure
String and Character Array
String is a sequence of characters that are treated as a single data item
and terminated by a null character '\0'. Remember that the C
language does not support strings as a data type. A string is actually a
one-dimensional array of characters in C language. These are often
used to create meaningful and readable programs.

If you don't know what an array in C means, you can check the C
Array tutorial to know about Array in the C language. Before
proceeding further, check the following articles:

 C Function Calls

 C Variables

 C Datatypes

 C Syntax Rules

For example: The string "home" contains 5 characters including the '\
0' character which is automatically added by the compiler at the end
of the string.

Declaring and Initializing a string variables:

// valid

char name[13] = "StudyTonight";

char name[10] = {'c','o','d','e','\0'};

// Illegal

char ch[3] = "hello";

char str[4];

str = "hello";

16
String Input and Output:

 %s format specified to read a string input from the terminal.

 But scanf() function, terminates its input on the first white space
it encounters.

 edit set conversion code %[..] that can be used to read a line
containing a variety of characters, including white spaces.

 The gets() function can also be used to read character string with
white spaces.

char str[20];

printf("Enter a string");

scanf("%[^\n]", &str);

printf("%s", str);

char text[20];

gets(text);

printf("%s", text);

String Handling Functions:

C language supports a large number of string handling functions that


can be used to carry out many of the string manipulations. These
functions are packaged in the string.h library. Hence, you must
include string.h header file in your programs to use these functions.

The following are the most commonly used string handling functions.

Method Description

17
strcat() It is used to concatenate(combine) two strings

strlen() It is used to show the length of a string

strrev() It is used to show the reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

strcat() function in C:

Syntax:

strcat("hello", "world");

strcat() will add the string "world" to "hello" i.e ouput = helloworld.

strlen() and strcmp() function:

strlen() will return the length of the string passed to it


and strcmp() will return the ASCII difference between first
unmatching character of two strings.

int j = strlen("studytonight");

int i=strcmp("study ", "tonight");

printf("%d %d",j,i);

18
12 -1

strcpy() function:

It copies the second string argument to the first string argument.

Example of strcpy() function:

#include<stdio.h>

#include<string.h>

int main()

char s1[50], s2[50];

strcpy(s1, "StudyTonight");

strcpy(s2, s1);

printf("%s\n", s2);

return(0);

Study Tonight

strrev() function:

It is used to reverse the given string expression.

19
Code snippet for strrev():

#include <stdio.h>

int main()

char s1[50];

printf("Enter your string: ");

gets(s1);

printf("\nYour reverse string is: %s",strrev(s1));

return(0);

Enter your string: studytonight


Your reverse string is: thginotyduts

20
1.9 C - 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

C - Strings
Strings are actually one-dimensional array of characters terminated by
a null character '\0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting
of the word "Hello". To hold the null character at the end of the array,
the size of the character array containing the string is one more than
the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the
above statement as follows −

21
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in
C:

Actually, you do not place the null character at the end of a


string constant. The C compiler automatically places the '\0' at the end
of the string when it initializes the array. Let us try to print the above
mentioned string −
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("Greeting message: %s\n", greeting );
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Greeting message: Hello
C supports a wide range of functions that manipulate null-terminated
strings −

Sr.No Function & Purpose


.
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string
s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
22
The following example uses some of the above-mentioned functions –
#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
When the above code is compiled and executed, it produces the
following result:
strcpy( str3, str1) : Hello
strcat( str1, str2): HelloWorld
strlen(str1) : 10

C - Structures
Arrays allow to define type of variables that can hold several data
items of the same kind. Similarly structure is another user defined
data type available in C that allows to combine data items of different
kinds.
Structures are used to represent a record. Suppose you want to keep
track of your books in a library. You might want to track the
following attributes about each book −
 Title
 Author
 Subject
23
 Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member. The
format of the struct statement is as follows −
struct [structure tag] {
member definition;
member definition;
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal
variable definition, such as int i; or float f; or any other valid variable
definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is
optional. Here is the way you would declare the Book structure −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
Accessing Structure Members
To access any member of a structure, we use the member access
operator (.). The member access operator is coded as a period
between the structure variable name and the structure member that we
wish to access. You would use the keyword struct to define variables
of structure type. The following example shows how to use a structure
in a program −
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
24
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Madhav Prasad Regmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Aashish Neupane");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
When the above code is compiled and executed, it produces the
following result:
Book 1 title : C Programming
Book 1 author : Madhav Prasad Regmi
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Aashish Neupane
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

25
1.10 C - Functions
A function is a group of statements that together perform a task.
Every C program has at least one function, which is main(), and all
the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide
up your code among different functions is up to you, but logically the
division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name,
return type, and parameters. A function definition provides the actual
body of the function.
The C standard library provides numerous built-in functions that your
program can call. For example, strcat() to concatenate two
strings, memcpy() to copy one memory location to another location,
and many more functions.
A function can also be referred as a method or a sub-routine or a
procedure, etc.
Defining a Function
The general form of a function definition in C programming language
is as follows −
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function
header and a function body. Here are all the parts of a function −
Return Type − A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform
the desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the function
signature.
Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of
statements that define what the function does.

26
Example
Given below is the source code for a function called max(). This
function takes two parameters num1 and num2 and returns the
maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {

/* local variable declaration */


int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

27
Function Declarations
A function declaration tells the compiler about a function name and
how to call the function. The actual body of the function can be
defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as
follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their
type is required, so the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one
source file and you call that function in another file. In such case, you
should declare the function at the top of the file calling the function.
Calling a Function

While creating a C function, you give a definition of what the


function has to do. To use a function, you will have to call that
function to perform the defined task.
When a program calls a function, the program control is transferred to
the called function. A called function performs a defined task and
when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the
main program.
To call a function, you simply need to pass the required parameters
along with the function name, and if the function returns a value, then
you can store the returned value.

For example –
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main () {
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
28
printf( "Max value is : %d\n", ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
We have kept max() along with main() and compiled the source code.
While running the final executable, it would produce the following
result −
Max value is : 200
Function Arguments

If a function is to use arguments, it must declare variables that accept


the values of the arguments. These variables are called the formal
parameters of the function.
Formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed
upon exit.
While calling a function, there are two ways in which arguments can
be passed to a function −
Sr.No Call Type & Description
.
1 Call by value
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes made to
the parameter inside the function have no effect on the
argument.
2 Call by reference
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the
actual argument used in the call. This means that changes made

29
to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, it
means the code within a function cannot alter the arguments used to
call the function.

30
1.11 File Handling in C

In programming, we may require some specific input data to be


generated several numbers of times. Sometimes, it is not enough to
only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again. However, if we
need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file
handling in C.

File handling in C enables us to create, update, read, and delete the


files stored on the local file system through our C program. The
following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling

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

No. Functio Description


n

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file


31
5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position

8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

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

Opening File: fopen()

We must open a file before it can be read, write, or update. The


fopen() function is used to open a file. The syntax of the fopen() is
given below.

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

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific


location, then we must mention the path at which the file is
stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

We can use one of the following modes in the fopen() function.

Mode Description

r opens a text file in read mode

32
w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer.
The buffer is used to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character
of the file.

Consider the following example which opens a file in write mode.

#include<stdio.h>
void main( )
{
FILE *fp ;
33
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Output
The content of the file will be printed.

#include;
void main( )
{
FILE *fp; // file pointer
char ch;
fp = fopen("file_handle.c","r");
while ( 1 )
{
ch = fgetc ( fp ); //Each character of the file is read and stored in the
character file.
if ( ch == EOF )
break;
printf("%c",ch);
}
fclose (fp );
}
Closing File: fclose()

The fclose() function is used to close a file. The file must be closed
after performing all the operations on it. The syntax of fclose()
function is given below:

C fprintf() and fscanf()

34
Writing File : fprintf() function

The fprintf() function is used to write set of characters into file. It


sends formatted output to a stream.

Syntax:

int fprintf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file by fprintf...\n");//writing data into file
fclose(fp);//closing file
}
Reading File : fscanf() function

The fscanf() function is used to read set of characters from file. It


reads a word from the file and returns EOF at the end of file.

Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])

Example:

#include <stdio.h>
main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}

Output:

Hello file by fprintf...


35
C File Example: Storing employee information

Let's see a file handling example to store employee information as


entered by user from console. We are going to store id, name and
salary of the employee.

#include <stdio.h>
void main()
{
FILE *fptr;
int id;
char name[30];
float salary;
fptr = fopen("emp.txt", "w+");/* open for writing */
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the id\n");
scanf("%d", &id);
fprintf(fptr, "Id= %d\n", id);
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name= %s\n", name);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary= %.2f\n", salary);
fclose(fptr);
}

Output:

Enter the id
1
Enter the name
sonoo
Enter the salary
120000

36
Now open file from current directory. For windows operating system,
go to TC\bin directory, you will see emp.txt file. It will have
following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000

37
CHAPTER TWO:
RESULTS AND DISCUSSION
It was identified early on that testing and evaluation of the source
code would determine a successful program. Each group member
was responsible for checking their code construction so that final
compilation could run smoothly.

38
CHAPTER THREE:
SUMMARY AND
CONCLUSION
Summary

It was discovered that C programming was a versatile tool. Though


it proved to be challenging to use and manipulate; as with any
language understanding the basics is essential before any further
progress can be made.

Conclusion
Though the common trend among us (students) is to take these
academic activities as a formal job (which is correct for a different
point of view), I really enjoyed doing this project. I started the work
the first day I got my copy of assignment and completed 90%
excluding printing and binding jobs within a week and spent some
days on its moderation. Now, I am satisfied with my project and the
report.

Time management was crucial for this project. With the desire to
create a working program and with the limitations of time, it was
decided to create a simpler version that would work but still prove
the principle and solve the problem.

39
Bibliography
JAAVAPoints . (2079, 04 26). Retrieved 04 26, 2079,
from JAAVAPoints :
https://www.javatpoint.com/array-of-structures-in-c

Tutorial . (2022, 08 12). Retrieved 04 26, 2079, from Tutorial :


https://www.tutorialspoint.com/cprogramming/c_pointers.htm
w3schools. (2079, 04 26). Retrieved 04 26, 2079, from w3schools:
https://www.w3schools.com/c/c_intro.php
Greeks for greek.com etc.

40

You might also like