Skip to content

Commit 4845aca

Browse files
committed
Pulled code out of Replit to make it a simple codeblock
1 parent 3d46642 commit 4845aca

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

pretext/Input_and_Output/DealingWithIOFailures.ptx

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,29 @@
1515
occured, in_stream may be in a corrupted state and it is best not to attempt any more
1616
operations with it.</p>
1717
<p>The following example code fragment safely quits the program entirely in case an I/O operation fails:</p>
18-
<raw format="html" xml:space="preserve">&lt;div&gt;
19-
&lt;iframe height="400px" width="100%" src="https://repl.it/@CodyWMitchell/File-Handling-1?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"&gt;&lt;/iframe&gt;
20-
&lt;/div&gt;</raw>
18+
<blockquote>
19+
<program language="cpp">
20+
<input>
21+
#include &lt;cstdlib&lt; // for the fail member function
22+
#include &lt;fstream&lt; // for file I/O definitions
23+
#include &lt;iostream&lt; // for cout definition
24+
using namespace std;
25+
26+
int main() {
27+
ifstream in_stream;
28+
// Try changing this to realFile.txt
29+
in_stream.open("realFile.txt");
30+
if (in_stream.fail()) {
31+
cout &lt;&lt; "Sorry, the file couldn't be opened!\n";
32+
exit(1); // This exit value indicates an error happened (usual exit
33+
// value is 0)
34+
}
35+
36+
return 0;
37+
}
38+
</input>
39+
</program>
40+
</blockquote>
2141
<p>After opening the <q>myFile.txt</q> file, the <c>if</c> conditional checks to see if there was an error. If so, the program will output the apologetic error message and then exit. The <c>exit(1)</c> function from the library <c>cstdlib</c> enables the program to terminate at that point and have it return a <q>1</q> versus a <q>0</q>, indicating an Error has occurred.</p>
2242
<p>For more on Error Handling, see section 1.11.</p>
2343
</section>

0 commit comments

Comments
 (0)