[英]Reading/Writing several structs of unknown size to file C++
I am wanting to make a book database to record what books I have read. 我想建立一个图书数据库来记录我读过的书。 So far, I have a structure for a book entry. 到目前为止,我已经有了一个书的结构。
struct Entry
{
string title;
string author;
int pages;
};
As you can see, the title and the author variables are of undetermined size. 如您所见,标题和作者变量的大小不确定。 I would like to store several structures within one file, and then to read all those structures when I want to display the database. 我想将多个结构存储在一个文件中,然后在想要显示数据库时读取所有这些结构。
How would I read/write several of these structures from a file? 如何从文件中读取/写入这些结构中的几个? Would I have to have predetermined sizes? 我需要预定大小吗? Please provide an example. 请提供一个例子。
you could easily store it in a CSV-format the following way: 您可以通过以下方式轻松将其存储为CSV格式:
title_1,author_1,pages_1,title_2,author_2,pages_2,title_3,auth...
when reading back the file, then parse the file according to your separators and you have back your data. 读回文件时,然后根据分隔符解析文件,就可以恢复数据了。
edit : as @Mark Setchell suggested you shouldn't use ' ,
' as a separator, because a comma might also be part of the title itself. 编辑 :正如@Mark Setchell所建议的那样,您不应使用' ,
'作为分隔符,因为逗号本身也可能是标题的一部分。 instead you should use a more rare character as separator, which isn't used very often in possible book titles. 相反,您应该使用更罕见的字符作为分隔符,这种分隔符在可能的书名中很少使用。 some examples are ' ;
一些例子是' ;
' ' |
'' |
' or ' #
' or even unprintable characters '或' #
'甚至是无法打印的字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.