下面的代码是在单个文件中读取/写入文件.但是这段代码不能创建文件

This following code is file read/write in a single file. but this code is not able to create file

本文关键字:文件 代码 段代码 创建 不能 单个 读取      更新时间:2023-10-16

我正在写一个程序,读取和写入学生使用类的记录。这个程序不能打开文件。所以我不能从文件中读取数据。

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

调用fstream::open(),模式设置为ios::out|ios::in时,只有文件存在才能打开文件。如果该文件不存在,则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);
   } 
}