【问题标题】:Unable to write an object to a file in C++无法将对象写入 C++ 中的文件
【发布时间】:2015-08-18 01:12:39
【问题描述】:

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

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();
}

【问题讨论】:

  • 除非你只有普通数据类型,否则你会在读写数据时遇到麻烦(即std::stringstd::vector 将是一个问题)。
  • 你建议我怎么做?
  • for(int i=0;i&lt;count-1;i++) 应该是for(int i=0;i&lt;count;i++)
  • 嘿,成功了!谢谢!

标签: c++ file io


【解决方案1】:

这里是如何使用流来做到这一点:

  1. 写入文件:

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. 从文件中读取:

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; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 2012-07-28
    • 2011-01-11
    • 2023-03-06
    • 1970-01-01
    • 2011-01-23
    • 2016-10-07
    • 2015-05-15
    相关资源
    最近更新 更多