Sei sulla pagina 1di 8

File Processing

Introduction

Files are used for permanent


retention of large amount of data

Storage of data in variables is


temporary

Files are stored on secondary


storage devices

Magnetic disks, optical disks, tapes



Data Hierarcy

!it" manipulated by computer circuitry

binary digit" # or $,

!yte" commonly composed of % bits

Decimal digits, letters, special symbols

Field" a group of bytes tat conveys


meaning

&ecord" composed of related 'elds

File" a group of related records

Database" a group of related 'les



Files and Streams

()) vie*s 'les as a


se+uence of bytes

,o concept of record

-en a 'le is opened,


an ob.ect is created and
a stream is associated
*it it

/o process 'le in ()),


0iostream1,0fstream1
must be included2
ios
istream
iostream
ostream
ofstream ifstream
fstream

(reating a Se+uential File
Maintain !ank !alances
#include<iostream>
#include<fstream>
void main() {
ofstream clientF(clients.dat, ios::out);
if (!clientF){ //overloaded ios oerator !
cerr<<File could not !e oened<<endl;
e"it(#);
$
int account; c%ar name&'(); dou!le !alance;
*%ile (cin>>account>>name>>!alance){
clientF<<account<<name<<!alance<<+,n-;
$
$

Files are opened by creating ob.ects


of ifstream, ofstream, or fstream

34plicitly close 'le" clientF2close567



&eading From a Se+uential
File
#include<iostream>
#include<fstream>
#include<iomani>
void main() {
ifstream clientF(clients.dat, ios::in);
if (!clientF) .
int account; c%ar name&'(); dou!le !alance;
*%ile (clientF>>account>>name>>!alance){
cout<<setiosfla/s(ios::left)<<set*(#()
<<account<<set*(#')<<name<<set*(0)
<<setrecision(1)
<<resetiosfla/s(ios::left)
<<!alance<<+,n-;
$
$

&eposition File Position
Pointer
istream file2!3(a!c.dat);
//osition to t%e nt% !4te of file2!3
file2!3.see5/(n, ios::!e/);
//osition n !4tes for*ard from current osition
file2!3.see5/(n, ios::cur);
//osition n !4tes !ac5 from end of file2!3
file2!3.see5/(n, ios::end);
///et current osition
lon/ loc 6 file2!3.tell/();

!ot istream and ostream provide


member function for repositioning

seekg56, seekp56

8pdating Se+uential Files
'(( 7%ite (.(( '(( 7ort%in/ton (.((
8(( 9ames (.1(

Ine9cient : ;*k*ard metod

(opy all records before -ite to ne* 'le

;ppend -ortington record to ne* 'le

;ppend all records after -ite to ne* 'le

If record *ere re*ritten beginning at te


same location
'(( 7ort%in/to
n (.((mes (.1(

/ere is no easy *ay<

Potrebbero piacerti anche