如何从二进制文件中查找和读取
How to seek and read from binary file?
我对高级文件和结构还是个新手。我只是很难弄清楚如何从文件中查找和读取特定记录。以及如何通过记录编号显示特定记录的信息?
#include <iostream>
#include <fstream>
using namespace std;
struct catalog
{
char title[50];
char author[50];
char publisher[30];
int yearpublish;
double price;
};
void showRec(catalog);
long byteNum(int);
int main()
{
catalog book;
fstream fbook("book.dat",ios::in|ios::binary);
if (!fbook)
{
cout <<"Error opening file";
return 0;
}
//Seek and read record 2 (the third record)
showRec(book); // Display record 2
//Seek and read record 0 (the first record)
showRec(book); // Display record 0
fbook.close();
return 0;
}
void showRec(catalog record)
{
cout << "Title:" << record.title << endl;
cout << "Author:" << record.author << endl;
cout << "Publisher name:" << record.publisher << endl;
cout << "Year publish:" << record.yearpublish << endl;
cout << "Price:" << record.price << endl << endl;
}
long byteNum(int recNum)
{
return sizeof(catalog) * recNum;
}
请帮忙。非常感谢。
您需要的C++istream
方法是seekg
和read
。
// Seek and read record 2
fbook.seekg(byteNum(2));
fbook.read((char*)&book, sizeof(book));
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 正在查找文档以获得PS4平台的C++中的设备信息
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- 无法读取保存的 TensorFlow 模型(无法查找标头条目)
- 读取IMAGE_EXPORT_DIRECTORY以查找导出的函数名称会导致访问冲突
- C++如何使用读取进程内存查找进程内存中使用的最后一个(偏移量 - 地址)
- IDE 可以直接读取 C 库源代码吗?如何查找所需的源代码
- 使用 std::find 查找从二进制文件中读取的字符并转换为 std::vector 中的 std::string<string> 会产生这种不可预测的行为?
- C 功能:读取直到文件结束 - 查找代码中的错误
- 如何向后读取文件以有效地查找子字符串
- 在opencv中查找方块:访问违规读取位置
- 使用 ifstream 读取列中随机生成的数字的文本文件,并从列表中查找最小值和最大值
- 如何在不读取整个文件的情况下查找文件中字符串的长度
- 在读取udp之前查找sockaddr信息
- 是对std::map线程安全的查找和读取操作
- 如何从二进制文件中查找和读取
- 逐字符从管道读取缓冲区/查找管道中数据的大小
- 读取(简单)程序集以查找使用C++模板生成的编译时计算