<< 在输出期间提供数字的自动格式化。同样,流提取操作符 >> 提供数字输入的解析。例如,来看以下程序片段:
ofstream file("num.dat");
short x = 12 97;
file << x;
最后一个语句将 x 的内容写入文件。然而,当数字被写入时,它将被存储为字符 '1'、'2'、'9' 和 '7',如图 1 所示。file.open("stuff.dat", ios::out | ios::binary);
请注意,ios::out 和 ios::binary 标志使用|运算符联合加入到语句中,这导致文件以输出和二进制模式打开。注意,默认情况下,文件以文本模式打开。
ostream 和 ofstream 类的 write 成员函数可用于将二进制数据写入文件或其他输出流。要调用该函数,需指定一个缓冲区的地址,该缓冲区包含一个要写入的字节数组和一个指示要写入多少字节的整数:write(addressOfBuffer, numberOfBytes);
write 成员函数不会区分缓冲区中的整数、浮点数或其他类型;它只是将缓冲区视为一个字节数组。由于 C++ 不支持指向字节的指针,因此 write 函数原型将指定缓冲区的地址是指向 char 的指针:write(char *addressOfBuffer, int numberOfBytes);
这意味着当调用 write 时,需要告诉编译器将缓冲区的地址解释为指向 diar 的指针。要做到这一点,可以使用称为 reinterpret_cast 的特殊形式的类型转换。简单地说,reinterpret_cast 可用于强制编译器解释一个类型的位,就好像它们定义了一个不同类型的值。
double d = 45.9;
double *pd = &d;
char *pChar;
//将指向double的指针转换为指向char的指针
pChar = reinterpret_cast<char *>(pd);
reinterpret_cast<TargetType>(value);
以下是使用 write 将一个 double 类型数字和一个包含 3 个 double 类型数字的数组写入文件的示例:
double dl = 45.9;
double dArray[3] = { 12.3, 45.8, 19.0 };
ofstream outFile("stuff.dat", ios::binary);
outFile.write(reinterpret_cast<char *>(&dl), sizeof(dl));
outFile.write(reinterpret_cast<char *>(dArray),sizeOf(dArray));
char ch = 'X';
char charArray[5] = "Hello";
outFile.write(&ch, sizeof(ch));
outFile.write(charArray, sizeof(charArray));
read(addressOfBuffer, numberOfBytes)
必须使用 reinterpret_cast 将缓冲区的地址解释为指向 char 的指针。可以通过调用输入流上的 fail() 成员函数来发现指定的字节数是否成功读取。
//This program uses the write and read functions.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//File object used to access file
fstream file("nums.dat", ios::out | ios::binary);
if (!file)
{
cout << "Error opening file.";
return 0;
}
//Integer data to write to binary file
int buffer[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(buffer) / sizeof(buffer[0]);
// Write the data and close the file
cout << "Now writing the data to the file.\n";
file.write(reinterpret_cast<char *>(buffer), sizeof(buffer));
file.close ();
// Open the file and use a binary read to read contents of the file into an array
file.open("nums.dat", ios::in);
if (!file)
{
cout << "Error opening file.";
return 0;
}
cout << "Now reading the data back into memory.\n";
file.read(reinterpret_cast<char *>(buffer), sizeof (buffer));
// Write out the array entries
for (int count = 0; count < size; count++)
cout << buffer[count] << " ";
// Close the file
file.close ();
return 0;
}
程序屏幕输出:
Now writing the data to the file.
Now reading the data back into memory.
1 2 3 4 5 6 7 8 9 10
int buffer[ ] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(buffer)/sizeof(buffer[0]);
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有