Unable to write an object to a file in C++ -


after running savetofile() file isempty. won't print anything. also, when use while(file.eof() == 0) instead of while(file.read(...)) in displayfromfile() loops forever.

using namespace std;  void database::savetofile() {   fstream file;   file.open("abc", ios::ate);   (int = 0; < count - 1; i++)   {     file.write((char *) &s[i], sizeof s[i]);   }   file.close(); }  void database::displayfromfile() {   student stud;   fstream file;   file.open("abc", ios::in);   file.seekg(0, ios::beg);   cout << "rollno\t|\tmarks " << endl;   cout << "------------------------------------" << endl;   while (file.read((char *) &stud, sizeof stud))   {     cout << stud.getrollno() << "\t|\t" << stud.getmarks() << endl;   }   file.close(); } 

here how using streams:

  1. writing file:

int main () { std::fstream fs; fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app); fs << " more lorem ipsum"; fs.close(); return 0; }

  1. reading file:

int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); } else cout << "unable open file"; return 0; }


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -