Inputs / Outputs: The streams in C ++
To save data after closing your programs, you must write the data into files. Here is how to proceed.
To open a file, either for reading or writing, you must declare an instance of ofstream / ifstream. Make use of "fstream".
Open a file for reading
To open a file for reading, "ifstream" is needed, then we must close this stream with
the function close().
Open the file "data.txt" (read only)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
file.close(); //close stream
return 0;
}
This code does nothing in appearance, but in reality it opens the file "data.txt" in reading mode.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream file("data.txt");
char character;
while(file.get(character))
cout << character;
cout << endl << endl;
file.close(); //close stream
return 0;
}
Open a file for writing
To open a file for writing, "ofstream" is needed, then we must close this stream with the function close ().
Open the file "data.txt" to write in it
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("data.txt");
file.close(); //close stream
return 0;
}
This code does nothing in appearance, but in reality it opens the file "data.txt" in writing mode.
Writing in "data.txt"
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char niceday[10] = "niceday!"
ofstream file("data.txt");
file << niceday; //writing the data
file.close(); //close stream
return 0;
}
Opening different types of streams:
By default, ofstream automatically creates a file if it doesn't exist. But you can add parameters to change the behavior:
Here is a list of possible parameters:
- ios:: app: Open the file by adding at the end, instead of removing its content in advance.
- ios:: ate: To be at the end of file.
- ios:: trunc: The default behavior: the content is deleted at the opening.
- ios:: nocreate: Causes failure when opening if file does not exist.
- ios:: noreplace: Causes a failure when opening if the file already exists
See also
Knowledge communities.