#include <fstream>
This library provides 3 objects for us to work this:
- ifstream: To read data FROM an input file stream.
- ofstream: To stream data TO an output filestream.
- fstream: Does both inputting and outputting. To read data from an input file and stream data to an output file.
Read from a file
Use the “ifstream” object#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream my_file;
my_file.open("files/1.board");
if (my_file) {
cout << "The file stream has been created!" << "\n";
}
}
Explanation:
- Let’s assume the file to be read is called “1.board” and is within the “file” directory hence it’s path is “files/1.board”
- We’ve included the <fstream> ibrary in addition to other pre-processor directives like <iostream> (since we’re using cout) and <string> (since we’re using strings)
- Using the standard namespace
- Declare function int main()
- Within the body of the function make a new input file into which data will be streamed called my_file using the ifstream object
- Open the newly created file called my_file which is at the path files/1.board
- Files must be opened before you can read or write into them
- If my_file has been opened THEN
- print out the string “The file stream has been created!”
Read data from a file
getline
method: The get line method reads line by line from an input stream. This method takes 2 parameters:
- ifstream object
- And a string to write the line to
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream my_file;
my_file.open("files/1.board");
if (my_file) {
cout << "The file stream has been created!" << "\n";
string line;
while (getline(my_file, line)) {
cout << line << "\n";
}
}
}
Leave a Reply