SlideShare una empresa de Scribd logo
1 de 32
FILE MANAGEMENT
Jigar Jobanputra
• As we know that printf and scanf are console oriented functions,
which always use the terminal like keyboard as the target place.
These functions works fine as well as small application in concern.
But in some real life problems or large problems these functions
are not suitable as it is very cumbersome and time consuming.
• To solve these problems we need flexible approach where we can
store – read - write –update the data onto disks whenever
necessary.
• Language C supports many operation where we can store the data
onto the disks using the concept called file handling or file
management.
• C supports the following operation like :
– Naming a file
– Opening a file
– Reading the data from a file
– Write a data to the file
– Closing a file
• When working with a file steps it to establish
a buffer area, where information is
temporarily stored while being transferred
between the computer’s memory and the
data file. This buffer area allows information
to be read from or written to the data file
more rapidly then would otherwise be
possible. The buffer area is established by
writing
• FILE *pt;
• Where FILE (uppercase required) is a special
data structure type that establishes the buffer
area and pt is a pointer variable that indicates
the beginning of the buffer area. The
structure type file is defined with a system
include file : typically stdio.h
Function name Operation
fopen() Creates new file / Opens a new file
fclose() Closes a file which hass been opened for use
getc() Reads a character form a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads set of data values from a file
getw() Reads integer data value from a file
putw() Writes integer data value to a file
fseek() Sets a position to a desired position in the file
ftell() Gives the current position in the file
rewind() Sets the position at the beginning of the file
• 1. fopen () :- Creates new file / Opens a new file
•
• If we want to store the data file in the secondary memory , we must the filename
, data structure and purpose.
•
• Filename always contain some extension for example srk.txt or srkins.doc , data
structure means using which library we are storing the content of the file and
purpose means for what operation we want to open the file like for reading
/writing etc..
•
• Syntax:
• FILE *pt; // declares the variable pt as a pointer to the data type FILE
• pt = fopen( “ file name”, ”mode”) ; //
•
• Here , filename is name of the file which you want to open or you want to create
if file does not exists.
• mode specifying the purpose of opening the file.
• Mode can be one of the following :
• r open the file for reading only
• w open the file for reading only
• a open the file for appending
• r+ open the existing file to the beginning both
for reading and writing
• w+ same as w but both for reading and writing
• a+ same as a but both for reading and writing
• Example:
•
• FILE *pt1,*pt2;
• pt1=fopen(“srk.txt”,”w” ); // opens a file srk.txt if it exist or else create it
• pt2=fopen(“srk.doc”,”r” ); // opens a file srk.doc if it exist or else none
•
•
• The fopen function returns a pointer to the beginning of the buffer area
associated with the file. A NULL value is returned if the file cannot be opened as
for example, when and existing file cannot be found. Finally a data file must be
closed at eh end of the program. This ensures that all outstanding information
associated with the file is flushed out from the buffers and all links to the file are
broken. It also prevents any accidental misuse of the file. In case there is a limit to
the number of files that can be kept open simultaneously, closing of unwanted file
might help open the required files. Another instance, where we have to close a file
is when we want to reopen the same file in a different mode. This can be
accomplished with the library function fclose. The syntax is simply:
• 2. fclose() :
•
• Syntax:
•
• fclose(file pointer);
•
•
•
• Example:
•
• #include <stdio.h> main()
• {
• FILE *fp;
• fp=fopen(“SRKINS.txt”,”w”);
• fclose(fp);
• }
• 3. The getc and putc Functions:
•
• The simplest file i/o functions are getc and putc. These are used to handle one character at a time.
Assume that a file is opened with mode w and file pointer fp. Then, the statement
•
• putc(c,fp);
•
• Writes the character contained in the character variable c to the file associated with FILE pointer
fp.
•
• Similarly getc is used to read character from a file that has been opened in read mode. For
example, the statement
•
• c = getc(fp);
•
•
•
• Would reads character from file whose file
pointer is fp. the file pointer moves by one
character position for every operation of getc
and putc. The getc will have been reached.
Therefore, the reading should be terminated
when EOF( End Of File ) is encountered.
•  Write a program to read data from the
keyboard, write it to a file called SRK again read
the same data from the SRK file and display on
the screen.
•  Write a program to read data from the
keyboard, write it to a file called SRK again
read the same data from the SRK file and
display on the screen.
• The getw and putw Functions:
•
• The getw and putw are integer oriented functions. These functions are
useful when we deal with the integer type data value.
•
• getw() is used to
• read integer data value from a file
• putw() is used to
• writes integer data value to a file
•
• Syntax:
• putw(integer,fp); // fp is the pointer variable and integer is the name
of the variable type int
• getw(fp);
• THE FSCANF AND FPRINTF FUNCTIONS :
•
• These functions are used to read or write in formatted from from/to the
files.
•
• Syntax of fprintf ():
• fscanf(fp, “control string”, list);
•
• Example:
• FILE *f1;
• f1=fopen(“input.txt” , “w ” );
• fprintf(f1, “%s %d %f ”, name, age, 7.5); // prints
name,age and 7.5 from the file input
•
• Syntax of fscanf ():
•
• fscanf(fp, “control string”, list);
•
• Example:
•
• FILE *f1;
• f1=fopen(“input.txt” , “w ” );
• fscanf(f1, “%s %d %f ”, name, &age,&per);// writes name,age and
percentage from the file input
• fprintf(f1, “%s %d %f ”, name, age, 7.5);
•
• fcanf returns the number of items that are successfully read. When the
end of the file is reached, it returns the value of EOF.
• 5. The fseek function:
•
• fseek function is used to move the position to a desired location
within the file. It takes the following form.
•
• Syntax:
• feek(fp, offset, position)
•
• fp is a pointer to file concerned. offset is a number of variable of
type long and position is an integer number. The offset specifies
the number of bytes(position) to be moved from the location
specified by position. The position can take one of the following
three values:
• 0 beginning of file
• 1 current position
• 2 end of file
•
• The offset may be positive, meaning move
forward and negative, meaning move backwards.
When the operation is successful, fseek returns a
zero. If we attempt to move beyond the file
boundaries and error occurs and fseek returns.
•  A file named DATA contains a series of
integer numbers. Write a program to read
these numbers and then write all “ODD”
numbers to a file called ODD and all “even”
numbers to a file called EVEN.
DYNAMIC MEMORY ALLOCATION
• The process of allocating memory at run time
is known as dynamic memory allocation.
malloc() and calloc() are library routines
known as that can be used for allocating and
freeing memory during program execution.
• There are four “Memory Management
Functions” available in C library routine for
allocating and freeing a memory during a
program execution.
• malloc() : alloates the memory to a single
element and move the pointer to the first
byte
• calloc() : alloates the memory to an array of
elements
• free() : Frees the previously allocated space
• realloc() : modifies the previously allocated
space
• 1. malloc()
•
• A block of memory may be allocated using the
function malloc(). The function reserves a
block of memory of specified size and returns
a pointer of type void. This means that we can
assign it to any type of pointer. it takes the
following form.
• ptr = ( cast_type * ) malloc( byte_size );
•
• ptr is a pointer of type cast_type. The malloc
returns a pointer of cast_type to an area of
memory of size byte_size. For example,
• X = ( int * ) malloc( 100 * sizeof (int) );
•
• On successful execution of this statement a
memory space equivalent to “100 times for
the size of int” bytes is reserved and the
address of the first byte of the memory
allocated is assigned to the pointer x of type
int. Similarly statement
• cptr = (char *) malloc(10);
•
• Allocates 10 byte of space for the cptr of type
char. We may also use malloc to allocate
space for complex data types such as
structures.
• For example,
• stptr = ( struct store* )malloc( sizeof( struct
store ) );
• Where stptr is pointer of type struct store.
The malloc allocates a block of contiguous
bytes. The allocation can fall if the space in
the heap is not sufficient to satisfy the
request. If it fails it returns a NULL.
2. Calloc()
• Calloc is memory allocation function that is
normally used for requesting memory space
at runtime for storing derived data types such
as arrays and structures. Calloc allocates
multiple block of storage, each of the same
size and then sets all bytes to zero. The
general form of calloc is ;
•
• ptr = (cast_type *) calloc(n,elem_size);
• The above statement allocates contiguous
space of n blocks. Each of size elem_size. All
bytes are initialized to zero and a pointer to
the first byte of allocated region is returned. If
there is not enough space, a NULL pointer is
returned. The following segment of program
allocates space to a structure variable.
• struct student
• {
• char name[25]; float age;
• long int id_num;
• };
• typedef struct student record;
• record *stptr;
• int class size=30;
• stptr = (record *) calloc(class_size,
sizeof(record));
3. free()
• This function is used to allocate the previously
allocated space.
• Look the following form :
•
• free(ptr);
• Ptr is the pointer to the previously allocated
memory space.
• 4. realloc() :
• Sometimes the previously allocated memory
is not sufficient and we need additional space
for more elements. realloc function is used in
such type of situations.
• Syntax:
• ptr=realloc(ptr,new size);
• This function allocates a new memory space
of size new size to the pointer variable ptr and
returns a pointer to the first byte of the
memory block.
•  Write a program to store a character string
in a block of memory space created by malloc
and then modify the same to store a larger
string.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
File handling in 'C'
File handling in 'C'File handling in 'C'
File handling in 'C'
 
File handling in C by Faixan
File handling in C by FaixanFile handling in C by Faixan
File handling in C by Faixan
 
Mesics lecture files in 'c'
Mesics lecture   files in 'c'Mesics lecture   files in 'c'
Mesics lecture files in 'c'
 
File in c
File in cFile in c
File in c
 
File handling in c
File  handling in cFile  handling in c
File handling in c
 
File handling(some slides only)
File handling(some slides only)File handling(some slides only)
File handling(some slides only)
 
File Management
File ManagementFile Management
File Management
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Module 03 File Handling in C
Module 03 File Handling in CModule 03 File Handling in C
Module 03 File Handling in C
 
File handling in c
File handling in c File handling in c
File handling in c
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
file management in c language
file management in c languagefile management in c language
file management in c language
 
File Handling in C
File Handling in C File Handling in C
File Handling in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
file
filefile
file
 
File handling
File handlingFile handling
File handling
 

Destacado (6)

Java session14
Java session14Java session14
Java session14
 
C programming
C programmingC programming
C programming
 
Ms dos
Ms dosMs dos
Ms dos
 
File Management Presentation
File Management PresentationFile Management Presentation
File Management Presentation
 
File Management
File ManagementFile Management
File Management
 
Making appointment
Making appointmentMaking appointment
Making appointment
 

Similar a File mangement

Similar a File mangement (20)

File management
File managementFile management
File management
 
637225560972186380.pdf
637225560972186380.pdf637225560972186380.pdf
637225560972186380.pdf
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 
File management
File managementFile management
File management
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Introduction to c part 4
Introduction to c  part  4Introduction to c  part  4
Introduction to c part 4
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Programming in C Session 4
Programming in C Session 4Programming in C Session 4
Programming in C Session 4
 
Unit5
Unit5Unit5
Unit5
 
File handling With Solve Programs
File handling With Solve ProgramsFile handling With Solve Programs
File handling With Solve Programs
 
File Management in C
File Management in CFile Management in C
File Management in C
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
File management
File managementFile management
File management
 
File handing in C
File handing in CFile handing in C
File handing in C
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
 
Engineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptxEngineering Computers L34-L35-File Handling.pptx
Engineering Computers L34-L35-File Handling.pptx
 
File Handling in C Programming
File Handling in C ProgrammingFile Handling in C Programming
File Handling in C Programming
 
File Handling in C.pptx
File Handling in C.pptxFile Handling in C.pptx
File Handling in C.pptx
 

Más de Jigarthacker

Más de Jigarthacker (11)

Java session13
Java session13Java session13
Java session13
 
Java session5
Java session5Java session5
Java session5
 
Java session4
Java session4Java session4
Java session4
 
Java session3
Java session3Java session3
Java session3
 
Java session2
Java session2Java session2
Java session2
 
Computer networks
Computer networksComputer networks
Computer networks
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 1(sem-iv)
Unit 1(sem-iv)Unit 1(sem-iv)
Unit 1(sem-iv)
 
Unit 2
Unit 2Unit 2
Unit 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Basic object oriented approach
Basic object oriented approachBasic object oriented approach
Basic object oriented approach
 

Último

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 

Último (20)

Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

File mangement

  • 2. • As we know that printf and scanf are console oriented functions, which always use the terminal like keyboard as the target place. These functions works fine as well as small application in concern. But in some real life problems or large problems these functions are not suitable as it is very cumbersome and time consuming. • To solve these problems we need flexible approach where we can store – read - write –update the data onto disks whenever necessary. • Language C supports many operation where we can store the data onto the disks using the concept called file handling or file management.
  • 3. • C supports the following operation like : – Naming a file – Opening a file – Reading the data from a file – Write a data to the file – Closing a file
  • 4. • When working with a file steps it to establish a buffer area, where information is temporarily stored while being transferred between the computer’s memory and the data file. This buffer area allows information to be read from or written to the data file more rapidly then would otherwise be possible. The buffer area is established by writing
  • 5. • FILE *pt; • Where FILE (uppercase required) is a special data structure type that establishes the buffer area and pt is a pointer variable that indicates the beginning of the buffer area. The structure type file is defined with a system include file : typically stdio.h
  • 6. Function name Operation fopen() Creates new file / Opens a new file fclose() Closes a file which hass been opened for use getc() Reads a character form a file putc() Writes a character to a file fprintf() Writes a set of data values to a file fscanf() Reads set of data values from a file getw() Reads integer data value from a file putw() Writes integer data value to a file fseek() Sets a position to a desired position in the file ftell() Gives the current position in the file rewind() Sets the position at the beginning of the file
  • 7. • 1. fopen () :- Creates new file / Opens a new file • • If we want to store the data file in the secondary memory , we must the filename , data structure and purpose. • • Filename always contain some extension for example srk.txt or srkins.doc , data structure means using which library we are storing the content of the file and purpose means for what operation we want to open the file like for reading /writing etc.. • • Syntax: • FILE *pt; // declares the variable pt as a pointer to the data type FILE • pt = fopen( “ file name”, ”mode”) ; // • • Here , filename is name of the file which you want to open or you want to create if file does not exists. • mode specifying the purpose of opening the file.
  • 8. • Mode can be one of the following : • r open the file for reading only • w open the file for reading only • a open the file for appending • r+ open the existing file to the beginning both for reading and writing • w+ same as w but both for reading and writing • a+ same as a but both for reading and writing
  • 9. • Example: • • FILE *pt1,*pt2; • pt1=fopen(“srk.txt”,”w” ); // opens a file srk.txt if it exist or else create it • pt2=fopen(“srk.doc”,”r” ); // opens a file srk.doc if it exist or else none • • • The fopen function returns a pointer to the beginning of the buffer area associated with the file. A NULL value is returned if the file cannot be opened as for example, when and existing file cannot be found. Finally a data file must be closed at eh end of the program. This ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental misuse of the file. In case there is a limit to the number of files that can be kept open simultaneously, closing of unwanted file might help open the required files. Another instance, where we have to close a file is when we want to reopen the same file in a different mode. This can be accomplished with the library function fclose. The syntax is simply:
  • 10. • 2. fclose() : • • Syntax: • • fclose(file pointer); • • • • Example: • • #include <stdio.h> main() • { • FILE *fp; • fp=fopen(“SRKINS.txt”,”w”); • fclose(fp); • }
  • 11. • 3. The getc and putc Functions: • • The simplest file i/o functions are getc and putc. These are used to handle one character at a time. Assume that a file is opened with mode w and file pointer fp. Then, the statement • • putc(c,fp); • • Writes the character contained in the character variable c to the file associated with FILE pointer fp. • • Similarly getc is used to read character from a file that has been opened in read mode. For example, the statement • • c = getc(fp); • • •
  • 12. • Would reads character from file whose file pointer is fp. the file pointer moves by one character position for every operation of getc and putc. The getc will have been reached. Therefore, the reading should be terminated when EOF( End Of File ) is encountered. •  Write a program to read data from the keyboard, write it to a file called SRK again read the same data from the SRK file and display on the screen.
  • 13. •  Write a program to read data from the keyboard, write it to a file called SRK again read the same data from the SRK file and display on the screen.
  • 14. • The getw and putw Functions: • • The getw and putw are integer oriented functions. These functions are useful when we deal with the integer type data value. • • getw() is used to • read integer data value from a file • putw() is used to • writes integer data value to a file • • Syntax: • putw(integer,fp); // fp is the pointer variable and integer is the name of the variable type int • getw(fp);
  • 15. • THE FSCANF AND FPRINTF FUNCTIONS : • • These functions are used to read or write in formatted from from/to the files. • • Syntax of fprintf (): • fscanf(fp, “control string”, list); • • Example: • FILE *f1; • f1=fopen(“input.txt” , “w ” ); • fprintf(f1, “%s %d %f ”, name, age, 7.5); // prints name,age and 7.5 from the file input •
  • 16. • Syntax of fscanf (): • • fscanf(fp, “control string”, list); • • Example: • • FILE *f1; • f1=fopen(“input.txt” , “w ” ); • fscanf(f1, “%s %d %f ”, name, &age,&per);// writes name,age and percentage from the file input • fprintf(f1, “%s %d %f ”, name, age, 7.5); • • fcanf returns the number of items that are successfully read. When the end of the file is reached, it returns the value of EOF.
  • 17. • 5. The fseek function: • • fseek function is used to move the position to a desired location within the file. It takes the following form. • • Syntax: • feek(fp, offset, position) • • fp is a pointer to file concerned. offset is a number of variable of type long and position is an integer number. The offset specifies the number of bytes(position) to be moved from the location specified by position. The position can take one of the following three values:
  • 18. • 0 beginning of file • 1 current position • 2 end of file • • The offset may be positive, meaning move forward and negative, meaning move backwards. When the operation is successful, fseek returns a zero. If we attempt to move beyond the file boundaries and error occurs and fseek returns.
  • 19. •  A file named DATA contains a series of integer numbers. Write a program to read these numbers and then write all “ODD” numbers to a file called ODD and all “even” numbers to a file called EVEN.
  • 20. DYNAMIC MEMORY ALLOCATION • The process of allocating memory at run time is known as dynamic memory allocation. malloc() and calloc() are library routines known as that can be used for allocating and freeing memory during program execution. • There are four “Memory Management Functions” available in C library routine for allocating and freeing a memory during a program execution.
  • 21. • malloc() : alloates the memory to a single element and move the pointer to the first byte • calloc() : alloates the memory to an array of elements • free() : Frees the previously allocated space • realloc() : modifies the previously allocated space
  • 22. • 1. malloc() • • A block of memory may be allocated using the function malloc(). The function reserves a block of memory of specified size and returns a pointer of type void. This means that we can assign it to any type of pointer. it takes the following form.
  • 23. • ptr = ( cast_type * ) malloc( byte_size ); • • ptr is a pointer of type cast_type. The malloc returns a pointer of cast_type to an area of memory of size byte_size. For example,
  • 24. • X = ( int * ) malloc( 100 * sizeof (int) ); • • On successful execution of this statement a memory space equivalent to “100 times for the size of int” bytes is reserved and the address of the first byte of the memory allocated is assigned to the pointer x of type int. Similarly statement
  • 25. • cptr = (char *) malloc(10); • • Allocates 10 byte of space for the cptr of type char. We may also use malloc to allocate space for complex data types such as structures.
  • 26. • For example, • stptr = ( struct store* )malloc( sizeof( struct store ) ); • Where stptr is pointer of type struct store. The malloc allocates a block of contiguous bytes. The allocation can fall if the space in the heap is not sufficient to satisfy the request. If it fails it returns a NULL.
  • 27. 2. Calloc() • Calloc is memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures. Calloc allocates multiple block of storage, each of the same size and then sets all bytes to zero. The general form of calloc is ; • • ptr = (cast_type *) calloc(n,elem_size);
  • 28. • The above statement allocates contiguous space of n blocks. Each of size elem_size. All bytes are initialized to zero and a pointer to the first byte of allocated region is returned. If there is not enough space, a NULL pointer is returned. The following segment of program allocates space to a structure variable.
  • 29. • struct student • { • char name[25]; float age; • long int id_num; • }; • typedef struct student record; • record *stptr; • int class size=30; • stptr = (record *) calloc(class_size, sizeof(record));
  • 30. 3. free() • This function is used to allocate the previously allocated space. • Look the following form : • • free(ptr); • Ptr is the pointer to the previously allocated memory space.
  • 31. • 4. realloc() : • Sometimes the previously allocated memory is not sufficient and we need additional space for more elements. realloc function is used in such type of situations. • Syntax: • ptr=realloc(ptr,new size);
  • 32. • This function allocates a new memory space of size new size to the pointer variable ptr and returns a pointer to the first byte of the memory block. •  Write a program to store a character string in a block of memory space created by malloc and then modify the same to store a larger string.