File Output and Input article - #82
Conversation
Added sub-items for 'File Input and Output' section in sidebar.
| ``` | ||
| This will create the file if it doesn’t exist, or overwrite it if it already exists. | ||
|
|
||
| ## Redirecting standard input/output {#redirecting-stdio} |
There was a problem hiding this comment.
I think I'd probably put this in a separate article. I'm not 100% sure if this is something useful for beginners. Would want to get another opinion here.
| In C++, you can use the `fstream` library to create, write and read files. \ | ||
| To use fstream, you need to include the `<iostream>` **AND** `<fstream>` header files. | ||
|
|
||
| ``` cpp |
There was a problem hiding this comment.
No space between ` and cpp
| ## Read a File (`std::ifstream`) {#read-a-file} | ||
| `std::ifstream` is used to read data from a file. | ||
|
|
||
| ``` cpp |
|
|
||
| # File Input and Output | ||
| In C++, you can use the `fstream` library to create, write and read files. \ | ||
| To use fstream, you need to include the `<iostream>` **AND** `<fstream>` header files. |
There was a problem hiding this comment.
You only need fstream.
| --- | ||
|
|
||
| # File Input and Output | ||
| In C++, you can use the `fstream` library to create, write and read files. \ |
There was a problem hiding this comment.
Instead of jumping right into "how", a brief discussion of what and why may be useful.
| #include <fstream> | ||
| ``` | ||
| The `<fstream>` library provides three main classes: | ||
| |Function|Description| |
There was a problem hiding this comment.
These aren't functions, these are types.
|
|
||
| std::ifstream file("filename.txt"); | ||
|
|
||
| if (!file) return 1; |
There was a problem hiding this comment.
For consistency, use {} around branches
| ``` cpp | ||
| std::ofstream file("filename.txt"); | ||
|
|
||
| if (!file) return 1; |
There was a problem hiding this comment.
Same comment about {}
| |`std::fstream`|Used for both reading and writing| | ||
|
|
||
| ::: info Note | ||
| `std::fstream` is a general-purpose file stream, while `std::ifstream` and `std::ofstream` are more specific and commonly used in practice. |
There was a problem hiding this comment.
Wording feels a bit weird, I'm just not sure how to address it right now.
No description provided.