Updating the end of the file in c++ fstream -
i wrote code:
#include <fstream> #include <iostream> using namespace std; struct man { int id; char name[20]; }; void add(); void update(); void print(); int main() { int n; cout << "1-add, 2-update, 3-print, 5-exit" << endl; cin >> n; while (n != 5) { switch (n) { case 1: add(); break; case 2: update(); break; case 3: print(); break; } cout << "1-add, 2-update, 3-print, 5-exit" << endl; cin >> n; } return 0; } void add() { fstream file; file.open("data.dat", ios::in | ios::out | ios::binary); if (file.is_open()) { int id; man man; bool didfound = false; cout << "id : "; cin >> id; file.read((char*)&man, sizeof(man)); while (!file.eof() && !didfound) { if (man.id == id) { cout << "already exist" << endl; didfound = true; } file.read((char*)&man, sizeof(man)); } if (!didfound) { man.id = id; cout << "name: "; cin >> man.name; file.clear(); file.seekp(0, ios::end); file.write((char*)&man, sizeof(man)); } } } void update() { fstream file; file.open("data.dat", ios::in | ios::out | ios::binary); if (file.is_open()) { int id; man man; bool didfound = false; cout << "id : "; cin >> id; file.read((char*)&man, sizeof(man)); while (!file.eof() && !didfound) { if (man.id == id) { cout << "name: "; cin >> man.name; file.seekp((int)file.tellg() - sizeof(man), ios::beg); file.write((char*)&man, sizeof(man)); didfound = true; } file.read((char*)&man, sizeof(man)); } file.close(); if (!didfound) { cout << "cant update none existing man" << endl; } } } void print() { fstream file; file.open("data.dat", ios::in | ios::binary); if (file.is_open()) { int id; man man; bool didfound = false; cout << "id\tname" << endl; file.read((char*)&man, sizeof(man)); while (!file.eof()) { cout << man.id << '\t' << man.name << endl; file.read((char*)&man, sizeof(man)); } file.close(); } }
but have problem in update function: when update last man in file, when reach file.read file writes value of last man(in file before writting) end of file (after updated man)
i added after file.write , seems solve it:
file.seekg(file.tellp(), ios::beg);
can explain why?
(yes can solved else)
somewhat arbitrarily, required perform seek
in between read
, write
. it's not spelled out in standard, c++ standard mentions c++ fstream
has same properties c stdio
streams respect validity of stream operations, , c standard mentions positioning command required between reading , writing (or vice versa).
some platforms relax requirement. gcc after version 4.5 or 4.6, modified basic_filebuf
eliminate byzantine rule.
by way, file.seekg( 0, ios::cur )
safer.
Comments
Post a Comment