0% found this document useful (0 votes)
12 views14 pages

Unit5 FileHandling

Pointer variables store the addresses of other variables and can be used to access the values of those variables indirectly. The document discusses pointer variables and double pointers, and demonstrates their use through examples. It also covers the differences between call by value and call by reference, and how pointers allow call by reference in C.

Uploaded by

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

Unit5 FileHandling

Pointer variables store the addresses of other variables and can be used to access the values of those variables indirectly. The document discusses pointer variables and double pointers, and demonstrates their use through examples. It also covers the differences between call by value and call by reference, and how pointers allow call by reference in C.

Uploaded by

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

UNIT 5

Pointer:.
• Pointer variables are used to store the addresses of other variables.

• An integer pointer variable can store the address of any integer variable.
• A float pointer variable can store the address of any float variable.
• For declaration of pointer variables we use ‘*’ before pointer variable name.
o Eg. int *p; where p is integer pointer variable.

#include<stdio.h>
void main()
{
int a, *p;
a=7;
p=&a;
printf(“The value of a is %d.”, a);
printf(“\n The address of a is %u.”, p);
printf(“\n The value of a is %d.”, *p);
}
Output:
The value of a is 7.
The address of a is 65545(it could be different on execution).
The value of a is 7.

• For storing the address of pointer variable, we can use double pointer variable. For this
we use ‘**’ before variable name.
o Eg. int **q; where q is double pointer variable.

#include<stdio.h>
void main()
{
int a, *p, **q;
a=7;
p=&a;
q=&p;
printf(“The value of a is %d.”, a);
printf(“\n The address of a is %u.”, p);
printf(“\n The address of p is %u.”, q);
printf(“\n The value of a is %d.”, *p);
printf(“\n The value of a is %d.”, **q);
printf(“\n The value of p is %u.”, p);
printf(“\n The value of q is %u.”, q);
}

Output:
The value of a is 7.
The address of a is 65545.
The address of p is 65543.
The value of a is 7.
The value of a is 7.
The value of p is 65545.
The value of q is 65543.

Difference between Call by Value and Call by Reference

Functions can be invoked in two ways: Call by Value and Call by Reference. These two ways
are generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received
by function are called formal parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected in actual parameters of caller.
Call ByReference: Both the actual and formal parameters refer to same locations, so any
changes made inside the function are actually reflected in actual parameters of caller.

CALL BY VALUE CALL BY REFERENCE

While calling a function, instead of passing

While calling a function, we pass values of the values of variables, we pass address of

variables to it. Such functions are known as variables(location of variables) to the function

“Call By Values”. known as “Call By References.


CALL BY VALUE CALL BY REFERENCE

In this method, the value of each variable in

calling function is copied into In this method, the address of actual variables

corresponding dummy variables of the in the calling function are copied into the

called function. dummy variables of the called function.

With this method, the changes made to the

dummy variables in the called function With this method, using addresses we would

have no effect on the values of actual have an access to the actual variables and

variables in the calling function. hence we would be able to manipulate them.

// C program to illustrate // C program to illustrate


// call by value // Call by Reference

#include <stdio.h> #include <stdio.h>

// Function Prototype // Function Prototype


voidswapx(intx, inty); voidswapx(int*, int*);

// Main function // Main function


intmain() intmain()
{ {
inta = 10, b = 20; inta = 10, b = 20;

// Pass by Values // Pass reference


swapx(a, b); swapx(&a, &b);

printf("a=%d b=%d\n", a, b); printf("a=%d b=%d\n", a, b);

return0; return0;
} }
CALL BY VALUE CALL BY REFERENCE

// Swap functions that swaps // Function to swap two variables


// two values // by references
voidswapx(intx, inty) voidswapx(int* x, int* y)
{ {
intt; intt;

t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;

printf("x=%d y=%d\n", x, y); printf("x=%d y=%d\n", *x, *y);


} }
Output: Output:

x=20 y=10 x=20 y=10


a=10 b=20 a=20 b=10

Thus actual values of a and b remain

unchanged even after exchanging the values Thus actual values of a and b get changed

of x and y. after exchanging values of x and y.

In call by values we cannot alter the values In call by reference we can alter the values of

of actual variables through function calls. variables through function calls.

Values of variables are passes by Simple Pointer variables are necessary to define to

technique. store the address values of variables.


Note : In C, we use pointers to achieve call by reference
Library Functions for Dynamic Memory Allocation
malloc()
 void* malloc(size_t size);
 ‘malloc’ allocates a block of size bytes from the memory heap.
 ‘malloc’ returns a pointer to the newly allocated block of memory. If not enough space
exits for the new block, ‘malloc’ returns NULL.

#include<alloc.h>
#include<stdio.h>
void main()
{
char *str;
str=(char*)malloc(10);
strcpy(str, “Hello”);
printf(“%s” str);
free(str);
}
calloc:
 void* calloc(size_t n items, size_t size);
 ‘calloc’ provides access to the C memory heap, which is available for dynamic allocation
of variable-sized blocks of memory.
 ‘calloc’ returns a pointer to the newly allocated block. If not enough space exists for new
block, returns NULL.

void main()
{
char *str;
str=(char*)calloc(10, sizeof(char));
strcpy(str, “Hello”);
printf(“%s”, str);
free(str);
}

Difference b/w malloc and calloc:


1. malloc takes one argument and calloc takes two arguments.
2. malloc leaves the block of memory uninitialized, but calloc fills zero to the block.

Ex.
void main()
{
int *a, *b;
a=(int*) malloc (10*sizeof(int));
b=(int*) calloc(10, sizeof(int));
}
realloc:
 void* realloc (void *ptr, size_t size);
 realloc adjusts the size of the allocated block to size, copying the contents to a new
location if necessary.

void main()
{
char *str;
str=(char*)malloc(10);
strcpy(str, “Hello”);
str= (char*) realloc (str, 20);
free(str);
}
void pointer: void pointer is a generic pointer type. It can be point to any other data types.
Ex.
void main()
{
int x=10;
float y=4.0;
char ch=’a’;
void *ptr;
ptr=&x;
printf(“x= %d”, *((int*) ptr)); // typecasting of generic(void) pointer

ptr=&y;
printf(“\n y=%f”, *((float*) ptr));
ptr=&ch;
printf(“\n ch=%c”, *((char*) ptr));
}

NULL pointer: A NULL pointer is a special pointer value that does not point anywhere.
void main()
{
int *p;
p=NULL;
printf(“%u”, p);
}

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.

 If you have to enter a large number of data, it will take a lot of time to enter
them all.
However, if you have a file containing all the data, you can easily access the
contents of the file using a few commands in C.
 You can easily move your data from one computer to another without any
changes.

Types of Files
When dealing with files, there are two types of files you should know about:

1. Text files

2. Binary files
1. Text files

Text files are the normal .txt files. You can easily create text files using any simple
text editors such as Notepad.
When you open those files, you'll see all the contents within the file as plain text.
You can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide the least
security and takes bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.


Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold a higher amount of data, are not readable easily, and provides better
security than text files.

File Input/ Output:


File Operations:

a) Creation of a new file


b) Opening an existing file
c) Reading from a file
d) Writing to a file
e) Moving to a specific location in a file (seeking)
f) Closing a file

Working with files


When working with files, you need to declare a pointer of type file. This declaration
is needed for communication between the file and the program.

Opening a file - for creation and edit


Opening a file is performed using the fopen() function defined in
the stdio.h header file.
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode");

File Opening Modes:

i) “r”- reading from the file

This file mode searches file. If the file is opened successfully, fopen() loads it into
memory and sets up a pointer which points to the first character in it. If the file cannot
be opened, fopen() returns NULL.

ii) “w”- writing to the file

This file mode searches file. If the file exists, its contents are overwritten. If the file
doesn’t exist, a new file is created. It returns NULL, if unable to open file.

iii) “a”- adding new contents at the end of file

This file mode 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. If the file doesn’t
exist, a new file is created. It returns NULL, if unable to open file.

iv) “r+”- reading existing contents, writing new contents, modifying existing contents of
the file

This file mode searches file. If file is opened successfully, fopen() loads it into
memory and sets up a pointer which points to the first character in it. It returns
NULL, if unable to open the file.

v) “w+”- writing new contents, reading them back and modifying existing contents of
the file

This file mode searches file. If file exists, its contents are overwritten. If the file
doesn’t exist, a new file is created. It returns NULL, if unable to open file.

vi) “a+”- reading existing contents, appending new contents to the end of file, but cannot
modify existing contents.

This file mode searches file. If the file is opened successfully, fopen() loads it into
memory and sets up a pointer which points to the first character in it. If the doesn’t
exist, a new file is created. It returns NULL, if unable to open file.
File Functions:

Name of
Operation of Function
Function
fopen() Creates a new file for use
Opens a new existing file for use
fclose() Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads a integer from a file
putw() Writes an integer to the file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file

1. Write a C program for printing the contents of a file on screen.


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();

fp=fopen("sha.c","r"); // file must be in exists in the location


if(fp==NULL)
{
printf("Cannot open source file");
exit(1);
}
while(1)
{
ch=fgetc(fp);
if(ch==EOF)
{
break;
}
printf("%c", ch);
}
fclose(fp);
getch();
}

2. C program to copy the contents of one file to another.


#include<stdio.h>

void main()
{
FILE *fs, *ft;
char ch;

fs=fopen("sha.c","r");
if(fs==NULL)
{
puts("Cannot open source file.");
exit(1);
}
ft=fopen("t.c","w");
if(ft==NULL)
{
puts("Cannot open target file.");
exit(1);
}

while(1)
{
ch=fgetc(fs);
if(ch==EOF)
{
break;
}
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
}

You might also like