DS 2nd UNIT
DS 2nd UNIT
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
C Library Functions
The Standard Function Library in C is a huge library of sub-libraries, each of which contains the
code for several functions. In order to make use of these libraries, link each library in the broader
library through the use of header files. The actual definitions of these functions are stored in
separate library files, and declarations in header files. In order to use these functions, we have to
include the header file in the program. Below are some header files with descriptions:
Example:
The math.h header defines various mathematical functions and one macro. All the
<math.h> Functions
in this library take double as an argument and return double as the result.
The stdio.h header defines three variable types, several macros, and various
<stdio.h>
function for performing input and output.
User-Defined Function in C
Return Value:
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the function.
1. void hello(){
2. printf("hello c");
3. }
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output:
In C, 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.
Terminology
Formal Parameter: A variable and its type as it appears in the prototype 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.
Parameter passing techniques in C, such as pass by value and pass by reference, are fundamental for controlling data flow. If you’re looking to master these concepts
alongside their use in data structures, the C Programming Course Online with Data Structures provides in-depth lessons on function handling and parameter
management.
1. Pass By Value
This method uses in-mode semantics. Changes made to formal parameters do not get transmitted back to the caller. Any modifications to the formal parameter
variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This
method is also called call by value.
// C program to illustrate
// call by value
#include <stdio.h>
// Passing parameters
func(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
Output
In func, a = 12 b = 7
In main, x = 5 y = 7
2. Pass By Reference in C
In this method, the address of an argument is passed to the function instead of the argument itself during the function call. Due to this, any changes made in the
function will be reflected in the original arguments. We use the address operator (&) and indirection operator (*) to provide an argument to a function via
reference.
When any argument is passed by reference in the function call as a parameter, it is passed using the address of(&) operator from the main function. In the
function definition, the function takes the value of the parameter by using (*) operator. By using this, it can directly access the value of the parameter directly from
its original location. There will be no need for extra memory or copying the same data into some other fields.
Also, a pointer type must be defined for the matching parameter in the called function in C.
Syntax
}
..
// function call
functionName (&arg1, &arg2, ....);
Example of Pass by Reference
In the below program, the arguments that are passed by reference will be swapped with each other.
#include <stdio.h>
// parameters
*a = *b;
*b = temp;
// driver code
int main(void)
{ int n1 = 5;
int n2 = 10;
// arguments
swap(&n1, &n2);
Output
3. Pass by Pointers
This technique uses a pointer. In function we pass memory address (pointer) of a variable rather than passing the actual value of variable. This passing technique
allows the function to access and modify the content at that particular memory location.
Example of Pass by Pointers
C
#include <stdio.h>
int main()
{
int x = 5;
int* myptr = &x;
Output
C Function Prototype
A function prototype is also known as a function declaration which specifies the function’s name, function
parameters, and return type. The function prototype does not contain the body of the function. It is basically used to inform
the compiler about the existence of the user-defined function which can be used in the later part of the program.
Syntax
Syntax
C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.
Syntax
function_name(arg1, arg2, ... argN);
Structures in C
A structure in C is a derived or user-defined data type. We use the keyword struct to define a
custom data type that groups together the elements of different types. The difference between an
array and a structure is that an array is a homogenous collection of similar types, whereas a
structure can have elements of different types stored adjacently and identified by a name.
We are often required to work with values of different data types having certain relationships
among them. For example, a book is described by
its title (string), author (string), price (double), number of pages (integer), etc. Instead of using
four different variables, these values can be stored in a single struct variable.
Declare (Create) a Structure
You can create (declare) a structure by using the "struct" keyword followed by the structure_tag
(structure name) and declare all of the members of the structure inside the curly braces along
with their data types.
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member.
struct[structure tag]{
member definition;
member definition;
...
member definition;
}[one or more structure variables];
At the end of the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional.
Example
In the following example we are declaring a structure for Book to store the details of a Book −
structbook{
char title[50];
char author[50];
double price;
int pages;
} book1;
Here, we declared the structure variable book1 at the end of the structure
definition. However, you can do it separately in a different statement.
To access and manipulate the members of the structure, you need to declare its variable first. To
declare a structure variable, write the structure name along with the "struct" keyword followed
by the name of the structure variable. This structure variable will be used to access and
manipulate the structure members.
Example
structbook book1;
Usually, a structure is declared before the first function is defined in the program, after
the include statements. That way, the derived type can be used for declaring its variable inside
any function.
Structure Initialization
The initialization of a struct variable is done by placing the value of each element inside curly
brackets.
Example
To access the members of a structure, first, you need to declare a structure variable and then use
the dot (.) operator along with the structure variable.
Example 1
The four elements of the struct variable book1 are accessed with the dot (.) operator. Hence,
"book1.title" refers to the title element, "book1.author" is the author name, "book1.price" is the
price, "book1.pages" is the fourth element (number of pages).
Open Compiler
#include<stdio.h>
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};
intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325};
Output
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
Example 2
In the above program, we will make a small modification. Here, we will put the type
definition and the variable declaration together, like this −
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
} book1;
Note that if you a declare a struct variable in this way, then you cannot initialize it with curly
brackets. Instead, the elements need to be assigned individually.
Open Compiler
#include<stdio.h>
#include<string.h>
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
} book1;
intmain(){
strcpy(book1.title,"Learn C");
strcpy(book1.author,"Dennis Ritchie");
book1.price =675.50;
book1.pages =325;
When you execute this code, it will produce the following output −
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Copying Structures
The assignment (=) operator can be used to copy a structure directly. You can also use the
assignment operator (=) to assign the value of the member of one structure to another.
Let's have two struct book variables, book1 and book2. The variable book1 is initialized with
declaration, and we wish to assign the same values of its elements to that of book2.
Example
You can also assign book1 to book2 so that all the elements of book1 are respectively assigned
to the elements of book2. Take a look at the following program code −
Open Compiler
#include<stdio.h>
#include<string.h>
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};
intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325}, book2;
book2 = book1;
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48
You can pass a structure as a function argument in the same way as you pass any other variable
or pointer.
Example
Take a look at the following program code. It demonstrates how you can pass a structure as a
function argument −
Open Compiler
#include<stdio.h>
#include<string.h>
structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};
/* function declaration */
voidprintBook(structBooks book);
intmain(){
structBooks Book1;/* Declare Book1 of type Book */
structBooks Book2;/* Declare Book2 of type Book */
/* book 1 specification */
strcpy(Book1.title,"C Programming");
strcpy(Book1.author,"Nuha Ali");
strcpy(Book1.subject,"C Programming Tutorial");
Book1.book_id =6495407;
/* book 2 specification */
strcpy(Book2.title,"Telecom Billing");
strcpy(Book2.author,"Zara Ali");
strcpy(Book2.subject,"Telecom Billing Tutorial");
Book2.book_id =6495700;
voidprintBook(structBooks book){
When the above code is compiled and executed, it produces the following result −
Pointers to Structures
You can define pointers to structures in the same way as you define pointers to any other
variable.
structBooks*struct_pointer;
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325},
structbook*strptr;
Example
In this example, strptr is a pointer to struct book book1 variable. Hence, strrptr→title returns
the title, just like book1.title does.
Open Compiler
#include<stdio.h>
#include<string.h>
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};
intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325};
structbook*strptr;
strptr=&book1;
printf("Title: %s \n",strptr-> title);
printf("Author: %s \n",strptr-> author);
printf("Price: %lf \n",strptr-> price);
printf("Pages: %d \n",strptr-> pages);
return0;
}
Output
When you run this code, it will produce the following output −
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Note: The dot (.) operator is used to access the struct elements via the struct variable. To access
the elements via its pointer, we must use the indirection (->) operator
.
A struct variable is like a normal variable of primary type, in the sense that you can have an array
of struct, you can pass the struct variable to a function, as well as return a struct from a function.
You may have noted that you need to prefix "struct type" to the name of the variable or pointer at
the time of declaration. This can be avoided by creating a shorthand notation with the help
of typedef keyword.
Keyword typedef
We use the typedef keyword to create an alias name for data types. It is commonly used with
structures to simplify the syntax of declaring variables.
For example, let us look at the following code:
structDistance{
int feet;
float inch;
};
intmain() {
structDistanced1, d2;
}
typedefstructDistance {
int feet;
float inch;
} distance d1,d2;
intmain() {
distances d1, d2;
}
C Unions
The Union is a user-defined data type in C language that can contain elements of the different data types
just like structure. But unlike structures, all the members in the C union are stored in the same memory
location. Due to this, only one member can store data at the given instance.
Syntax of Union in C
The syntax of the union in C can be divided into three steps which are as follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’
names and data types along with the name of the union. No memory is allocated to the union in
the declaration.
unionunion_name {
datatype member1;
datatype member2;
...
};
Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning the value
to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.
Example of Union in C
// C Program to demonstrate how to use union
#include<stdio.h>
// driver code
intmain()
{
return0;
}
Output
Size of Union
The size of the union will always be equal to the size of the largest member of the array. All
the less-sized elements can store the data in the same space without any overflow.
The size of the structure is equal to or greater than the The size of the union is the size of
total size of all of its members. its largest member.
The structure can contain data in multiple members at Only one member can contain data
the same time. at the same time.
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used
to store the memory address of other variables, functions, or even other pointers. The use of
pointers allows low-level memory access, dynamic memory allocation, and many other
functionality in C.
In this article, we will discuss C pointers in detail, their types, uses, advantages, and
disadvantages with examples.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.
As the pointers in C store the memory addresses, their size is independent of the type of data
they are pointing to. This size of pointers in C only depends on the system architecture. If you’re
looking to master pointers, especially how they work with data structures, the C Programming
Course Online with Data Structures offers a comprehensive breakdown of this concept.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype *ptr;
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to
functions, structures, etc.
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer,
we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not initialized. Such
pointers are called wild pointers.
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable. We
generally use the ( &: ampersand ) addressof operator to get the memory address of a variable
and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is called pointer
definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value before
starting using it. Otherwise, it may lead to number of errors.
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address
specified in the pointer. We use the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereferencing a Pointer in C
C Pointer Example
voidgeeks()
{
intvar=10;
// Driver program
intmain()
{
geeks();
return0;
}
Output
Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter on which we are
defining their types. If we consider the type of variable stored in the memory location pointed by
the pointer, then the pointers can be classified into the following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer to its first
element. They are also known as Pointer to Arrays. We can create a pointer to an array using the
given syntax.
Syntax
char *ptr = &array_name;
Pointer to Arrays exhibits some interesting properties which we discussed later in this article.
. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can
be declared in the same way as we declare the other primitive data types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the
sense that instead of pointing to the data, they point to the code. Let’s consider a function
prototype – int func (int, char), the function pointer for this function will be
Syntax
int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer. Such
pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data value,
they point to another pointer.
Syntax
datatype ** pointer_name;
Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3,
****ptr4, ******ptr5 and so on.
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be
created by assigning a NULL value to the pointer. A pointer of any type can be assigned the
NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any type and can
be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot be dereferenced.
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of
C-pointers can cause problems in our programs and can eventually cause them to crash. If values
is updated using wild pointers, they could cause data abort or data corruption.
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be
modified once it is defined. It will always point to the same memory address.
Syntax
data_type * const pointer_name;
Size of Pointers in C
The size of the pointers in C is equal for every pointer type. The size of the pointer does not
depend on the type it is pointing to. It only depends on the operating system and CPU
architecture. The size of pointers in C is
8 bytes for a 64-bit System
4 bytes for a 32-bit System
The reason for the same size is that the pointers store the memory addresses, no matter what type
they are. As the space required to store the addresses of the different memory locations is the
same, the memory required by one pointer type will be equal to the memory required by other
pointer types.
How to find the size of pointers in C?
We can find the size of pointers using the sizeof operator as shown in the following program:
Example: C Program to find the size of different pointer types.
// C Program to find the size of different pointers types
#include<stdio.h>
// dummy structure
structstr{
};
// dummy function
voidfunc(inta,intb){};
intmain()
{
// dummy variables definitions
inta=10;
charc='G';
structstrx;
// printing sizes
printf("Size of Integer Pointer \t:\t%d bytes\n",
sizeof(ptr_int));
printf("Size of Character Pointer\t:\t%d bytes\n",
sizeof(ptr_char));
printf("Size of Structure Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
printf("Size of Function Pointer\t:\t%d bytes\n",
sizeof(ptr_func));
printf("Size of NULL Void Pointer\t:\t%d bytes",
sizeof(ptr_vn));
return0;
}
Output
C Pointer Arithmetic
The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on
a pointer. It is slightly different from the ones that we generally use for mathematical
calculations as only a limited set of operations can be performed on pointers. These operations
include:
Increment in a Pointer
Decrement in a Pointer
Addition of integer to a pointer
Subtraction of integer to a pointer
Subtracting two pointers of the same type
Comparison of pointers of the same type.
Assignment of pointers of the same type.
C
#include<stdio.h>
intmain()
{
// Declare an array
intv[3]={10,100,200};
for(inti=0;i<3;i++){
Output
Value of *ptr = 10
Value of ptr = 0x7ffcfe7a77a0
Void fun()
{
// Declare an array
intval[3]={5,10,15};
return;
}
// Driver program
intmain()
{
fun();
return0;
}
Output
Not only that, as the array elements are stored continuously, we can pointer arithmetic operations
such as increment, decrement, addition, and subtraction of integers on pointer to move between
array elements.
Example 2: Accessing Array Elements using Pointer Arithmetic
intmain()
{
// defining array
intarr[5]={1,2,3,4,5};
Output
12345
This concept is not limited to the one-dimensional array, we can refer to a multidimensional
array element as well using pointers.
To know more about pointers to an array, refer to this article – Pointer to an Array
Uses of Pointers in C
The C pointer is a very powerful tool that is widely used in C programming to perform various
useful operations. It is used to achieve the following functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
3. Return Multiple Values from Function
4. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.
Advantages of Pointers
Following are the major advantages of pointers in C:
Pointers are used for dynamic memory allocation and deallocation.
An Array or a structure can be accessed efficiently with pointers
Pointers are useful for accessing memory locations.
Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
Pointers reduce the length of the program and its execution time as well.
Disadvantages of Pointers
File handling in C is the process in which we create, open, read, write, and close operations on
a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(),
fprintf(), etc. to perform input, output, and many different C file operations in our program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
Text Files
Binary Files
1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
Each line in a text file ends with a new line character (‘\n’).
It can be read or written by any text editor.
They are generally stored with .txt file extension.
Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
The binary files can be created only from within a program and their contents can only be
read by a program.
More secure as they are not easily readable.
They are generally stored with .bin file extension.
C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
The highlighted text mentions the C function used to perform the file operations.
File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling
to perform all file operations such as read, write, close, etc. We use the FILE macro to declare
the file pointer variable. The FILE macro is defined inside <stdio.h> header file.
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.
access_mode: Specifies for what operation the file is being opened.
Return Value
If the file is opened successfully, returns a file pointer to it.
If the file is not opened, then returns NULL.
Opening
Modes Description
Searches file. If the file is opened successfully fopen( ) loads it into memory and
r sets up a pointer that points to the first character in it. If the file cannot be opened
fopen( ) returns NULL.
Open for reading in binary mode. If the file does not exist, fopen( ) returns
rb
NULL.
w Open for writing in text mode. If the file exists, its contents are overwritten. If the
Opening
Modes Description
file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.
Open for writing in binary mode. If the file exists, its contents are overwritten. If
wb
the file does not exist, it will be created.
Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer that points to the last character in it. It opens only in the append
a
mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to
open the file.
Open for append in binary mode. Data is added to the end of the file. If the file
ab
does not exist, it will be created.
Searches file. It is opened successfully fopen( ) loads it into memory and sets up a
r+ pointer that points to the first character in it. Returns NULL, if unable to open the
file.
Open for both reading and writing in binary mode. If the file does not exist,
rb+
fopen( ) returns NULL.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist
w+
a new file is created. Returns NULL, if unable to open the file.
Open for both reading and writing in binary mode. If the file exists, its contents
wb+
are overwritten. If the file does not exist, it will be created.
a+ Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer that points to the last character in it. It opens the file in both
Opening
Modes Description
reading and append mode. If the file doesn’t exist, a new file is created. Returns
NULL, if unable to open the file.
Open for both reading and appending in binary mode. If the file does not exist, it
ab+
will be created.
As given above, if you want to perform operations on a binary file, then you have to append ‘b’
at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use
“a+b”.
Example of Opening a File
C
intmain()
{
// file pointer variable to store the value returned by
// fopen
FILE*fptr;
return0;
}
Output
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such as
w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File
C
intmain()
{
// file pointer
FILE*fptr;
return0;
}
Output
fscanf() Use formatted string and variable arguments list to take input from a file.
So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description
Similar to printf(), this function use formatted string and varible arguments list to
fprintf()
print output to the file.
fputs() Prints the whole line in the file and a newline at the end.
Function Description
fwrite() This functions write the specified amount of bytes to the binary file.
Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);
intmain()
{
return0;
}
Output
intmain()
{
printf(
"Data successfully read from file GfgTest.c\n");
printf("The file is now closed.");
}
return0;
}
Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.
This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.
Syntax of fwrite()
size_tfwrite(const void *ptr, size_tsize, size_tnmemb, FILE *file_pointer);
Parameters:
ptr: pointer to the block of memory to be written.
size: size of each element to be written (in bytes).
nmemb: number of elements.
file_pointer: FILE pointer to the output file stream.
Return Value:
Number of objects written.
Example: Program to write to a Binary file using fwrite()
C
fclose(fptr);
return0;
}
Output
Return Value:
Number of objects written.
Example: Program to Read from a binary file using fread()
C
return0;
}
Output
n1: 1 n2: 5 n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21
fseek() in C
If we have multiple records inside a file and need to access a particular record that is at a
specific position, so we need to loop through all the records before it to get the record. Doing
this will waste a lot of memory and operational time. To reduce memory consumption and
operational time we can use fseek() which provides an easier way to get to the required data.
fseek() function in C seeks the cursor to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
Example of fseek()
intmain()
{
FILE*fp;
fp=fopen("test.txt","r");
return0;
}
Output
81
rewind() in C
The rewind() function is used to bring the file pointer to the beginning of the file. It can be
used in place of fseek() when you want the file pointer at the start.
Syntax of rewind()
rewind (file_pointer);
Example
intmain()
{
FILE*fptr;
fptr=fopen("file.txt","w+");
fprintf(fptr,"data structures\n");
// using rewind()
rewind(fptr);
// reading from file
charbuf[50];
fscanf(fptr,"%[^\n]s",buf);
printf("%s",buf);
return0;
}
Output:
Data structures