Introduction to Programming Lecture 19 Random Access Files























![Example 3 char str [ 10000 ] ; my. Input. File. read ( str Example 3 char str [ 10000 ] ; my. Input. File. read ( str](https://slidetodoc.com/presentation_image_h2/994c096892f6eb7cbc0a3dae401b4eab/image-24.jpg)







- Slides: 31
Introduction to Programming Lecture 19
Random Access Files
Files n open ( file_name , mode ) ; n close ( ) ;
ifstream my. File. Ptr ; my. File. Ptr. open ( “my. File” , ios : : in ) ;
Output File Stream ios : : app n ios : : trunc n ios : : ate n
Read/write a character get ( ) put ( ) Read a character Write a character
Number of characters to read Delimiter getline(str, 10, ‘n’) ;
File Positions
File Position Pointer
tellg ( ) Function my. File. tellg ( ) ; Returns a whole number which tell you the position of the next character to be read from the file
tellp ( ) Function my. File. tellp ( ) ; Returns a whole number which tell you the position o the next character to be written in a file
For Positioning in the file seekg ( ) ; seekp ( ) ;
seekg ( ) Number of characters to move to Starting point file. Ptr. seekg ( long Num , ios : : origin ) ;
seekg ( ) seekg ( 10 L , ios : : beg ) ; seekg (10 L , ios : : cur ) ; seekg ( 10 L , ios : : end ) ;
Example 1 #include<fstream. h> main ( ) { int length ; ifstream in. File ( “my. File. txt” ) ; in. File. seekg ( 0 L , ios : : end ) ; length = in. File. tellg ( ) ; }
Name : Jamil Ahmed : File city Date-of-Birth : : Sukkur 10 -10 -1982 : : Rawalpindi
Merge Method Original file This is a text data And needs To be replaced Empty file NOT
seekg ( ) seekg ( 2201 L , ios : : beg ) ;
fstream my. File ( “Sample. txt” , ios : : in | ios : : out ) ;
OR Function A 0 0 1 1 B 0 1 Output 0 1 1 1
Example 2 This is an Apple This is a Sample
get ( ) and put ( ) character in a file my. Input. File. get ( c ) ; my. Output. File. put ( c ) ;
read ( ) and write ( ) Functions Area in memory Number of bytes to be read ( char *buff , int count ) ; Area in memory Number of bytes to be written write ( char *buff , int count ) ;
Example 3 char str [ 10000 ] ; my. Input. File. read ( str , 10000 ) ; my. Ouput. File. write ( str , 10000 ) ;
seekg ( ) seekg ( 0 L , ios : : end ) ;
seekg ( ) seekg ( -1 L , ios : : end ) ;
seekg ( ) seekg ( -2 L , ios : : cur ) ;
Address of the integer ‘i’ Number of bytes to be written my. Output. File. write ( &i , 4 ) ;
sizeof ( ) ;
Address of the integer ‘i’ Size of integer my. Output. File. write ( &i , sizeof ( i ) ) ;
for ( i = 0 ; i < 100 ; i ++ ) { my. Output. File. write ( &i , sizeof ( i ) ) ; } my. Output. File. close ( ) ;