C++ fstream 读取 .dat 文件中的 double 类型数据
使用 C++ 的 fstream 类可以轻松读取 .dat 文件中的 double 类型数据。以下是示例代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file('data.dat', ios::in | ios::binary);
if (!file.is_open())
{
cout << 'Failed to open file!' << endl;
return 1;
}
double num;
while (file.read(reinterpret_cast<char*>(&num), sizeof(double)))
{
cout << num << endl;
}
file.close();
return 0;
}
在上面的代码中,我们首先使用 fstream 类和 ios::binary 标志打开 .dat 文件。接下来,我们使用 read() 函数从文件中读取 double 类型数据。read() 函数的第一个参数是一个字符指针,它指向一个存储 double 类型数据的缓冲区。我们使用 reinterpret_cast 将指针转换为 char* 类型,以便我们可以将其传递给 read() 函数。第二个参数是要读取的字节数,这里是 sizeof(double)。在 while 循环中,我们读取文件中的每个 double 类型数据并将其打印到屏幕上。最后,我们关闭文件并返回 0。
原文地址: https://www.cveoy.top/t/topic/oirB 著作权归作者所有。请勿转载和采集!