Computer Science, City University of
Semester B 2021-22
CS2310 Computer Programming
Copyright By PowCoder代写 加微信 powcoder
LT10: File I/O
File I/O vs. Console I/O
“Console” refers to “keyboard + screen”
Keyboard input and screen output are volatile
Input file can be used again and again
Useful for debugging especially when volume of data is huge
Allow off-line processing
Output file retains the results after execution
Basic I/O – Keyboard and Screen
Program read input from keyboard (console) or disk storage (file) and write data to screen (console) or disk storage (file)
Sequence of inputs is conceptually treated as an object called “Stream”
Stream – a flow (sequence) of data
Input stream – a flow of data into your program
Output stream – a flow of data out of your program
Predefined console streams in C++
#include
cin : input stream physically linked to the keyboard
cout: output stream physically linked to the screen
File streams class in C++
#include
ifstream: stream class for file input
ofstream: stream class for file output
To declare an objects of class ifstream or ofstream, use
ifstream fin; // fin is a variable name
ofstream fout; // fout is a variable name
To declare an ifsteam object
ifstream fin;
To open a file for reading
fin.open(“infile.dat”);
To read the file content
fin >> x; // x is a variable
To close the file
fin.close();
To declare an ofsteam object
ofstream fout;
To open a file for writing
fout.open(“myfile.dat”) ;
To write something to the file
fout << x; //x is a variable
To close the file
fout.close();
PS: fin.open() and fout.open() refer to different functions
#include
using namespace std;
void main(){
ifstream fin;
ofstream fout;
int x,y,z;
fin.open(“input.txt”);
fout.open(“output.txt”);
fin >>x>>y>>z;
fout << “The sum is “<
#include
Using namespace std;
void main(){
ifstream in1, in2;
in1.open(“infile1.dat”);
in2.open(“infile2.dat”);
if (in1.fail()) {
cout << “Input file 1 opening failed.\n”;
exit(1); // 1 stands for error
Detecting end-of-file (EOF)
Member function eof()returns true if and only if we reach the end of the input file (no more data)
Only for objects of class ifstream
E.g. fin >> x;
if (!fin.eof()) …
The expression fin >> x has value 0 if fin has no more data
E.g. while (fin>> x)
Examples: file dump (integer only)
#include
#include
using namespace std;
void main(){
ifstream fin;
ofstream fout;
fin.open(“input.txt”);
fout.open(”output.txt”)
if(!fin.fail() && !fout.fail()) {
while (fin >> x){
fout << x <<" ";
Examples: file dump (integer only)
#include
#include
using namespace std;
void main(){
ifstream fin;
ofstream fout;
fin.open(“input.txt”);
fout.open(”output.txt”)
if(!fin.fail() && !fout.fail()) {
while (fin >> x){
fout << x <<" ";
return 0 if fin has no more data
Stream of data
/docProps/thumbnail.jpeg
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com