在 C++ 中读取和写入文件位
在 C++ 中,诸如文本文件压缩之类的过程需要读取文件中的位并将其写入文件中。 在本文中,您将学习如何在 C++ 中毫无错误地读取或写入文件位。
istream 和 ostream 作为析构函数,在需要向文件读写位时发挥着至关重要的作用。
但是,在霍夫曼编码中通过霍夫曼树进行编码时,可能需要将位写入二进制输出文件,并且您可以将布尔值打包成 8 位块,然后写入字节,而不是使用流。
使用 iStream 和 oStream 在 C++ 中读取和写入文件位
BitInputStream 类包含用于读取和写入位的 iStream 和 oStream 功能。 由于 ifstream 和 ofstream 可以通过将流附加到物理文件名来打开二进制文件,因此它们对于读取或写入文件位也至关重要。
此外,目标 BitInputStream 类的 open 成员函数可以提供未共同描述的参数(可选参数)。
ostream 是 open 成员函数之一,它导致从内存位置写入 n 个字节,并在 n 个字节之前传输指针。
fstream 流类比任何其他流类都具有更高的功能,因为它能够读取和写入文件。
文件流以二进制方式进行读写操作并不重要,因为它们是以二进制方式打开的; 相反,它们可以执行任何形式的读/写操作。
#include <fstream>
#include <iostream> // reflects `istream` and `ostream`
// optional
using namespace std;
// struct declaration
struct army_per
{
// an entity that reflects three attributes
int ref_no;
string rank, name;
};
// primary class
int main()
{
// declaration of `ofstream` for read/write `army_per` file
ofstream wf ("army_per.dat", ios::out | ios::binary);
if(!wf)
{
cout << "Unable to open the file!" << endl;
return 1;
}
// entity declaration
army_per soldier[2];
// first entry
soldier[0].ref_no = 1;
soldier[0].name = "Rob";
soldier[0].rank = "Captain";
//second entry
soldier[1].ref_no = 2;
soldier[1].name = "Stannis";
soldier[1].rank = "Major";
for (int i = 0; i < 2; i++)
wf.write((char *) &soldier[i], sizeof(army_per));
wf.close();
if (!wf.good())
{
cout << "Error: bits writing time error!" << endl;
return 1;
}
ifstream rf("army_per.dat", ios::out | ios::binary);
if (!rf)
{
cout << "File is not found!" << endl;
return 1;
}
army_per rstu[2];
for(int i = 0; i < 2; i++)
rf.read((char *) &rstu[i], sizeof(army_per));
rf.close();
if (!rf.good())
{
cout << "Error: bits reading time error occured!" << endl;
return 1;
}
cout << "Army Div-32 details:" << endl;
for(int i = 0; i < 2; i++)
{
// access the elements of the object and output the result of each individual
cout << "Reference No: " << soldier[i].ref_no << endl;
cout << "Name: " << soldier[i].name << endl;
cout << "Rank: " << soldier[i].rank << endl;
cout << endl;
}
return 0;
}
输出:
Army Div-32 details:
Reference No: 1
Name: Rob
Rank: Captain
Reference No: 2
Name: Stannis
Rank: Major
一般来说,人们认为cin和cout属于C++中的ostream,但cin对象(作为全局对象)属于istream类。
此外,文件流包括: ifstream
和 ofstream
分别继承自 istream 和 ostream。
程序员应该意识到缓冲区总是大于它应该保存的数据。 在 C++ 中,如果出现未检查或已解决的错误,则降低程序可靠性的可能性会增加,并确保没有文件操作导致程序停止。
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。