类ofstream, ifstream 和fstream 是分别从ostream, istream 和iostream 中引申而来的。这就是为什么 fstream 的对象可以使用其父类的成员来访问数据。 |
一般来说,我们将使用这些类与同控制台(console)交互同样的成员函数(cin 和 cout)来进行输入输出。如下面的例题所示,我们使用重载的插入操作符<<: |
// writing on a text file |
#include <fiostream.h> |
|
int main () { |
ofstream examplefile ( "example.txt" ); |
if (examplefile.is_open()) { |
examplefile << "This is a line.\n" ; |
examplefile << "This is another line.\n" ; |
examplefile.close(); |
} |
return 0; |
} |
|
file example.txt |
This is a line. |
This is another line. |
从文件中读入数据也可以用与 cin的使用同样的方法: |
// reading a text file |
#include <iostream.h> |
#include <fstream.h> |
#include <stdlib.h> |
|
int main () { |
char buffer[256]; |
ifstream examplefile ( "example.txt" ); |
if (! examplefile.is_open()) |
{ cout << "Error opening file" ; exit (1); } |
while (! examplefile.eof() ) { |
examplefile.getline (buffer,100); |
cout << buffer << endl; |
} |
return 0; |
} |