Lecture 6 - Sept 19, 2023
Summary
In this lecture, we introduce file input/output and what happens when the input is unexpected.
Last lecture
Separate compilation and header guards.
Today
C++ file I/O and handling errors.
There are many ways to take input and produce output.
Standard input-output
Using cout
and cin
from iostream
.
#include <iostream>
using namespace std;
int main() {
int x;
<< "Hello world" << endl;
cout >> x;
cin return 0;
}
File input-output
Using ifstream
and ofstream
from fstream
.
Output to a file
#include <fstream>
using namespace std;
int main() {
("output.txt");
ofstream outFile= "We are engineers!";
string name << name;
outFile .close();
outFile}
If a file does not exist, it will be created. If it exists, its contents will be overwritten.
To append to a file, use outFile.open("output.txt", ios::app)
.
Input from a file
#include <fstream>
using namespace std;
int main() {
;
ifstream inputFile.open("myFile.txt");
inputFile
// or ifstream inputFile("myFile.txt");
// to replace the two lines above
int num1, num2, num3;
// input from file
>> num1 >> num2 >> num3;
inputFile
.close();
inputFile
return 0;
}
Where to find the file?
// absolute path
.open("/u/prof/emarasal/ece244/lab1/myFile.txt")
inFile
// relative path
.open("lab1/myFile.txt")
inFile.open("../myFile.txt")
inFile
// current directory
.open("myFile.txt") inFile
Buffering
- The output is not immediately written to a file.
- It will be written in “chunks”.
- Why buffering? Writing in a buffer is much faster than writing in a file.
- To optimize resources, writing in files happens in chunks.
- To force output, use
outputFile.flush()
oroutputFile << endl;
.
Remember the diagram from lecture 5.
Handling I/O errors
- Input stream is stored in a buffer.
- This buffer is only available when
\n
is entered. cin
ignores/skips delimiters or whitespaces- Delimiters are
,
\t
,\n
.
Reading still happens until a delimiter is seen or when something wrong happens!
How do we know a failure ocurred?
- To detect tat a file does not exist,
inputFile.fail()
will be set totrue
. - TO detect an issue with reading a variable,
cin.fail()
orinputFile.fail()
will be set totrue
. - To detect we reached the end of a file,
cin.eof()
andinputFile.eof()
will be set totrue
. However,inputFile.eof()
will not set the failure flag totrue
.
cin.eof()
is CTRL+D on PC and CMD+D on Mac.
What is cerr
? It is an output stream like cout
. It is unbuffered unlike cout
. This means that the output appears immediately on the console/terminal.
Why return 1
? Any non-zero number signals an error.
What to do when a failure with input occurs?
cin.clear()
will clear the failure condition so cin.fail()
and cin.eof()
are back to false
.
cin.ignore(int n, char ch)
will discard n
characters or up to character ch
, whichever comes first.