CS201-19 - Introduction to Programming Lecture 19 Random...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 19 Random Access Files Files open ( file_name , mode ) ; close ( ) ; ifstream myFilePtr ; myFilePtr.open ( “myFile” , ios :: in ) ; Output File Stream ios :: app ios :: ate ios :: trunc 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 Returns a whole number which tell you the position of the next character to be read from the file myFile.tellg ( ) ; tellp ( ) Function myFile.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 filePtr.seekg ( long Num , ios :: origin ) ; seekg ( ) seekg ( 10L , ios :: beg ) ; seekg (10L , ios :: cur ) ; seekg ( 10L , ios :: end ) ; #include<fstream.h> main ( ) { int length ; ifstream inFile ( “myFile.txt” ) ; inFile.seekg ( 0L , ios :: end ) ; length = inFile.tellg ( ) ; } Example 1 Name city Date­of­Birth : : : Jamil Ahmed Sukkur 10­10­1982 : : : Rawalpindi File Merge Method Original file This is a text data And needs To be replaced Empty file NOT seekg ( ) seekg ( 2201L , ios :: beg ) ; fstream fstream myFile ( “Sample.txt” , ios :: in | ios :: out ) ; A 0 0 1 1 OR Function B 0 1 0 1 Output 0 1 1 1 This is an Apple Example 2 This is a Sample get ( ) and put ( ) character in a file myInputFile.get ( c ) ; myOutputFile.put ( c ) ; read ( ) and write ( ) Functions Area in memory Number of bytes to be read read ( char *buff , int count ) ; Area in memory Number of bytes to be written write ( char *buff , int count ) ; Example 3 char str [ 10000 ] ; myInputFile.read ( str , 10000 ) ; myOuputFile.write ( str , 10000 ) ; seekg ( ) seekg ( 0L , ios :: end ) ; seekg ( ) seekg ( ­1L , ios :: end ) ; seekg ( ) seekg ( ­2L , ios :: cur ) ; Address of the integer ‘i’ Number of bytes to be written myOutputFile.write ( &i , 4 ) ; sizeof ( ) ; Address of the integer ‘i’ Size of integer myOutputFile.write ( &i , sizeof ( i ) ) ; for ( i = 0 ; i < 100 ; i ++ ) { myOutputFile.write ( &i , sizeof ( i ) ) ; } myOutputFile.close ( ) ; ...
View Full Document

This note was uploaded on 01/12/2010 for the course CS CS 201 taught by Professor Dr.naveedmalik during the Spring '09 term at Virtual University of Pakistan.

Ask a homework question - tutors are online