#include<fstream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char ch;
class book
{
char *title;
char *author;
double price;
int quantity;
public:
book()
{
title=NULL;
author=NULL;
price=0.00;
quantity=0;
}
void create(char *a, char *b, double x, int q)
{
title=new char;
author=new char;
strcpy(title, a);
strcpy(author, b);
price=x;
quantity=q;
}
void display()
{
cout<<"\n"<<title<<"\t"<<author<<"\t"<<price<<"\t"<<quantity;
}
};
book obj, obj2;
fstream stock;
void displaystock();
void addbook()
{
cout << "\033[2J\033[1;1H";
int n, i,q, j;
stock.open("stock.txt", ios::app|ios::out|ios::binary);
cout<<"\n\nHow many unique book titles would you like to add?";
cin>>n;
char *a, *b;
double x=0;
a=new char;
b= new char;
for(i=0;i<n;i++)
{
while ((ch = getchar()) != '\n' && ch != EOF);
cout<<stock.tellg();
cout<<"\n\nEnter book title: ";
gets(a);
cout<<"\n\nEnter author: ";
gets(b);
cout<<"\n\nEnter price: ";
cin>>x;
cout<<"\n\nEnter quantity: ";
cin>>q;
obj.create(a,b,x, q);
stock.write((char*)&obj,sizeof(obj));
}
stock.close();
}
void displaystock()
{
cout << "\033[2J\033[1;1H";
stock.open("stock.txt", ios::in|ios::binary);
cout<<stock.tellg();
while(stock.read((char*)&obj2, sizeof(obj2)))
{
cout<<"\n"<<stock.tellg();
//if(!stock.eof())
{
obj2.display();
}
//else
//break;
}
stock.close();
}
int main()
{
addbook();
displaystock();
return 0;
}
这是一个尝试使用类的对象写入和读取二进制文件的代码。当文件不存在(第一次运行)时,它可以工作。但是,只要将某些内容附加到现有文件,就会在读取时出现分段错误(在 displaystock 函数中)。