How can i skip over structures when writing in a binary file [c++] -
i have structure :
struct ticket { bool isreserved; // seat resereved (true) time_t soldon; //when has ticket been bought double price; // price of ticket ticket() { isreserved = 0; price = 0; soldon = 0; } }; i have saved many times needed in binary file , read correctly. question when how can modify 1 structure when user wants buy ticket. example when wants buy 5th seat should go 5th structure , change data. here how try it.
std::cout<<"\nplease enter how many tickets purchase : \n"; { if(number<0 || number > freeseats) std::cerr<<"invalid input.try again: \n"; std::cin>>number; }while(number<0 || number > freeseats); int *t = new int[number]; for(int = 0; i<number; i++) { int seat = 0; { std::cout<<"please enter seat "<<i<<" : "; std::cin>>seat; file.clear(); file.seekg(0,std::ios::beg); for(int =1; <= seat; i++) { serializetickets(file,ticket); } if(ticket.isreserved == 1) std::cout<<"the ticket has been reserved\n"; }while(ticket.isreserved == 1); t[i] = seat; } file.close(); schedule.serializetargetline(choice); std::ofstream myfile(ticketsfilename,std::ios::binary || std::ios::out); for(int = 0; i<number; i++) { time_t timer(0); std::time(&timer); myfile.seekp(+(t[i] - 1)*sizeof(ticket),std::ios::beg); ticket.isreserved=1; ticket.price = atof(schedule.getprice().c_str()); ticket.soldon = timer; myfile.write(reinterpret_cast<char*> (&ticket),sizeof(ticket)); } delete[] t; myfile.close();
if you're compiling gcc, encourage add -wall compiler flags maximum compiler assistance.
the problem appears not opening file writing:
std::ofstream myfile(ticketsfilename,std::ios::binary || std::ios::out); when mean't
std::ios::binary | std::ios::out or (std::ios::binary | std::ios::out)
if turn on full compiler warnings, tell you have boolean operation mean't have logical.
and, yes, should use pragma pack around structure. see http://msdn.microsoft.com/en-us/library/ms253935(v=vs.80).aspx , https://stackoverflow.com/a/9852860/257645
note, unless targetting older compilers, can as:
#pragma pack(push, 1) struct ... { ... }; #pragma pack(pop) (short version: tells compiler use in-memory representation of structure may less run-time performant create less environment-dependent footprint storage this)
Comments
Post a Comment