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:
- 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; }
- 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
Post a Comment