To write data into a stream, Tools/Streams/OutStreams.h must be included, a stream must be constructed, and the data must be written into the stream. For example, to write data into a text file, the following code would be appropriate(合适的):
#include "Tools/Streams/OutStreams.h"
// ...
OutTextFile stream("MyFile.txt");
stream << 1 << 3.14 << "Hello Dolly" << endl << 42;
The file will be written into the configuration directory(配置目录), e.g. Config/MyFile.txt on the PC. It will look like this:
1 3.14 "Hello Dolly"
42
由于空格用于分隔文本文件中的条目,字符串“Hello Dolly”用双引号括起来。可以使用以下代码读取数据:
#include "Tools/Streams/InStreams.h"
// ...
InTextFile stream("MyFile.txt");
int a, d;
double b;
std::string c;
stream >> a >> b >> c >> d;
It is not necessary to read the symbol endl here, although it would also work, i. e. it would be ignored.
为了在不分离条目和添加双引号的情况下写入文本流,可以使用OutTextRawFile代替OutTextFile。它格式化来自ANSI c++ cout流的已知数据。以上示例的格式如下:
13.14 Hello Dolly
42
为了使流独立于所使用的流类型,可以将其封装在函数中。在这种情况下,应该只使用抽象基类In和Out来作为参数传递流,因为这会产生与流类型的独立性:
#include "Tools/Streams/InOut.h"
void write(Out& stream) {
stream << 1 << 3.14 << "Hello Dolly" << endl << 42;
}
void read(In& stream) {
int a, d;
double b;
std::string c;
stream >> a >> b >> c >> d;
}
// ...
OutTextFile stream("MyFile.txt");
write(stream);
// ...
InTextFile stream("MyFile.txt");
read(stream);