Programming in C
Programming in C
strtok() strxfrm()
User defined Function in C
C programming language allows coders to define functions to perform
special tasks. As functions are defined by users, they are called user-
defined functions. user-defined functions have contained the block of
statements which are written by the user to perform a task.
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.
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) {
return result;
}
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);
Type of User-defined Functions in C
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and a return value
#include<stdio.h>
int greatNum(int x, int y) // function definition
int greatNum(int a, int b); // function declaration {
if(x > y) {
int main() return x;
{ }
int i, j, result; else {
printf("Enter 2 numbers that you want to compare..."); return y;
scanf("%d%d", &i, &j); }
result = greatNum(i, j); // function call }
printf("The greater number is: %d", result);
return 0;
}
Accessing function by passing values
There are different ways in which parameter data can be passed into and
out of methods and functions. Let us assume that a function B() is called
from another function A(). In this case A is called the “caller
function” and B is called the “called function or callee function”. Also, the
arguments which A sends to B are called actual arguments and the
parameters of B are called formal arguments.
Formal Parameter : A variable and its type as they appear in the body of
the function or method.
Actual Parameter : The variable or expression corresponding to a formal
parameter that appears in the function or method call in the calling
environment
Important methods of Parameter Passing
Call By Value : The call by value method of passing arguments to a
function 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.
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
output
}
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by reference in C
The call by reference method of passing arguments to a function
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. It means the changes made to the parameter affect the passed
argument.
To pass a value by reference, argument pointers are passed to the
functions just like any other value. So accordingly you need to declare
the function parameters as pointer types
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
call by value call by reference
This method copy original value into function as a This method copy address of arguments into
arguments. function as a arguments.
Actual and formal arguments will be created in Actual and formal arguments will be created in
different memory location same memory location
Difference between call by value and call by
reference in c
No. Call by value Call by reference
1 A copy of the value is passed into the An address of value is passed into the
function function
2 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values of outside of the function also. The values of
the actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.
3 Actual and formal arguments are created Actual and formal arguments are created at
at the different memory location the same memory location
Storage Classes in C
Storage Classes are used to describe the features of a variable/function.
These features basically include the scope, visibility and life-time which
help us to trace the existence of a particular variable during the
runtime of a program.
C language uses 4 storage classes, namely:
1. auto
This is the default storage class for all the variables declared inside a
function or a block. Hence, the keyword auto is rarely used while
writing programs in C language. Auto variables can be only accessed
within the block/function they have been declared and not outside
them (which defines their scope). Of course, these can be accessed
within nested blocks within the parent block/function in which the
auto variable was declared. However, they can be accessed outside
their scope as well using the concept of pointers given here by pointing
to the very exact memory location where the variables resides. They
are assigned a garbage value by default whenever they are declared.
2. external: Extern storage class simply tells us that the variable is defined
elsewhere and not within the same block where it is used. Basically, the
value is assigned to it in a different block and this can be
overwritten/changed in a different block as well. So an extern variable is
nothing but a global variable initialized with a legal value where it is declared
in order to be used elsewhere. It can be accessed within any function/block.
Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any function/block. This
basically signifies that we are not initializing a new variable but instead we
are using/accessing the global variable only. The main purpose of using
extern variables is that they can be accessed between two different files
which are part of a large program.
3.static: This storage class is used to declare static variables which are
popularly used while writing programs in C language. Static variables
have a property of preserving their value even after they are out of
their scope! Hence, static variables preserve the value of their last use
in their scope. So we can say that they are initialized only once and
exist till the termination of the program. Thus, no new memory is
allocated because they are not re-declared. Their scope is local to the
function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the
value 0 by the compiler.
4.register: This storage class declares register variables which have the
same functionality as that of the auto variables. The only difference is
that the compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of
register variables to be much faster than that of the variables stored in
the memory during the runtime of the program. If a free register is not
available, these are then stored in the memory only. Usually few
variables which are to be accessed very frequently in a program are
declared with the register keyword which improves the running time of
the program. An important and interesting point to be noted here is
that we cannot obtain the address of a register variable using pointers.
// A C program to demonstrate different storage { int i = 0;
// classes printf("\nDemonstrating static class\n\n");
#include <stdio.h> // using a static variable 'y'
// declaring the variable which is to be made extern printf("Declaring 'y' as static inside the loop.\n"
// an initial value can also be initialized to x "But this declaration will occur only"
int x; " once as 'y' is static.\n"
void autoStorageClass() "If not, then every time the value of 'y' "
{ "will be the declared value 5"
printf("\nDemonstrating auto class\n\n"); " as in the case of variable 'p'\n");
// declaring an auto variable (simply
// writing "int a=32;" works as well) printf("\nLoop started:\n");
auto int a = 32; for (i = 1; i < 5; i++) {
// printing the auto variable 'a' // Declaring the static variable 'y'
printf("Value of the variable 'a'" static int y = 5;
" declared as auto: %d\n",a); // Declare a non-static variable 'p'
printf("--------------------------------"); int p = 10;
} // Incrementing the value of y and p by 1
void registerStorageClass() y++;
{ p++;
printf("\nDemonstrating register class\n\n"); // printing value of y at each iteration
// declaring a register variable printf("\nThe value of 'y', “ "declared as static, in %d "
register char b = 'G'; "iteration is %d\n",i, y);
// printing the register variable 'b' // printing value of p at each iteration
printf("Value of the variable 'b'" printf("The value of non-static variable 'p', "
" declared as register: %d\n",b); "in %d iteration is %d\n", i, p);
printf("--------------------------------"); }
} printf("\nLoop ended:\n");
void externStorageClass() printf("--------------------------------");
{ printf("\nDemonstrating extern class\n\n"); }
// telling the compiler that the variable int main()
// x is an extern variable and has been {
// defined elsewhere (above the main printf("A program to demonstrate"
// function) " Storage Classes in C\n\n");
extern int x; // To demonstrate auto Storage Class
// printing the extern variables 'x' autoStorageClass();
printf("Value of the variable 'x'" // To demonstrate register Storage Class
" declared as extern: %d\n",x); registerStorageClass();
// value of extern variable x modified // To demonstrate extern Storage Class
x = 2; externStorageClass();
// printing the modified values of // To demonstrate static Storage Class
// extern variables 'x' staticStorageClass();
printf("Modified value of the variable 'x'" // exiting
" declared as extern: %d\n", printf("\n\nStorage Classes demonstrated");
x); return 0;
printf("--------------------------------"); }
}
void staticStorageClass()
Output: A program to demonstrate Storage Classes in C
Demonstrating auto class
Value of the variable ‘a’ declared as auto: 32
——————————–
Demonstrating register class
Value of the variable ‘b’ declared as register: 71
——————————–
Demonstrating extern class
Value of the variable ‘x’ declared as extern: 0
Modified value of the variable ‘x’ declared as extern: 2
——————————–
Demonstrating static class
Declaring ‘y’ as static inside the loop.
But this declaration will occur only once as ‘y’ is static.
If not, then every time the value of ‘y’ will be the declared value 5 as in the case of variable ‘p’
Loop started:
The value of ‘y’, declared as static, in 1 iteration is 6
The value of non-static variable ‘p’, in 1 iteration is 11
The value of ‘y’, declared as static, in 2 iteration is 7
The value of non-static variable ‘p’, in 2 iteration is 11
The value of ‘y’, declared as static, in 3 iteration is 8
The value of non-static variable ‘p’, in 3 iteration is 11
The value of ‘y’, declared as static, in 4 iteration is 9
The value of non-static variable ‘p’, in 4 iteration is 11
Loop ended:
——————————–
Storage Classes demonstrated
Recursive function
The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive
function. Using recursive algorithm, certain problems can be solved
quite easily. A recursive function is a function defined in terms of itself
via self-calling expressions. This means that the function will continue
to call itself and repeat its behavior until some condition is satisfied to
return a value.
Program to find factorial of a given number recursively to illustrate
recursive function
#include<stdio.h> }
#include<conio.h> int fact(int n) /* Function Definition */
{
int fact(int n); /* Function Definition */ int f=1;
if(n <= 0)
void main() {
{ return(1);
int num, res; }
clrscr(); else
printf("Enter positive integer: "); {
scanf("%d",&num); f = n * fact(n-1); /* Recursive Function Call as
res = fact(num); /* Normal Function Call */ fact() calls itself */
printf("%d! = %d" ,num ,res); return(f);
getch(); }
}
Output
Enter positive integer:
5↲
5! = 120
Working of above recursive example can be illustrated using following diagrams:
Fibonacci series is a series of numbers in which each number
output
( Fibonacci number ) is the sum of the two preceding numbers. The 0
simplest is the series 1, 1, 2, 3, 5, 8, etc.
1
The following example generates the Fibonacci series for a given
number using a recursive function − 1
#include <stdio.h> } 2
if(i == 0) { int i; 5
return 0;
} for (i = 0; i < 10; i++) { 8
printf("%d\t\n", fibonacci(i));
if(i == 1) { } 13
return 1;
} return 0; 21
return fibonacci(i-1) + fibonacci(i-2); }
34
Structure and Union
What is a structure?
A structure is a user defined data type in C.
Structure helps to construct a complex data
type which is more meaningful. It is
somewhat similar to an Array, but an array
holds data of similar type only. But
structure on the other hand, can store data
of any type, which is practical more useful.
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;
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};
struct keyword is used to define a structure. struct defines a new data type
which is a collection of primary and derived data types
Each member can have different datatype, like in this case, name is an array of
char type and age is of int type etc. Student is the name of the structure and is
called as the structure tag.
Declaring Structure Variables
It is possible to declare variables of a structure, either along with structure definition
or after the structure is defined. Structure variable declaration is similar to the
declaration of any normal variable of any other datatype. Structure variables can be
declared in following two ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct A {
int a;
int* b;
char c;
char* d;
};
int main()
{
struct A a1;
printf("Size of struct A: %lu\n", sizeof(struct A));
printf("Size of object a1: %lu\n", sizeof(a1));
return 0;
}
Array of Structure
We can also declare an array of structure variables. in which each
element of the array will represent a structure variable. Example :
struct employee emp[5];
The below program defines an array emp of size 5. Each element of the
array emp is of type Employee.
#include<stdio.h> printf("\nEnter Salary:\t");
scanf("%d", &emp[i].sal);
struct Employee }
{ printf("\nDisplaying Employee record:\n");
char ename[10]; for(i = 0; i < 3; i++)
int sal; {
}; printf("\nEmployee name is %s", emp[i].ename);
printf("\nSlary is %d", emp[i].sal);
struct Employee emp[5]; }
int i, j; }
void ask() void main()
{ {
for(i = 0; i < 3; i++) ask();
{ }
printf("\nEnter %dst Employee record:\n", i+1);
printf("\nEmployee name:\t");
scanf("%s", emp[i].ename);
#include <stdio.h> /* book 2 specification */
#include <string.h> strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
struct Books { strcpy( Book2.subject, "Telecom Billing Tutorial");
char title[50]; Book2.book_id = 6495700;
char author[50];
char subject[100]; /* print Book1 info */
int book_id; printf( "Book 1 title : %s\n", Book1.title);
}; printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
int main( ) { printf( "Book 1 book_id : %d\n", Book1.book_id);
struct Books Book1; /* Declare Book1 of type Book */ /* print Book2 info */
struct Books Book2; /* Declare Book2 of type Book */ printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
/* book 1 specification */ printf( "Book 2 subject : %s\n", Book2.subject);
strcpy( Book1.title, "C Programming"); printf( "Book 2 book_id : %d\n", Book2.book_id);
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial"); return 0;
Book1.book_id = 6495407; }
output
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Union in C
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 Data {
int i;
float f;
char str[20];
} data;
Advantages of union
Here, are pros/benefits for using union:
1. It occupies less memory compared to structure.
2. When you use union, only the last variable can be directly accessed.
3. Union is used when you have to use the same memory location for
two or more data members.
4. It enables you to hold data of only one data member.
5. Its allocated space is equal to maximum size of the data member.
Structure Union
You can use a struct keyword to define a structure. You can use a union keyword to define a union.
Every member within structure is assigned a unique In union, a memory location is shared by all the data
memory location. members.
Changing the value of one data member will not Changing the value of one data member will change
affect other data members in structure. the value of other data members in union.
It enables you to initialize only the first member of
It enables you to initialize several members at once.
union.
The total size of the structure is the sum of the size of The total size of the union is the size of the largest
every data member. data member.
It is mainly used for storing one of the many data
It is mainly used for storing various data types.
types that are available.
It occupies space for each and every member written It occupies space for a member having the highest
in inner parameters. size written in inner parameters.
You can retrieve any member at a time. You can access one member at a time in the union.
union Data {
int i;
float f;
char str[20];
};
void main( ) {
clrscr();
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
getch();
}
Accessing Union Members
To access any member of a union, we use the member access operator
(.). The member access operator is coded as a period between the
union variable name and the union member that we wish to access.
You would use the keyword union to define variables of union type.
The following example shows how to use unions in a program −
#include <stdio.h> printf( "data.i : %d\n", data.i);
#include <conio.h> printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
union Data {
int i; return 0;
float f; }
char str[20]; Ouptut
}; data.i : 10
data.f : 220.500000
void main( ) { data.str : C Programming
union Data data; • Here, we can see that the values of i and f members of
union got corrupted because the final value assigned to
clrscr (); the variable has occupied the memory location and this
is the reason that the value of str member is getting
printed very well.
data.i = 10;
• Now let's look into the same example once again
data.f = 220.5; where we will use one variable at a time which is the
main purpose of having unions −
strcpy( data.str, "C Programming");
include <stdio.h> data.f = 220.5;
#include <string.h> printf( "data.f : %f\n", data.f);
Array refers to a collection consisting of elements of homogeneous Structure refers to a collection consisting of elements of
data type. heterogeneous data type.
Array uses subscripts or “[ ]” (square bracket) for element access Structure uses “.” (Dot operator) for element access
Array is pointer as it points to the first element of the collection. Structure is not a pointer
Array size is fixed and is basically the number of elements multiplied Structure size is not fixed as each element of Structure can be of
by the size of an element. different type and size.
Array declaration is done simply using [] and not any keyword. Structure declaration is done with the help of “struct” keyword.
Array traversal and searching is easy and fast. Structure traversal and searching is complex and slow.
Array elements are accessed by their index number using subscripts. Structure elements are accessed by their names using dot operator.
Pointers in C
The pointer in C language is a variable which stores the address of another
variable. This variable can be of type int, char, array, function, or any other
pointer. The size of the pointer depends on the architecture. However, in 32-
bit architecture the size of a pointer is 2 byte.
Consider the following example to define a pointer which stores the address
of an integer.
int n = 10;
int* p = &n;
// Variable p of type pointer is pointing to the address of the variable n of
the type integer.
Pointer declaration in C
The pointer in c language can be declared using * (asterisk symbol).
The general syntax of pointer declaration is,
datatype *pointer_name;
Note: The data type of the pointer and
the variable to which the pointer variable is
pointing must be the same.
Examples:
• int *a;//pointer to int
• char *c;//pointer to char
Advantages of Using Pointers
• Less time in program execution
• Working on the original variable
• With the help of pointers, we can create data structures (linked-list,
stack, queue).
• Returning more than one values from functions
• Searching and sorting large data very easily
• Dynamically memory allocation
Disadvantages of Using Pointers
• Sometimes by creating pointers, such errors come in the program,
which is very difficult to diagnose.
• Sometimes pointer leaks in memory are also created.
• If extra memory is not found then a program crash can also occur.
NULL pointer in C
The pointer variable which is initialized with the null value is called the Null Pointer. Null Pointer
doesn’t point to any memory location until we are not assigning the address. The size of the Null
pointer also is 2 bytes according to DOS Compiler.
int * pInt = NULL;
Some uses of the null pointer are:
a) To initialize a pointer variable when that pointer variable isn’t assigned any valid memory address
yet.
b) To pass a null pointer to a function argument when we don’t want to pass any valid memory
address.
c) To check for null pointer before accessing any pointer variable. So that, we can perform error
handling in pointer related code e.g. dereference pointer variable only if it’s not NULL.
#include <stdio.h>
#include<conio.h>
void main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p);
getch();
}
C Pointers Operators that are used with Pointers
as you can see, the address of p is 3214864300. But after adding 3 with p variable, it is
3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only,
i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable.
Subtracting any number from a pointer will give an address. The
formula of subtracting value from the pointer variable is given below:
new_address= current_address - (number * size_of(data type))
For 32-bit int variable, it will subtract 2 * number.
For 64-bit int variable, it will subtract 4 * number.
#include<stdio.h>
#include<conio.h>
void main ()
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
getch(); Output
Address of p variable is 3214864300
} After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the previous address
value.
However, instead of subtracting a number, we can also subtract an address from another address
(pointer). This will result in a number. It will not be a simple arithmetic operation, but it will follow the
following rule.
If two pointers are of the same type,
Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointer points
Consider the following example to subtract one pointer from an another.
#include<stdio.h>
#include<conio.h>
void main ()
{
int i = 100;
int *p = &i;
int *temp;
temp = p;
p = p + 3;
printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
getch();
}
Output
Pointer Subtraction: 1030585080 - 1030585068 = 3
Pointer Comparison in C
In C language pointers can be compared if the two pointers are pointing
to the same array.
All relational operators can be used for pointer comparison, but a
pointer cannot Multiplied or Divided.
Below is a program on pointer comparison for same type of pointer:
#include <stdio.h>
#include<conio.h>
void main()
{
int *ptrA,*ptrB;
ptrA = (int *)1;
ptrB = (int *)2;
getch();
}
Below is a program on pointer comparison for different type of pointer:
#include <stdio.h>
#include<conio.h>
void main(){
{
int *ptrA;
float *ptrB;
getch();
}
Illegal arithmetic with pointers
There are various operations which can not be performed on pointers. Since,
pointer stores address hence we must ignore the operations which may lead to an
illegal address, for example, addition, and multiplication. A list of such operations
is given below.
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.
• Text Files.
A Text file contains only the text information like alphabets ,digits and
special symbols. The ASCII code of these characters are stored in these
files.It uses only 7 bits allowing 8 bit to be zero.
• Binary Files
A binary file is a file that uses all 8 bits of a byte for storing the information
.It is the form which can be interpreted and understood by the computer.
The only difference between the text file and binary file is the data contain
in text file can be recognized by the word processor while binary file data
can’t be recognized by a word processor.
EOF
EOF in any programming language is for End Of File.
So if you are trying to display the contents of file and want to stop
when the fil
The EOF function returns False until the end of the file has been
reached. It returns true when the file ends.
getc() and feof() // function for EOF in C
Types of File access in C
depending up on the method of accessing the data stored ,there are two
types of files.
• Sequential file
In this type of files data is kept in sequential order if we want to read the last
record of the file, we need to read all records before that record so it takes
more time.
• Random access file
In this type of files data can be read and modified randomly .If we want to
read the last record we can read it directly. It takes less time when compared
to sequential 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. Function Description
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
1 "r"
Opens a file for reading. The file must exist.
2 "w"
Creates an empty file for writing. If a file with the same name already exists, its
content is erased and the file is considered as a new empty file.
3 "a"
Appends to a file. Writing operations, append data at the end of the file. The file
is created if it does not exist.
4 "r+"
Opens a file to update both reading and writing. The file must exist.
5 "w+"
Creates an empty file for both reading and writing.
6 "a+"
Opens a file for reading and appending.
fclose()
• Declaration: int fclose(FILE *fp);
• fclose() function closes the file that is being pointed by file pointer
fp. In a C program, we close a file as below.
fclose (fp);
Example:
fclose(fptr);
fprintf()
The fprintf() function is used to write set of characters into file.
Declaration: int fprintf(FILE *fp, const char *format, …)
fprintf() function is used to write formatted data into a file. In a C
program, we use fprinf() as below.
fprintf (fp, “%s %d”, “var1”, var2);
Where, fp is file pointer to the data type “FILE”.
var1 – string variable
var2 – Integer variable
This is for example only. You can use any specifiers with any data type
as we use in normal printf() function.
#include<stdio.h> return 0;
#include<conio.h> }
void main() for (i = 0; i < n; i++)
{ {
int i, n=2; puts("Enter a name");
char str[50]; scanf("%s", str);
//open file sample.txt in write fprintf(fptr,"%d.%s\n", i, str);
mode
}
FILE *fptr = fopen("sample.txt",
"w"); fclose(fptr);
if (fptr == NULL)
{ getch();
printf("Could not open file"); }
fscanf()
fscanf() function is used to read formatted data from a file. In a C
program, we use fscanf() as below.
Declaration: int fscanf(FILE *fp, const char *format, …)
fscanf (fp, “%d”, &age);
Where, fp is file pointer to the data type “FILE”.
Age – Integer variable
This is for example only. You can use any specifiers with any data type
as we use in normal scanf() function.
/*c program demonstrating fscanf and format
its usage*/ NAME AGE CITY
#include<stdio.h> abc 12 hyderbad
#include<conio.h> bef 25 delhi
void main() cce 65 bangalore */
{ char buf[100];
FILE* ptr = fopen("abc.txt","r"); while (fscanf(ptr,"%*s %*s %s
if (ptr==NULL) ",buf)==1)
{ printf("%s\n", buf);
printf("no such file.");
return 0; getch();
} }
getw(fp);
#include<stdio.h> fp =fopen ("num.txt", "r");
#include<conio.h> printf ("file content is\n");
void main( ){ for (i =1; i<= 10; i++){
FILE *fp; i= getw(fp);
int i; printf ("%d",i);
fp = fopen ("num.txt", "w"); printf("\n");
for (i =1; i<= 10; i++){ }
putw (i, fp); fclose (fp);
} getch();
fclose (fp); }
fgetc()
fgetc functions is used to read a character from a file. It reads single
character at a time. In a C program, we use fgetc() function as below.
fgetc (fp);
Declaration: int fgetc(FILE *fp)
where,
fp – file pointer
fputc()
fputc functions is used to write a character into a file. In a C program,
we use fputc() function as below.
Declaration: int fputc(int char, FILE *fp)
fputc(ch, fp);
where,
ch – character value
fp – file pointer
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() { void main() {
FILE *f; FILE *f;
char s; f = fopen("new.txt", "w");
clrscr(); fputc('a',f);
f=fopen("new.txt","r"); fclose(f);
while((s=fgetc(f))!=EOF) { getch();
printf("%c",s); }
}
fclose(f);
getch();
}
** unsuccessful */
* C program to create a file and write data into file. if(fPtr == NULL)
*/ {
#include <stdio.h> /* File not created hence exit */
#include <stdlib.h> printf("Unable to create file.\n");
#define DATA_SIZE 1000 exit(EXIT_FAILURE);
int main() }
{ /* Input contents from user to store in file */
/* Variable to store user content */ printf("Enter contents to store in file : \n");
char data[DATA_SIZE]; fgets(data, DATA_SIZE, stdin);
/* File pointer to hold reference to our file */
FILE * fPtr; /* Write data to file */
/* fputs(data, fPtr);
* Open file in w (write) mode. /* Close file to save file data */
* "data/file1.txt" is complete path to create file fclose(fPtr);
*/ /* Success message */
fPtr = fopen("data/file1.txt", "w"); printf("File created and saved successfully. :) \n");
getch();
/* fopen() return NULL if last operation was }
Write a C program to read name and exit(1);
marks of n number of students from }
user and store them in a file
#include <stdio.h> for (i=0;i<n;++i) {
#include<conio.h> printf("For
student%d\nEnter name: ",i+1);
void main() { scanf("%s",name);
char name[50]; printf("Enter marks: ");
int marks,i,n; scanf("%d",&marks);
printf("Enter number of students: fprintf(fptr,"\nName: %s
"); \nMarks=%d \n",name,marks);
scanf("%d",&n); }
FILE *fptr; fclose(fptr);
fptr=(fopen("C:\\student.txt","w" getch();
));
if(fptr==NULL) { }
printf("Error!");
Write a C program to read name and exit(1);// this function is in stdlib.h
marks of n number of students from user and }
store them in a file. If the file previously exits, for (i=0;i<n;++i) {
add the information of n students.
#include <stdio.h> printf("For student%d\nEnter name: ",i+1);
#include<conio.h> scanf("%s",name);
#include<stdlib.h> printf("Enter marks: ");
void main() { scanf("%d",&marks);
char name[50]; fprintf(fptr,"\nName: %s \nMarks=%d
\n",name,marks);
int marks,i,n; }
printf("Enter number of students: "); fclose(fptr);
scanf("%d",&n); getch();
FILE *fptr; }
fptr=(fopen("C:\\student.txt","a")); C:\Users\user\Desktop
if(fptr==NULL) {
printf("Error!");
C program to rename a file printf("File renamed
#include <stdio.h> successfully");
#include<conio.h> } else {
int main () { printf("Error: unable to rename
the file");
int ret;
}
char oldname[] = "file.txt";
char newname[] = "newfile.txt";
getch();
}
ret = rename(oldname, newname);
if(ret == 0) {