gpt4 book ai didi

c++ - 关闭程序后如何从二进制文件中读取字符串

转载 作者:行者123 更新时间:2023-11-28 04:28:36 24 4
gpt4 key购买 nike

我有结构

struct Order
{
unsigned int productamount = 0;
Products product = Products::OOPlabs;
double cost = 0.0;
string FIO = "Иванов Иван Иванович";
unsigned int orderID = 0;
};

以及二进制写入和读取该结构数组的函数

bool createbinfile(string way, Order* request, int reqlen)
{
ofstream f(way, ios::trunc | ios::binary);
if (!f.is_open())
{
cout << "Файл не найден\n";
return false;
}
else if (f.rdstate())
{
cout << "Ошибка неизвестной природы\n";
return false;
}
f.write((char*)&reqlen, sizeof(int));
for (int i = 0; i < reqlen; i++)
{
f.write(reinterpret_cast<char *>(&request[i].productamount), sizeof(unsigned int));
f.write(reinterpret_cast<char *>(&request[i].product), sizeof(Products));
f.write(reinterpret_cast<char *>(&request[i].cost), sizeof(double));
size_t tmp = request[i].FIO.length();
f.write(reinterpret_cast<char *>(&tmp), sizeof(size_t));
f.write(&request[i].FIO[0], tmp);
}
f.close();
return true;
}

bool readbinfile(string way, Order* &request, int &len)
{
ifstream f(way, ios::binary);
if (!f.is_open())
{
cout << "Файл не найден\n";
return false;
}
else if (f.rdstate())
{
cout << "Ошибка неизвестной природы\n";
return false;
}
f.read(reinterpret_cast<char *>(&len), sizeof(int));
for (int i = 0; i < len; i++)
{
f.read(reinterpret_cast<char *>(&request[i].productamount), sizeof(unsigned int));
f.read(reinterpret_cast<char *>(&request[i].product), sizeof(Products));
f.read(reinterpret_cast<char *>(&request[i].cost), sizeof(double));
size_t tmp = 0;
f.read(reinterpret_cast<char *>(&tmp), sizeof(size_t));
request[i].FIO.resize(tmp);
f.read(&request[i].FIO[0], tmp);
}
f.close();
return true;
}

字符串有问题。我可以在执行期间以二进制模式读取和写入它,但在重新启动程序后我无法读取它 - 具有“访问冲突写入位置”。为什么?如果我一个字一个字地写,它就会重复。我该如何解决?问题是关于 null 终止、序列化、类型转换,还是什么?我很困惑。我错过了什么吗?

最佳答案

将流操作符添加到类/结构中通常很好,因为它可以将大问题分解为较小的部分。我在这里做了一个例子。我添加了一个类 (OrderBox) 来保存许多 Order 对象,并为该类添加了流操作符。我没有将 FIO 字段的长度写入文件,而是读/写到 \0。由于 \0 在字符串中间完全有效(但我假设您不会使用那样的字符串),我确保 \0 在中间字符串永远不会保存到文件中(在 Order 的 ofstream 运算符中查找 std::strlen)。应该在 C++14/17/2a 中工作。

#include <iostream>
#include <initializer_list>
#include <fstream>
#include <vector>
#include <cstring>
#include <stdexcept>

enum Products {OOPlabs}; // no idea if this is an enum, needed it to compile ...

//-----------------------------------------------------------------------------
// slightly restructured - I put the FIO field last
struct Order
{
unsigned int productamount = 0;
Products product = Products::OOPlabs;
double cost = 0.0;
unsigned int orderID = 0;
std::string FIO = "Иванов Иван Иванович";

// operator to read from file
friend std::ifstream& operator>>(std::ifstream&, Order&);

// operator to write to file
friend std::ofstream& operator<<(std::ofstream&, const Order&);

// operator to stream to other ostreams, like std::cout
friend std::ostream& operator<<(std::ostream&, const Order&);
};

using OrderVec = std::vector<Order>;

//-----------------------------------------------------------------------------
// read one Order from a file stream
std::ifstream& operator>>(std::ifstream& is, Order& ord) {
is.read(reinterpret_cast<char*>(&ord.productamount), sizeof(ord.productamount));
is.read(reinterpret_cast<char*>(&ord.product), sizeof(ord.product));
is.read(reinterpret_cast<char*>(&ord.cost), sizeof(ord.cost));
is.read(reinterpret_cast<char*>(&ord.orderID), sizeof(ord.orderID));
std::getline(is, ord.FIO, '\0');
return is;
}

// write one Order to a file stream
std::ofstream& operator<<(std::ofstream& os, const Order& ord) {
os.write(reinterpret_cast<const char*>(&ord.productamount), sizeof(ord.productamount));
os.write(reinterpret_cast<const char*>(&ord.product), sizeof(ord.product));
os.write(reinterpret_cast<const char*>(&ord.cost), sizeof(ord.cost));
os.write(reinterpret_cast<const char*>(&ord.orderID), sizeof(ord.orderID));
// using strlen in case a '\0' has snuck into the string
os.write(ord.FIO.c_str(), std::strlen(ord.FIO.c_str())+1);
return os;
}

// stream an Order ... to std::cout
std::ostream& operator<<(std::ostream& os, const Order& ord) {
os << "{" << ord.productamount << "," << ord.product << "," << ord.cost
<< "," << ord.orderID << "," << ord.FIO << "}";
return os;
}
//-----------------------------------------------------------------------------
class OrderBox { // to keep all your Order objects
OrderVec m_orders;
public:
// default ctor
OrderBox() : m_orders() {}

// ctor to read from a file
OrderBox(const std::string file) :
m_orders()
{
if(!readbinfile(file))
throw std::runtime_error("error reading file");
}

// ctor to populate from an initializer_list {...}
OrderBox(std::initializer_list<Order> il) :
m_orders(il)
{}

bool createbinfile(const std::string& filename)
{
std::ofstream f(filename, std::ios::trunc | std::ios::binary);
if(f) f << *this; // use OrderBox's ofstream operator
return f.good();
}

bool readbinfile(const std::string& filename)
{
std::ifstream f(filename, std::ios::binary);
if(f) f >> *this; // use OrderBox's ifstream operator
return f.good();
}

// the OrderBox's stream operators
friend std::ifstream& operator>>(std::ifstream&, OrderBox&);
friend std::ofstream& operator<<(std::ofstream&, const OrderBox&);
friend std::ostream& operator<<(std::ostream&, const OrderBox&);
};
//-----------------------------------------------------------------------------
std::ifstream& operator>>(std::ifstream& is, OrderBox& ob) {
OrderVec result;
Order tmpord;
size_t reqlen;

is.read(reinterpret_cast<char*>(&reqlen), sizeof(reqlen));
result.reserve(reqlen);

while(is>>tmpord) // use the ifstream operator of Order
{
result.emplace_back(std::move(tmpord));
if(result.size()==reqlen) break; // all records read
}
if(result.size()!=reqlen) is.setstate(std::ios_base::failbit);
else std::swap(result, ob.m_orders);
return is;
}

std::ofstream& operator<<(std::ofstream& os, const OrderBox& ob) {
size_t reqlen = ob.m_orders.size();
os.write(reinterpret_cast<const char*>(&reqlen), sizeof(reqlen));
for(const auto& ord : ob.m_orders)
{
os << ord; // use the ofstream operator of Order
}
return os;
}

std::ostream& operator<<(std::ostream& os, const OrderBox& ob) {
os << "{\n";
for(const auto& ord : ob.m_orders) {
std::cout << " " << ord << "\n"; // print one order
}
os << "}\n";
return os;
}
//-----------------------------------------------------------------------------
int main() {
OrderBox ob = { // OrderBox with orders to write to file
{10, OOPlabs, 0.1, 1, "Hello One"},
{20, OOPlabs, 0.2, 2, "Hello Two"},
{30, OOPlabs, 0.3, 3, "Hello Three"},
{40, OOPlabs, 0.4, 4, "Hello Four"},
{50, OOPlabs, 0.5, 5, "Hello Five"}
};

try {
if(ob.createbinfile("orders.db")) {
// a new OrderBox to populate directly from the file
OrderBox newbox("orders.db");
// stream OrderBox
std::cout << newbox;
}
} catch(const std::exception& ex) {
std::clog << "Exception: " << ex.what() << "\n";
}
}

如果一切正常,输出:

{
{10,0,0.1,1,Hello One}
{20,0,0.2,2,Hello Two}
{30,0,0.3,3,Hello Three}
{40,0,0.4,4,Hello Four}
{50,0,0.5,5,Hello Five}
}

关于c++ - 关闭程序后如何从二进制文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53619737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com