C++ Random Access Files -
its first time experiment random access files in c++ however, i've tried before in java can't work in c++. idea want create 100 empty records, , store record @ particular record number in file. here code, kept simple possible.
i have here structure named tool:
struct tool { int number; char name[20]; int quantity; double cost; };
and here have in main function:
fstream outfile; outfile.open("inventory.dat"); // create 100 empty tool records tool tool; tool.number = 0; tool.name[0] = '\0'; tool.quantity = 0; tool.cost = 0; (int = 0; < 100; i++) { outfile.write(reinterpret_cast<char *>(&tool.number), sizeof(int)); outfile.write(tool.name, sizeof(char)* 20); outfile.write(reinterpret_cast<char *>(&tool.quantity), sizeof(int)); outfile.write(reinterpret_cast<char *>(&tool.cost), sizeof(double)); } // insert tool record tool t; t.number = 3; t.quantity = 7; t.cost = 57; strcpy(tool.name, "electric sander"); outfile.seekp((tool.number - 1) * sizeof(tool)); outfile.write(reinterpret_cast<char *>(&tool.number), sizeof(int)); outfile.write(tool.name, sizeof(char)* 20); outfile.write(reinterpret_cast<char *>(&tool.quantity), sizeof(int)); outfile.write(reinterpret_cast<char *>(&tool.cost), sizeof(double)); outfile.close();
the part initialize 100 empty record works fine (assuming comment insert section of code.
however, when insert section performed, program generates 4 gb of data. i'm not sure what's going on. appreciate kind of help. in advance.
you write entire contents of struct
outfile.seekp(t.number*sizeof(tool)); outfile.write(reinterpret_cast<char *>(&tool),sizeof(tool));
don´t forget tell compiler don´t insert padding
#ifdef msvc #pragma pack(push,1) #endif struct tool { int number; char name[20]; int quantity; double cost; #ifdef gcc }__attribute__((packed)); #else }; #endif #ifdef msvc #pragma pack(pop) #endif
sources:
https://codereview.stackexchange.com/questions/26344/writing-reading-data-structure-to-a-file-using-c
https://stackoverflow.com/a/18654265/194717
comments of our valuable members.
Comments
Post a Comment