File Input & Output File I/O File I/O
with
std::ofstream
(output file stream)
#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
- makes a new file
squares.txt
- if file already exists → overwrites!
- writes 2 numbers per line, separated by a space
squares.txt
1·1\n
2·4\n
3·9\n
4·16\n
5·25\n
6·36\n
with
std::ifstream
(input file stream)
#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
squares.txt
1·1\n
2·4\n
3·9\n
4·16\n
5·25\n
6·36\n
Output
1² = 1
2² = 4
3² = 9
4² = 16
5² = 25
6² = 36
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));
Runnable Example Program
#include <iostream>
#include <fstream>
#include <cstdint>
int main (int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "usage: " << argv[0] << " <integer> <filename>\n";
return 0;
}
std::string filename {argv[2]};
{ // write binary
std::uint64_t i = atoi(argv[1]);
std::cout << "writing: " << i << " to " << filename << "\n";
std::ofstream os {filename, std::ios::binary};
if (os.good()) {
os.write(reinterpret_cast<char const*>(&i), sizeof(i));
}
}
{ // read binary
std::uint64_t i = 0;
std::ifstream is {filename, std::ios::binary};
if (is.good()) {
is.read(reinterpret_cast<char*>(&i), sizeof(i));
std::cout << "read as: " << i << "\n";
}
}
}
Comments…