| 1 |
#include <fstream> |
| 2 |
#include <iostream> |
| 3 |
#include <string> |
| 4 |
|
| 5 |
using namespace std; |
| 6 |
|
| 7 |
int main() |
| 8 |
{ |
| 9 |
fstream rw("fname", ios::out | ios::in); |
| 10 |
|
| 11 |
if (!rw) // file didn't exist yet |
| 12 |
{ |
| 13 |
rw.clear(); // try again, creating it using ios::trunc |
| 14 |
rw.open("fname", ios::out | ios::trunc | ios::in); |
| 15 |
} |
| 16 |
|
| 17 |
if (!rw) // can't even create it: bail out |
| 18 |
{ |
| 19 |
cerr << "Opening `fname' failed miserably" << '\n'; |
| 20 |
return 1; |
| 21 |
} |
| 22 |
|
| 23 |
cerr << "We're at: " << rw.tellp() << '\n'; |
| 24 |
|
| 25 |
// write something |
| 26 |
rw << "Hello world" << '\n'; |
| 27 |
|
| 28 |
rw.seekg(0); // go back and read what's written |
| 29 |
|
| 30 |
string s; |
| 31 |
getline(rw, s); |
| 32 |
|
| 33 |
cout << "Read: " << s << '\n'; |
| 34 |
} |