Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

C (Dynamic Memory Allocation and File Handling)

The document discusses dynamic memory allocation and file handling in C. It covers functions like malloc(), calloc(), free() and realloc() for memory allocation and de-allocation. It also discusses functions like fopen(), fclose(), getc() for file opening, closing and reading file contents.

Uploaded by

Vidhi Gaba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

C (Dynamic Memory Allocation and File Handling)

The document discusses dynamic memory allocation and file handling in C. It covers functions like malloc(), calloc(), free() and realloc() for memory allocation and de-allocation. It also discusses functions like fopen(), fclose(), getc() for file opening, closing and reading file contents.

Uploaded by

Vidhi Gaba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Manav Rachna College of Engg.

Dynamic memory allocation


&
File handling in C
Memory Allocation in C
There are two type of memory allocation in C

Manav Rachna College of Engg.


Compile Time or Static allocation
Run-time or Dynamic allocation (using pointers)

In the compile time memory allocation the required


amount of memory is allocated to the program
element at the start of the program e.g. variable
name, function name, program name etc
Dynamic Memory Allocation
Dynamic memory allocation gives flexibility for programmer

Manav Rachna College of Engg.


and it also makes efficient use of memory, by allocating the
required amount of memory whenever needed

C provides the following dynamic allocation and de-allocation


function
malloc()
calloc()
free()
realloc()
Malloc()
The malloc() function allocates a block of memory in bytes.

Manav Rachna College of Engg.


The user should explicit give the block size it requires for
the use. The malloc() function is like a request to the RAM
of the system to allocate memory, if the request is granted,
if the request is granted it returns a pointer to the first block
of that memory. However if it fails to allocate the required
amount of memory, it returns a null

By default malloc() returns the pointer of type void, which means we can
assign it any type of pointer
The syntax of this function is as follows:

Manav Rachna College of Engg.


sieve= (char *)malloc(n*sizeof(char));

This is a CAST
(remember them) we want sizeof(char) returns how
that forces the variable n chars much memory a char
to the right type (not takes
needed)
e.g.
#include<stdio.h> Output

Manav Rachna College of Engg.


#include<alloc.h> Enter a value 18
#include<conio.h>
The value=19
void main()
{
int *p;
clrscr();
p=(int *)malloc(sizeof(int));
printf("\n Enter a value");
scanf("%d",p);
*p=*p+1;
printf("\nThe value=%d",*p);
getch();
}
Calloc()
The function works exactly similar to malloc()

Manav Rachna College of Engg.


function except for the fact that it needs two
arguments as against one argument required by
malloc()

int *ip;
ip = (int *) calloc(100, sizeof(int));
It will assign 100 integer elements that are initially
zero
Another minor difference between malloc() and calloc() is that the memory
allocated by the malloc() contains garbage values while the memory
allocated by calloc() functions contains all zeros
free()
The free() function is used to de-allocate the

Manav Rachna College of Engg.


previously allocated memory using malloc() or
calloc() functions.

The syntax of this function is:


free(ptr_var);

Where ptr_val is the pointer in which the address


of the allocated memory block is assigned.
Realloc()
The function is used to resize of memory block, which is

Manav Rachna College of Engg.


already allocated. It found uses in two situation
1. If the allocated memory block is insufficient for the current
application

2.If the allocated memory is much more that what is required by the
current application. In other words, it provides even more precise
and efficient utilization of memory

The syntax of this function is as follows


ptr_var=realloc(ptr_var,new_size);
Where ptr_var is the pointer holding the starting address of already
allocated memory block. new_size is the size in bytes you want the
system to allocate now.
Manav Rachna College of Engg.
FILE HANDLING
File handling in C
• The FILE structure contains information about the file

Manav Rachna College of Engg.


being used, eg. current size, its location in memory.
• We use FILE * to represent a pointer to a file.
• Here fptr is a pointer variable, that contains address of
structure FILE, defined in header file stdio.h.
• fopen is used to open a file. It returns the special
value NULL to indicate that it couldn't open the file.
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
fprintf (stderr, “ERROR”);
/* DO SOMETHING */
}
Modes for opening files
• The second argument of fopen is the mode

Manav Rachna College of Engg.


in which we open the file. There are three
basic modes:
• "r" opens a file for reading
• "w" opens a file for writing - and writes over
all previous contents (deletes the file so be
careful!)
• "a" opens a file for appending - writing on
the end of the file
Closing a file
• We can close a file simply using fclose

Manav Rachna College of Engg.


and the file pointer. Here's a complete
"hello files".
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen (filename,"w");
if (fptr == NULL) {
printf ("Cannot open file to write!\n");
exit(-1);
}
fprintf (fptr,"Hello World of filing!\n");
fclose (fptr);
• We use the file pointer to close the file -

Manav Rachna College of Engg.


not the name of the file

FILE *fptr;
fptr= fopen ("myfile.dat","r");
/* Read from file */
fclose ("myfile.dat");
/* Ooops - that's wrong */
File opening modes

"r" 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.

Manav Rachna College of Engg.


If the file cannot be opened fopen( ) returns NULL.
Operations possible – reading from the file.

"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
file.
Operations possible – writing to the file.

"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. If
the file doesn’t exist, a new file is created. Returns NULL, if unable to
open file.
Operations possible - adding new contents at the end of file.
File opening modes
"r+" Searches file. If is opened successfully fopen( ) loads it into
memory and sets up a pointer which points to the first character in it.
Returns NULL, if unable to open the file.
Operations possible - reading existing contents, writing new contents,

Manav Rachna College of Engg.


modifying existing contents of the file.

"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
file.
Operations possible - writing new contents, reading them back and
modifying existing contents of the file.

"a+" 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 doesn’t exist, a new file is created. Returns NULL, if unable to
open file.
Operations possible - reading existing contents, appending new contents
to end of file. Cannot modify existing contents.
Reading file contents using getc()
//Display contents of a file on screen
# include "stdio.h"
main( )

Manav Rachna College of Engg.


{
getc() reads the character from
FILE *fp ; current pointer position,
char ch ; advances the pointer position to
fp = fopen ( "PR1.C", "r" ) ; next character, and also returns
while ( 1 ) the read character.
{
ch = getc ( fp ) ;
if ( ch == EOF ) EOF – End of file is signified by
break ; a special character with ASCII
printf ( "%c", ch ) ; value 26
}
fclose ( fp ) ;
}
/* Count chars, spaces, tabs and newlines in a file */
# include <stdio.h>
main( )
{FILE *fp ;
char ch ;
int nol = 0, not = 0, nob = 0, noc = 0 ;
fp = fopen ( "PR1.C", "r" ) ;

Manav Rachna College of Engg.


while ( 1 )
{ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
noc++ ;
if ( ch == ' ' )
nob++ ;
if ( ch == '\n' )
nol++ ;
if ( ch == '\t' )
not++ ;
}
fclose ( fp ) ;
printf ( "\nNumber of characters = %d", noc ) ; printf ( "\nNumber of blanks = %d", nob ) ;
printf ( "\nNumber of tabs = %d", not ) ; printf ( "\nNumber of lines = %d", nol ) ;
}
/*COPY DATA FROM ONE FILE TO ANOTHER FILE */
#include<stdio.h>
main(){
FILE *p,*q;
char file1[20],file2[20];
char ch;
printf("\nEnter the source file name to be copied:");

Manav Rachna College of Engg.


gets(file1);
p=fopen(file1,"r");
if(p==NULL){
printf("cannot open %s",file1);
exit(0);
}
printf("\nEnter the destination file name:");
gets(file2);
q=fopen(file2,"w");
if(q==NULL){
printf("cannot open %s",file2);
exit(0);
}
while((ch=getc(p))!=EOF) putc() writes the
putc(ch,q); character on to the file at
printf("\nCOMPLETED"); the position of the file
fclose(p); pointer .
fclose(q);
}
Reading strings from a file using fgets
• fgets is a better way to read from a file
• We can read into a string using fgets

Manav Rachna College of Engg.


FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}
fgets takes 3 arguments, address where the string is stored, a
maximum number of characters to read and a file pointer.
It returns NULL if there is an error (such as EOF)
String (line) I/O in Files

/* Reads strings from the file and displays them on


screen */

Manav Rachna College of Engg.


#include "stdio.h"
main( )
{
FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "r" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
while ( fgets ( s, 79, fp ) != NULL )
printf ( "%s" , s ) ;
fclose ( fp ) ;
}
String (line) I/O in Files
/* Receives strings from keyboard and writes them to file */
#include "stdio.h"
main( )
{

Manav Rachna College of Engg.


FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "w" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 )
{
fputs ( s, fp ) ; fputs() writes the
fputs ( "\n", fp ) ; contents of the string
}
fclose ( fp ) ; at the position of file
} pointer.
Writing to a file using fprintf &
reading from a file using fscanf
• fprintf works just like printf except that its

Manav Rachna College of Engg.


first argument is a FILE pointer.

FILE *fptr;
fptr= fopen ("file.dat","w");
/* Check it's open */
fprintf (fptr,"Hello World!\n");

• fscanf() reads the data from file, similar to


scanf(), except that a pointer to FILE is its
first argument.
Record I/O in Files
/* Writes records to a file using structure */

#include "stdio.h" while ( another == 'Y' )


main( ) {

Manav Rachna College of Engg.


{ printf ( "\nEnter name, age and basic
FILE *fp ; salary: " ) ;
char another = 'Y' ; scanf ( "%s %d %f", e.name, &e.age,
struct emp &e.bs ) ;
{ fprintf ( fp, "%s %d %f\n", e.name,
char name[40] ; e.age, e.bs ) ;
int age ; printf ( "Add another record (Y/N) " ) ;
float bs ; fflush ( stdin ) ;
}; another = getche( ) ;
struct emp e ; }
fp = fopen ( "EMPLOYEE.DAT", "w" ); fclose ( fp ) ;
if ( fp == NULL ) }
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
Record I/O in Files
/* Read records from a file using structure */

#include "stdio.h"
main( ) if ( fp == NULL )
{

Manav Rachna College of Engg.


{
FILE *fp ; puts ( "Cannot open file" ) ;
struct emp exit( ) ;
{ }
char name[40] ; while ( fscanf ( fp, "%s %d %f",
int age ; e.name, &e.age, &e.bs ) != EOF )
float bs ; printf ( "\n%s %d %f", e.name, e.age,
}; e.bs ) ;
struct emp e ; fclose ( fp ) ;
fp = fopen ( "EMPLOYEE.DAT", "r" ) ; }
Text versus Binary Mode
Text versus Binary Mode: Newlines
• In text mode, a newline character is converted into the carriage
return-linefeed combination before being written to the disk. Likewise,

Manav Rachna College of Engg.


the carriage return-linefeed combination on the disk is converted
back into a newline when the file is read by a C program.
• However, if a file is opened in binary mode, as opposed to text
mode, these conversions will not take place.

Text versus Binary Mode: End of File


• In text mode, a special character, whose ASCII value is 26, is
inserted after the last character in the file to mark the end of file. If
this character is detected at any point in the file, the read function
would return the EOF signal to the program.
• As against this, there is no such special character present in the
binary mode files to mark the end of file. The binary mode files keep
track of the end of file from the number of characters present in the
directory entry of the file.
Text versus Binary Mode: Storage of Numbers
• In text mode, the only function that is available for storing
numbers in a disk file is the fprintf( ) function. Text and

Manav Rachna College of Engg.


characters are stored one character per byte, as we would
expect. Numbers are stored as strings of characters. Thus, 1234,
even though it occupies two bytes in memory, when transferred to
the disk using fprintf( ), would occupy four bytes, one byte per
character.

• The solution is to open the file in binary mode and use


functions (fread( ) and fwrite( )) which store the numbers in binary
format. It means each number would occupy same number of
bytes on disk as it occupies in memory.
Reading records using fread() & writing records using fwrite()

fwrite() writes records to a file. It has four arguments:


-first argument is the address of the structure to be written to disk.
-second argument is the size of the structure in bytes.
-third argument is the number of such structures that are to be written

Manav Rachna College of Engg.


at a time.
-fourth argument is the pointer to the file we want to write to.
Eg. fwrite ( &e, sizeof ( e ), 1, fp ) ;
fwrite() writes the record where the file pointer is currently placed.

fread() causes the data read from the file to be placed in structure
variable. Format is same as that of fwrite().

fwrite() reads the record where the file pointer is currently placed.

fread() returns the number of records read. This corresponds to the


the value of third argument or a lesser value. It returns a 0 when end
of file has been reached.
Writing records in binary mode
/* Receives records from keyboard and writes them to a file in binary mode */
#include "stdio.h"
main( )
while ( another == 'Y' )
{

Manav Rachna College of Engg.


{
FILE *fp ;
printf ( "\nEnter name, age and basic
char another = 'Y' ;
salary: " ) ;
struct emp
scanf ( "%s %d %f", e.name, &e.age,
{
&e.bs ) ;
char name[40] ;
fwrite ( &e, sizeof ( e ), 1, fp ) ;
int age ;
printf ( "Add another record (Y/N) " ) ;
float bs ;
fflush ( stdin ) ;
};
another = getche( ) ;
struct emp e ;
}
fp = fopen ( "EMP.DAT", "wb" ) ;
fclose ( fp ) ;
if ( fp == NULL )
}
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
Reading records in binary mode
/* Reads records from binary file and displays them on VDU */
#include "stdio.h"
main( )
{

Manav Rachna College of Engg.


FILE *fp ;
struct emp
{
char name[40] ;
int age ;
float bs ;
};
struct emp e ;
fp = fopen ( "EMP.DAT", "rb" ) ;
if ( fp == NULL )
{
puts ( "Cannot open file" ) ;
exit( ) ;
}
while ( fread ( &e, sizeof ( e ), 1, fp ) == 1 )
printf ( "\n%s %d %f", e.name, e.age, e.bs ) ;
fclose ( fp ) ;
}
Case : Employee Database Management

There is a provision to Add, Modify, List and Delete records, the operations that
are imperative in any database management.

Manav Rachna College of Engg.


Following comments would help you in understanding the program easily:
− Addition of records must always take place at the end of existing records in the
file, much in the same way you would add new records in a register manually.

− Listing records means displaying the existing records on the screen. Naturally,
records should be listed from first record to last record.

− While modifying records, first we must ask the user which record he intends to
modify. Instead of asking the record number to be modified, it would be more
meaningful to ask for the name of the employee whose record is to be modified. On
modifying the record, the existing record gets overwritten by the new record.

− In deleting records, except for the record to be deleted, rest of the records must
first be written to a temporary file, then the original file must be deleted, and the
temporary file must be renamed back to original.
Some points to remember:

• On opening a file a pointer is set up which points to the first record in the
file.

Manav Rachna College of Engg.


• On using the functions fread( ) or fwrite( ), the pointer moves to the
beginning of the next record.

• On closing a file the pointer is deactivated.

• fread( ) always reads that record where the pointer is currently placed.
Similarly, fwrite( ) always writes the record where the pointer is currently
placed.

• The rewind( ) function places the pointer to the beginning of the file,
irrespective of where it is present right now.
• The fseek( ) function lets us move the pointer from one record to another.

• To move the pointer to the previous record from its current position, we use the
function,
fseek ( fp, -recsize, SEEK_CUR ) ;

Manav Rachna College of Engg.


Here, -recsize moves the pointer back by recsize bytes from the current
position. SEEK_CUR is a macro defined in “stdio.h”.

• The following fseek( ) would place the pointer beyond the last record in the file.
fseek ( fp, 0, SEEK_END ) ;

•-recsize or 0 are just the offsets that tell the compiler by how many bytes should
the pointer be moved from a particular position.

•The third argument in fseek()could be SEEK_END, SEEK_CUR or SEEK_SET.


All these act as a reference from which the pointer should be offset.
SEEK_END means move the pointer from the end of the file,
SEEK_CUR means move the pointer with reference to its current position
and
SEEK_SET means move the pointer with reference to the beginning of
the file.
/* A menu-driven program for elementary database management */
#include "stdio.h"
main( )
{
FILE *fp, *ft ; recsize = sizeof ( e ) ;
char another, choice ; while ( 1 )
struct emp {
clrscr( ) ;

Manav Rachna College of Engg.


{
char name[40] ; gotoxy ( 30, 10 ) ;
int age ; printf ( "1. Add Records" ) ;
float bs ; gotoxy ( 30, 12 ) ;
}; printf ( "2. List Records" ) ;
struct emp e ; gotoxy ( 30, 14 ) ;
char empname[40] ; printf ( "3. Modify Records" ) ;
long int recsize ; gotoxy ( 30, 16 ) ;
fp = fopen ( "EMP.DAT", "rb+" ) ; printf ( "4. Delete Records" ) ;
if ( fp == NULL ) gotoxy ( 30, 18 ) ;
{ printf ( "0. Exit" ) ;
fp = fopen ( "EMP.DAT", "wb+" ) ; gotoxy ( 30, 20 ) ;
if ( fp == NULL ) printf ( "Your choice" ) ;
{ fflush ( stdin ) ;
puts ( "Cannot open file" ) ; choice = getche( ) ;
exit( ) ;
}
}
case '3' :
switch ( choice ) another = 'Y' ;
{ while ( another == 'Y' )
case '1' : {
fseek ( fp, 0 , SEEK_END ) ; printf ( "\nEnter name of employee to
another = 'Y' ; modify " ) ;
while ( another == 'Y' ) scanf ( "%s", empname ) ;

Manav Rachna College of Engg.


{ rewind ( fp ) ;
printf ( "\nEnter name, age and basic sal. while ( fread ( &e, recsize, 1, fp ) == 1 )
"); {
scanf ( "%s %d %f", e.name, &e.age, if ( strcmp ( e.name, empname ) == 0 )
&e.bs ) ; {
fwrite ( &e, recsize, 1, fp ) ; printf ( "\nEnter new name, age & bs" ) ;
printf ( "\nAdd another Record (Y/N) " ) ; scanf ( "%s %d %f", e.name, &e.age,
fflush ( stdin ) ; &e.bs ) ;
another = getche( ) ; fseek ( fp, - recsize, SEEK_CUR ) ;
} fwrite ( &e, recsize, 1, fp ) ;
break ; break ;
case '2' : }
rewind ( fp ) ; }
while ( fread ( &e, recsize, 1, fp ) == 1 ) printf ( "\nModify another Record (Y/N) " ) ;
printf ( "\n%s %d %f", e.name, e.age, e.bs ) fflush ( stdin ) ;
; another = getche( ) ;
break ; }
break ;
case '4' : case '0' :
another = 'Y' ; fclose ( fp ) ;
while ( another == 'Y' ) exit( ) ;
{ }
printf ( "\nEnter name of employee to delete " ) ; }
scanf ( "%s", empname ) ; }

Manav Rachna College of Engg.


ft = fopen ( "TEMP.DAT", "wb" ) ;
rewind ( fp ) ;
while ( fread ( &e, recsize, 1, fp ) == 1 )
{
if ( strcmp ( e.name, empname ) != 0 )
fwrite ( &e, recsize, 1, ft ) ;
}
fclose ( fp ) ;
fclose ( ft ) ;
remove ( "EMP.DAT" ) ;
rename ( "TEMP.DAT", "EMP.DAT" ) ;
fp = fopen ( "EMP.DAT", "rb+" ) ;
printf ( "Delete another Record (Y/N) " ) ;
fflush ( stdin ) ;
another = getche( ) ;
}
break ;

You might also like