【问题标题】:This following code is file read/write in a single file. but this code is not able to create file以下代码是单个文件中的文件读/写。但此代码无法创建文件
【发布时间】:2023-03-23 13:28:01
【问题描述】:

我正在编写一个程序,该程序可以读取和写入学生使用课程的记录。该程序不打开文件。所以我无法从文件中读取数据。

class Student
{
   private:
      unsigned roll ;
      char name[30];
      float perc;

   public:
      void getvalue()
      {
         cout<<"enter rollno , name and percentage :\n";
         cin>>roll;
         cin.ignore(); 
         cin>>name>>perc;
      }

      void  display()
      {
         cout << "\nRoll No : " << roll << "\nName : " << name
            << endl << "percentage : " << perc << endl;
      }
};

int main()
{
   char choice;
   Student st ;
   fstream file1;

   file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out );
   do
   {
      cout<<"\n Detail of student  :\n";
      st.getvalue();

      file1.write((char*)(&st) , sizeof(st));

      cout<<"\nwant to input more record(y/n) : ";

      cin>>choice;

   } while(tolower(choice) == 'y');

   file1.seekg(0,ios::beg);

   while(file1.read((char*)(&st) , sizeof(st))   )
   {
      cout<<"1";
      st.display();
   }

   file1.close();

   getch();
}

【问题讨论】:

  • 请在任何其他文件操作之前检查您的文件是否已成功打开

标签: c++ file-handling


【解决方案1】:

当您在模式设置为ios::out|ios::in 的情况下调用fstream::open() 时,只有当文件存在时才能打开文件。如果文件不存在,fstream::open() 将失败。请参阅http://en.cppreference.com/w/cpp/io/basic_fstream/open 和相关的http://en.cppreference.com/w/cpp/io/basic_filebuf/open

改变

file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out );

file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out);
if ( !file1.is_open() )
{
   file1.clear();
   file1.open("stud_rec1.bin", ios::out); //Create file.
   file1.close();
   file1.open("stud_rec1.bin", ios::binary|ios::in|ios::out);

   // If the file still cannot be opened, there may be permission
   // issues on disk.
   if ( !file1.is_open() )
   {
      std::cerr << "Unable to open file " << "stud_rec1.bin" << std::endl;
      exit(1);
   } 
}

【讨论】:

  • 感谢您的快速回复。我真的很感谢你的举动。
猜你喜欢
  • 2020-08-25
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多