Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C18:Strfile.cpp // Stream I/O with files // The difference between get() & getline() #include <fstream> #include <iostream> #include "../require.h" using namespace std; int main() { const int sz = 100; // Buffer size; char buf[sz]; { ifstream in("Strfile.cpp"); // Read assure(in, "Strfile.cpp"); // Verify open ofstream out("Strfile.out"); // Write assure(out, "Strfile.out"); int i = 1; // Line counter // A less-convenient approach for line input: while(in.get(buf, sz)) { // Leaves \n in input in.get(); // Throw away next character (\n) cout << buf << endl; // Must add \n // File output just like standard I/O: out << i++ << ": " << buf << endl; } } // Destructors close in & out ifstream in("Strfile.out"); assure(in, "Strfile.out"); // More convenient line input: while(in.getline(buf, sz)) { // Removes \n char* cp = buf; while(*cp != ':') cp++; cp += 2; // Past ": " cout << cp << endl; // Must still add \n } } ///:~
Flag
|
Function
|
---|---|
ios::in
|
Opens
an input file. Use this as an open mode for an
ofstream
to prevent truncating an existing file.
|
ios::out
|
Opens
an output file. When used for an
ofstream
without
ios::app,
ios::ate
or
ios::in,
ios::trunc
is implied.
|
ios::app
|
Opens
an output file for appending.
|
ios::ate
|
Opens
an existing file (either input or output) and seeks the end.
|
ios::nocreate
|
Opens
a file only if it already exists. (Otherwise it fails.)
|
ios::noreplace
|
Opens
a file only if it does not exist. (Otherwise it fails.)
|
ios::trunc
|
Opens
a file and deletes the old file, if it already exists.
|
ios::binary
|
Opens
a file in binary mode. Default is text mode.
|