unit 3
unit 3
Programming in C
POINTERS
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
.
POINTERS
.
POINTERS
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
.
POINTERS
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
getch();
}
.
POINTERS
#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;
printf ( "\n Address of var is: %x", &var);
printf ( "\n Address of var is: %x", p);
printf ( "\n Address of pointer p is: %x", &p);
/* Note I have used %u for p's value as it should be an address*/
printf( "\n Value of pointer p is: %x", p);
printf ( "\n Value of var is: %d", var);
printf ( "\n Value of var is: %d", *p);
printf ( "\n Value of var is: %d", *( &var));
} .
POINTERS
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to nothing.
• Two pointers can be subtracted to know how many elements are available between these two pointers.
• But, Pointer addition, multiplication, division are not allowed.
• The size of any pointer is 2 byte (for 16 bit compiler)
.
POINTERS
#include <stdio.h>
int main()
{
void *ptr = NULL; //void pointer
int *p = NULL;// integer pointer
char *cp = NULL;//character pointer
float *fp = NULL;//float pointer
//size of void pointer
printf("size of void pointer = %d\n\n",sizeof(ptr));
//size of integer pointer
printf("size of integer pointer = %d\n\n",sizeof(p));
//size of character pointer
printf("size of character pointer = %d\n\n",sizeof(cp));
//size of float pointer
printf("size of float pointer = %d\n\n",sizeof(fp));
return 0;
} .
Pointers to Pointers
Pointers can point to other pointers /pointer refers to the address of another pointer.
pointer can point to the address of another pointer which points to the address of a value.
.
Pointers to Pointers
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;//pointer to int
int **p2;//pointer to pointer
clrscr();
p=&number;//stores the address of number variable
p2=&p;
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p)
printf("Value of *p variable is %d \n",*p);
printf("Address of p2 variable is %x \n",p2);
printf("Value of **p2 variable is %d \n",**p);
getch();
}
.
Pointer Arithmetic
There are four arithmetic operators that can be used on
pointers:
o Increment(++)
o Decrement(--)
o Addition(+)
o Subtraction(-)
Increment pointer:
1. Incrementing Pointer is generally used in array
because we have contiguous memory in
array and we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type
of the Pointer variable.
The formula of incrementing pointer is given below:
new_address= current_address + i * size_of(data type)
Three rules should be used to increment pointer
.
Pointer Arithmetic
Increment pointer
#include <stdio.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+1;
printf("After increment: Address of p variable is %u \n",p);
}
.
Pointer Arithmetic
Decrement pointer
formula of decrementing pointer
new_address= current_address - i * size_of(data type)
Example:
#include <stdio.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-1;
printf("After decrement: Address of p variable is %u \n",p);
}
.
Pointer Arithmetic
Addition(+)
formula of adding value to pointer
new_address= current_address + (number * size_of(data
type))
Example:
#include <stdio.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; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
.}
Pointer Arithmetic
Subtraction (-)
The formula
of subtracting value from pointer variable.
new_address= current_address - (number * size_of(data type))
Example:
#include <stdio.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);
}
.
Arrays and Pointers
Suppose we declare an array arr, Here variable arr will give the base
int arr[5]={ 1, 2, 3, 4, 5 }; address, which is a constant pointer
Assuming that the base address of arr is 1000 and each integer pointing to the element, arr[0].
requires two byte, the five Therefore arr is containing the address
element will be stored as follows of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
.
Arrays and Pointers
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
Now we can access every element of array arr using p++ to move from one element to
another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
.
Arrays and Pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0; Output
printf("Enter 6 numbers:\n"); Enter 6 numbers:
for(i = 0; i < 6; ++i) 2
{ 3
// (classes + i) is equivalent to &classes[i] 4
scanf("%d",(classes + i)); 5
// *(classes + i) is equivalent to classes[i] 3
sum += *(classes + i); 4
} Sum = 21
printf("Sum = %d", sum);
return 0;
}
.
Arrays and Pointers
void main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
.
Array of Pointers
#include <stdio.h>
An array of pointers would be an const int MAX = 3;
array that holds memory locations. int main () {
An array of pointers is an int var[] = {10, 100, 200};
indexed set of variables in which int i, *ptr[MAX];
the variables are pointers (a for ( i = 0; i < MAX; i++) {
reference to a location in memory) ptr[i] = &var[i]; /* assign the address of integer. */
}
Syntax: for ( i = 0; i < MAX; i++) {
data_type_name * variable name printf("Value of var[%d] = %d\n", i, *ptr[i] );
Example }
int *ptr[MAX]; return 0;
}
.
Array of Pointers
#include <stdio.h>
An array of pointers would be an #include <conio.h>
array that holds memory locations. main() {
An array of pointers is an clrscr();
indexed set of variables in which int *array[3];
the variables are pointers (a int x = 10, y = 20, z = 30;
reference to a location in memory) int i;
array[0] = &x;
Syntax: array[1] = &y;
data_type_name * variable name array[2] = &z;
Example for (i=0; i< 3; i++) {
int *ptr[MAX]; printf("The value of %d= %d ,address is %u\t \n", i, *(array[i]),
array[i]);
}
getch();
.
Array of Pointers
#include <stdio.h>
An array of pointers would be an const int MAX = 4;
array that holds memory locations. int main () {
An array of pointers is an char *names[] = {
indexed set of variables in which "Zara Ali",
the variables are pointers (a "Hina Ali",
reference to a location in memory) "Nuha Ali",
"Sara Ali"
Syntax: };
data_type_name * variable name int i = 0;
Example for ( i = 0; i < MAX; i++) {
int *ptr[MAX]; printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
};
.
Function returning Pointer
int* findLarger(int *n1, int *n2) {
#include <stdio.h> // Checking which number is larger
int* findLarger(int*, int*); if (*n1 > *n2)
int main() { return n1;
int numa = 0; else
int numb = 0; return n2;
int *result; }
printf("\n\n Pointer : Show a function
returning pointer :\n");
printf("--------------------------------------------------\
n");
printf(" Input the first number : ");
scanf("%d", &numa);
printf(" Input the second number : ");
scanf("%d", &numb);
result = findLarger(&numa, &numb);
printf(" The number %d is larger. \n\n",
*result);
} .
Pointer to function
1) Unlike normal pointers, a function pointer points to code, not data. Typically a function
pointer stores the start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
3) A function’s name can also be used to get functions’ address. For example, in the below
program, we have removed address operator ‘&’ in assignment. We have also changed
function call by removing *, the program still works.
.
Pointer to function
1) Unlike normal pointers, a function pointer points to code, not data. Typically a function
pointer stores the start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
3) A function’s name can also be used to get functions’ address. For example, in the below
program, we have removed address operator ‘&’ in assignment. We have also changed
function call by removing *, the program still works.
.
Pointer to function
#include <stdio.h>
#include <stdio.h> /
void fun(int a)
// A normal function with an int parameter {
// and void return type printf("Value of a is %d\n", a);
void fun(int a) }
{
int main()
printf("Value of a is %d\n", a); {
} // fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
int main() /* The above line is equivalent of following two
{ void (*fun_ptr)(int);
void (*fun_ptr)(int) = fun; // & removed fun_ptr = &fun;
*/
.
Pointer and string
Create a character pointer to string in C
that points to the starting address of the
character array. This pointer will point to
the starting address of the string, that is
the first character of the string create a
character pointer to string in C that points
to the starting address of the character
array. This pointer will point to the starting
address of the string, that is the first
character of the string
.
Pointer and string
#include<stdio.h>
int main() {
char str[11] = "HelloWorld";
// pointer variable
char *ptr = str;
while (*ptr != '\0') {
printf("%c", *ptr);
.
ptr++;
}
return 0;
}
.
Dynamic Memory Allocation
Functions
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime.
Or
The process of allocating memory at runtime is known as dynamic memory allocation. Library
routines known as "memory management functions" are used for allocating and freeing memory
during execution of a program. These functions are defined in stdlib.h.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
.
Dynamic Memory Allocation
Functions
.
Dynamic Memory Allocation
Functions
malloc() #include <stdio.h>
malloc stands for "memory allocation". #include <stdlib.h>
The malloc() function allocates single block of requested int main()
memory at runtime. This function {
reserves a block of memory of given size and returns a int num, i, *ptr, sum = 0;
pointer of type void. This means that we printf("Enter number of elements: ");
scanf("%d", &num);
can assign it to any type of pointer using typecasting. It
ptr = (int*) malloc(num * sizeof(int)); //memory allocated
doesn't initialize memory at execution using malloc
time, so it has garbage value initially. If it fails to locate if(ptr == NULL)
enough space (memory) it returns a {
NULL pointer. printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
. }
Dynamic Memory Allocation
Functions
calloc()
calloc stands for "contiguous allocation".
Calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is
normally used for allocating memory to derived data types such as arrays and structures. The
calloc()function allocates multiple block of requested memory.It initially initialize (sets) all bytes to zero.If it
fails to locate enough space( memory) it returns a NULL pointer. The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of
memory each of same size.
.
Dynamic Memory Allocation
Functions
.
Memory Allocation Functions
#include <stdio.h>
#include <stdlib.h>
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
printf("Memory successfully allocated using calloc.\n");
The address assigned to a pointer should be of the same type as specified in the pointer declaration. For
example, if we declare the int pointer, then this int pointer cannot point to the float variable or some other
type of variable, i.e., it can point to only int type variable. To overcome this problem, we use a pointer to
void. A pointer to void means a generic pointer that can point to any data type. We can assign the address
of any data type to the void pointer, and a void pointer can be assigned to any type of the pointer without
performing any explicit typecasting.
.
GENERIC POINTER
void pointer
#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d %d ",ptr,&a);
return 0;
}
.
GENERIC POINTER
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
.
GENERIC POINTER
void pointer
#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
return 0;
}
.
Structure
.
Structure
Syntax
struct structure_name /tag name
{
data_type member1;
data_type member2;
.
.
data_type member n;
};
Note: Don't forget the semicolon }; in the ending line.
.
Structure
Syntax
struct tagname/structure_name
variable;
.
Structure
.
Structure
.
Structure
#include<stdio.h>
Accessing Structures/ Accessing #include<conio.h>
members of structure struct emp
{
There are two ways to access int id;
structure members: char name[36];
float sal;
1. By . (member or dot operator) };
2. By -> (structure pointer operator) void main()
{
struct emp e;
clrscr();
printf("Enter employee Id, Name, Salary: ");
scanf("%d",&e.id);
scanf("%s",&e.name);
scanf("%f",&e.sal);
printf("Id: %d",e.id);
printf("\nName: %s",e.name);
printf("\nSalary: %f",e.sal);
getch();
. }
Nested Structure in C
.
Nested Structure in C
.
Nested Structure in C
#include <stdio.h> e1.doj.dd=10;
#include <string.h> e1.doj.mm=11;
struct Employee e1.doj.yyyy=2014;
{
int id; printf( "employee id : %d\n", e1.id);
char name[20]; printf( "employee name : %s\n", e1.name);
struct Date printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",
{ e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
int dd; return 0;
int mm; }
int yyyy;
}doj;
}e1;
int main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string
. array
into char
Arrays of Structures
#include<stdio.h> printf("\nStudent Information List:");
#include<conio.h> for(i=0;i<5;i++){
#include<string.h> printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
struct student{ }
int rollno; getch();
char name[10]; }
};
void main(){
int i;
struct student st[5];
clrscr();
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);
}
.
Structures and Functions
A structure can be passed as a function argument just like any other variable. This raises a few
practical issues.
PASSING STRUCTURE TO FUNCTION IN C:
It can be done in below 3 ways.
1. Passing structure to a function by value
2. Passing structure to a function by address(reference)
3. No need to pass a structure – Declare structure variable as global
.
Structures and Functions
1. Passing structure to a function by value void func(struct student record)
#include <stdio.h> {
#include <string.h> printf(" Id is: %d \n", record.id);
struct student printf(" Name is: %s \n", record.name);
{ printf(" Percentage is: %f \n", record.percentage);
int id; }
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
} .
Structures and Functions
2. PASSING STRUCTURE TO FUNCTION IN C BY struct student record;
ADDRESS/REFERENCE: record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
#include <stdio.h>
func(&record);
#include <string.h> return 0;
struct student }
{ void func(struct student *record)
int id; {
char name[20]; printf(" Id is: %d \n", record->id);
float percentage; printf(" Name is: %s \n", record->name);
}; printf(" Percentage is: %f \n", record->percentage);
void func(struct student *); }
int main()
{
.
Structures and Functions
3. PASSING STRUCTURE TO FUNCTION IN C BY record.id=1;
DECLARE STRUCTURE AS GLOBAL VARABLE strcpy(record.name, "Raju");
: record.percentage = 86.5;
structure_demo();
return 0;
#include <stdio.h> }
#include <string.h> void structure_demo()
struct student {
{ printf(" Id is: %d \n", record.id);
int id; printf(" Name is: %s \n", record.name);
char name[20]; printf(" Percentage is: %f \n", record.percentage);
float percentage; }
};
struct student record; // Global declaration of
structure
void structure_demo();
int main()
{ .
Self‐referential Structures
A structure consists of at least a pointer member Syntax:
pointing to the same structure is known as a struct structname
{
self-referential structure. A self referential Datatype member1;
structure is used to create data structures like Datatype member2;
linked lists, stacks, etc. A self-referential structure . . .
is one of the data structures which refer to the Datatype member n;
};
pointer to (points) to Example:
another structure of the same type. For example, struct node
a linked list is supposed to be a self-referential {
data structure. The next node of a node is being int data1;
char data2;
pointed, which is of the same struct type. For struct node* link;
example, };
int main()
{
struct node ob;
return 0;
}
.
Unions
A union is a special data type available in C that allows
to store different data types in the same memory syntax
location. union union_name
Unions are conceptually similar to structures. The {
syntax of union is also similar to that of structure. The data_type member1;
only difference is in terms of storage. In structure each data_type member2;
member has its own storage location, whereas all .
members of union use a single shared memory .
location which is equal to the size of its largest data data_type memeberN;
member.We can access only one member of union at a };
time. We can’t access all member values at the same Example
time in union. But, structure can access all member union employee
values at the same time. This is because, Union { int id;
allocates one common storage space for all its char name[50];
members. Where as Structure allocates storage space float salary;
for all its members separately. };
.
Unions
.
Unions
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into
char array As you can see, id gets garbage value
//printing first employee information because name has large memory size. So
printf( "employee 1 id : %d\n", e1.id); only name will have actual value.
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
.
Unions
#include <stdio.h>
#include <conio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12; As you can see here, the values of a and b get
it.b = 20.2; corrupted and only variable c prints the expected
it.ch='z'; result. Because in union, the only member
clrscr(); whose value is currently stored will have the
printf("%d\n",it.a); memory.
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
.return 0;
Difference between Structure
and
Struct
Union Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, the When the variable is declared in the union, the compiler
compiler allocates memory to each variables member. allocates memory to the largest size variable member.
The size of a structure is equal or greater to the sum of The size of a union is equal to the size of its largest data
the sizes of each data member. member size.
Each variable member occupied a unique memory space. Variables members share the memory space of the
largest size variable.
Each variable member will be assessed at a time. Only one variable member will be assessed at a time.
We can initialize multiple variables of a structure at a In union, only the first data member can be initialized.
time.
.
typedef
Advantages of typedef : #include<stdio.h>
1 : Provides a meaningful way of declaring the variable. #include<conio.h>
2 : Increase the readability of the program. void main()
{
typedef int digits;
digits a,b,sum;
clrscr();
printf("Enter a and b values:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("The sum is:%d",sum);
getch();
}
.
Enumerations
Enumeration (or enum) is a user defined data type in C. It is
mainly used to assign names to integral constants, the
names make a program easy to read and maintain.An enum
is a keyword, it is an user defined data type. All properties
of integer are applied on
Enumeration data type so size of the enumerator data type
is 2 byte. It work like the Integer.
Syntax
enum tagname {value1, value2, value3,....};
• In above syntax enum is a keyword. It is a user defiend
data type.
• In above syntax tagname is our own variable. tagname is
any variable name.
• value1, value2, value3,.... are create set of enum values.
It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in
the list. If constant one value is not initialized then by default sequence will be start from zero
. and next to generated value should be previous constant value one.
Enumerations
#include<stdio.h>
#include<conio.h>
enum ABC {x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
}
.
Enumerations
#include<stdio.h>
#include<conio.h>
enum week {sun, mon, tue, wed, thu, fri,
sat};
void main()
{
enum week today;
today=tue;
printf("%d day",today+1);
getch();
}
.
FILE HANDLING
File handing 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.
.
FILE HANDLING
• Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime providing high
reusability.
• Portability: Without losing any data, files can be transferred to another in the computer system. The risk of flawed
coding is minimized with this feature.
• Efficient: A large amount of input may be required for some programs. File handling allows you to easily access a part of
a file using few instructions which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store a large amount of data without having to worry about storing everything
simultaneously in a program.
.
FILE HANDLING
Types of Files in C
1. Text Files
2. Binary Files
.
FILE HANDLING
Types of Files in C
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.
.
File opening modes in C
.
File opening modes in C
Opening Modes Description
r Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer
that points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
w Open for writing in text mode. If the file exists, its contents are overwritten. If the file doesn’t exist,
a new file is created. Returns NULL, if unable to open the file.
wb Open for writing in binary mode. If the file exists, its contents 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 only in the append mode. If the file doesn’t exist, a
new file is created. Returns NULL, if unable to open the file.
ab Open for append in binary mode. Data is added to the end of the file. If the file does not exist, it
will be created.
r+ Searches file. It is opened successfully fopen( ) loads it into memory and sets up a pointer that
points to the first character in it. Returns NULL, if unable to open the file.
.
File opening modes in C
Opening Description
Modes
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen( ) returns NULL.
w+ Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created.
Returns NULL, if unable to open the file.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents 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 reading and append mode. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open the file.
ab+ Open for both reading and appending in binary mode. If the file does not exist, it will be created.
.
File Handling
Opening a File
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;
.} return 0;
File Handling
Create a File in C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
return 0;
.}
Formatted File I/O Functions
Syntax of fprintf is
fprintf (fp, “control string”, list);
Example: fprintf(fp1, “%s %d”, name, age);
Syntax of fscanf is,
fscanf(fp, “control string”, list);
Example: fscanf(fp, “%s %d”, name, & age);
Note:
fscanf is used to read list of items from a file
fprintf is used to write a list of items to a file.
Note:
EOF – End of file (when EOF encountered the reading / writing
should be terminated)
.
Formatted File I/O Functions
fprintf
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
.}
Formatted File I/O Functions
fscanf
#include <stdio.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) ==
NULL){
printf("Error! opening file");
// Program exits if the file pointer returns
NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
.}
Unformatted File I/O Functions
fputc() function
The fputc() function is used to write a single character into file.
putc ( ):-Putting a character in to the file. It works with only character data type. One character
at a time can write into a file.
Ex: char ch =‟a‟;
putc (ch, fp);
Example:
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file1.txt", "w");//opening file
fputc('a',fp);//writing single character into file
fclose(fp);//closing file
}
file1.txt
a
.
Unformatted File I/O Functions
Example:
fgetc() function #include<stdio.h>
The fgetc() function returns/read a single character #include<conio.h>
from the file. It gets a character from the void main(){
stream. It returns EOF at the end of file. FILE *fp;
getc ( ): getting a character from the file, or reading char c;
the file information character by character at clrscr();
a time, upto the end of the file by using this fp=fopen("myfile.txt","r");
function. while((c=fgetc(fp))!=EOF){
Ex: char ch; printf("%c",c);
ch = getc (fp); }
fclose(fp);
getch();
}
myfile.txt
this is simple text message
.
Unformatted File I/O Functions
Example:
fputs() #include<stdio.h>
The fputs() function writes a line of characters into #include<conio.h>
file void main(){
FILE *fp;
clrscr();
fp=fopen("myfile2.txt","w");
fputs("hello c programming",fp);
fclose(fp);
getch();
}
myfile2.txt
hello c programming
.
Unformatted File I/O Functions
Example:
fgets() #include<stdio.h>
The fgets() function reads a line of characters from #include<conio.h>
file. void main(){
FILE *fp;
char text[300];
clrscr();
fp=fopen("myfile2.txt","r");
printf("%s",fgets(text,200,fp));
fclose(fp);
getch();
}
Output:
hello c programming
.
Unformatted File I/O Functions
The getw and putw functions:
These are integer oriented functions. These are similar to above functions and are used to read
and write integer values. These are useful when we deal with only integer data. The general
format is
putw ( ): putting or writing of an integer value to a file.
putw (integer , fp);
Ex: int x = 5;
putw(x,fp);
getw ( ): getting or reading integer value from a file.
Ex: int x;
x = getw (fp);
.
File Positioning Functions
fseek()
The fseek() function is used to set the file pointer to the specified offset. It is used to write data
into file at desired location.
syntax:
fseek(FILE * stream, long int offset, int whence)
The first parameter stream is the pointer to the file. The second parameter is the position of
the record to be found, and the third parameter specifies the location where the offset starts.
.
File Positioning Functions
fseek()
Example:
The fseek() function is used to set the file
#include <stdio.h>
pointer to the specified offset. It is used to
void main(){
write data
FILE *fp;
into file at desired location.
fp = fopen("myfile.txt","w+");
syntax:
fputs("This is javatpoint", fp);
fseek(FILE * stream, long int offset, int
fseek( fp, 7, SEEK_SET );
whence)
fputs("sonoo jaiswal", fp);
The first parameter stream is the pointer to the
fclose(fp);
file. The second parameter is the position of
}
the record to be found, and the third parameter
myfile.txt
specifies the location where the offset starts.
This is sonoo jaiswal
.
File Positioning Functions
rewind()
Example:
This function places the file pointer to the
#include <stdio.h>
beginning of the file, irrespective of where it is
void main(){
present
FILE *fp;
right now. It takes file pointer as an argument.
fp = fopen("myfile.txt","w+");
Syntax:
fputs("This is javatpoint", fp);
rewind( fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
myfile.txt
This is sonoo jaiswal
.
File Positioning Functions
rewind()
Example:
This function places the file pointer to the
#include <stdio.h>
beginning of the file, irrespective of where it is
void main(){
present
FILE *fp;
right now. It takes file pointer as an argument.
fp = fopen("myfile.txt","w+");
Syntax:
fputs("This is javatpoint", fp);
rewind( fp);
fseek( fp, 7, SEEK_SET );
fputs("sonoo jaiswal", fp);
fclose(fp);
}
myfile.txt
This is sonoo jaiswal
.
Command‐Line Arguments:
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important
for your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The arguments passed from command line are called command line arguments. These arguments
are handled by main() function.
To support command line argument, you need to change the structure of main() function
Syntax:
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.
.
Command‐Line Arguments:
Example1
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
.
Command‐Line Arguments:
Example1
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
But if you pass many arguments within double quote, all arguments will be treated as a single
argument only.
.
File Positioning Functions
#include<stdio.h>
fclose(fp);
#include<conio.h>
getch();
void main(){
}
FILE *fp;
Output:
char c;
this is a simple textthis is a simple text
clrscr();
fp=fopen("file.txt","r");
As you can see, rewind() function moves the file
while((c=fgetc(fp))!=EOF){
pointer at beginning of the file that is why "this
printf("%c",c);
is simple text" is printed 2 times. If you don't call
}
rewind() function, "this is simple text" will be
rewind(fp);//moves the file pointer at beginning
printed only once.
of the file
while((c=fgetc(fp))!=EOF){
printf("%c",c);
}
.
File Positioning Functions
ftell()
The ftell() function returns the current file
position of the specified stream. We can use
ftell() function to get the total size of a file after
moving file pointer at the end of file. We can
use SEEK_END constant to move the file
pointer at the end of file.
syntax:
n = ftell(fp);
n would give the relative offset(in bytes)
.
File Positioning Functions
#include <stdio.h>
#include <conio.h>
void main (){
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
printf("Size of file: %d bytes", length);
getch();
}
Output:
Size of file: 21 bytes
.