File Input & Output File I/O File I/O
#include <fstream> // file stream header
int main () {
std::ofstream os {"squares.txt"}; // open file
// if stream OK = can write to file
if (os.good()) {
for (int x = 1; x <= 6; ++x) {
// write x space x² newline
os << x << ' ' << (x*x) << '\n';
}
}
} // file is automatically closed
#include <iostream>
#include <fstream> // file stream header
int main () {
std::ifstream is {"squares.txt"}; // open file
// if stream OK = file readable
if ( is.good() ) {
double x, y;
// as long as any 2 values readable
while( is >> x >> y ) {
// print pairs (x,y)
std::cout << x << "² = " << y << "\n";
}
}
} // file is automatically closed
At creation / destruction
int main (int const argc, char const*const* argv) {
if (argc > 1) {
// with C-string
std::ofstream os { argv[1] };
…
} // automatically closed
else {
// with std::string C++11
std::string fn = "test.txt";
std::ofstream os { fn };
…
} // automatically closed
}
With open
and close
void bar () {
std::ofstream os;
os.open("squares.txt");
…
os.close();
// open another file:
os.open("test.txt");
…
os.close();
}
Default
ifstream is {"in.txt", ios::in};
ofstream os {"out.txt", ios::out};
(overwrite existing file)
Append to existing file
ofstream os {"log.txt", ios::app};
Binary
ifstream is {"in.jpg", ios::binary};
ofstream os {"out.jpg", ios::binary};
// we'll learn later what all this means…
std::uint64_t i = 0;
// read binary
is.read(reinterpret_cast<char*>(&i), sizeof(i));
// write binary
os.write(reinterpret_cast<char const*>(&i), sizeof(i));
Comments…