Академический Документы
Профессиональный Документы
Культура Документы
Stream I/O
one program can have multiple I/O streams associated and vice-versa
Input/Output
Extraction/Insertion
cout << Hello world!;
cout << The value of i is << i << endl; //endl puts a new line
Stream classes
Classes have methods, as we know
so does cin and cout some common to all I/O stream classes in C++ File I/O, binary/text mode I/O, console I/O
One example
but terminates when encounters space (ascii character 32) workaround? use the get method
Snippet
char tData[100];
// This is a method in C++ istream classes for
Inputting i am oh so cool
cin.get gets the entire line just cin will get I
// inputting text
//including spaces cin.get( tData, 99 ); // or cin.get(tData,99,'\n');
space termination
Or,
File I/O
myofile.close();
... ifstream myifile;
myifile.open( sample.txt );
string oneLine; getline( myifile, oneLine );
to write an int:
to read an int:
Binary files
text files stores everything as ascii text strings even numbers binary files do not
Difference?
Example program
Accepts student ID (I input 1010) Accepts name (I input Junaed) Accepts CGPA (I input 4.5)
Storage
TEXT FILE
BINARY FILE
Binary files
Failures?
If open fails?
End of file?
Random vs Sequential
nonsequential, as a result faster access times, content must be suitable for random access
or console input
File heads
Access positions
one each for read and write
seekg (as in get) for reading seekp (as in put) for writing ifstreams have seekg ofstreams have seekp
seeking
mode can be
ios::beg: from the beginning ios::end from the end ios::cur from current position
telling
returns as long integer, the position of the get and put positions, respectively
example seeks
file.seekg( 20L, ios::beg );
file.seekp( -100L, ios::cur );