2015-10-06 54 views
2

我正在編寫一個讀取和寫入學生使用類的記錄的程序。這個程序不打開文件。所以我無法從文件中讀取數據。以下代碼是文件讀/寫在單個文件中。但此代碼無法創建文件

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

請經常檢查你文件之前的任何其他文件操作 – TryinHard

回答

0

當你調用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); 
    } 
} 
+0

感謝ü先生您的快速反應成功與否打開。我非常感謝你的姿態。 –