无法在C ++中将对象写入文件

时间:2015-06-03 17:18:20

标签: c++ file io

运行SaveToFile()文件后isempty。它不会打印任何东西。此外,当我在while(file.eof() == 0)中使用while(file.read(...))代替DisplayFromFile()时,它会永远循环。

using namespace std;

void database::SaveToFile()
{
  fstream file;
  file.open("abc", ios::ate);
  for (int i = 0; i < 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();
}

1 个答案:

答案 0 :(得分:0)

以下是使用流的方法:

  1. 写入档案:
  2. 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. 从文件中读取:
    2. int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); } else cout << "Unable to open file"; return 0; }