2017-10-05 79 views
-3

每當ty進入選項1創建一個文件來存儲我的數據 錯誤就會生成。我無法創建文件並且無法讀取它fstream error無法在C++中創建或打開文件

*//cannot create the file* 
#include <fstream> 
class file 
{ 
private:      
    char data[100]; 
public: 
    void Write(); 
    void Read(); 
}; 
*//this is the write function*  help me 
void file::Write() { 
    *//fin object is created* 
    fstream fin; 
    *//cant open the file* 
    fin.open("rahul.txt", ios::in); 
    if (fin.is_open()) {        help me 
     cout << "Enter data" << endl; 
     cin.ignore(); 
     cin.getline(data, 100); 
     fin.close(); 
    } else 
     cout << "error" << endl;   help me 
} 
*//this is the read function* 

void file::Read() { 
    *//fout object is created* 
    fstream fout; 
    *//cant read the file*     help me 
    fout.open("rahul.txt", ios::out); 
    if (fout.is_open()) { 
     while (!fout.eof()) { 
      fout.getline(data, 100); 
      cout << data;      help me 
     } 
     fout.close(); 
    } else 
     cout << "error" << endl; 
} 

int main() { 
    int choice; 
    file f; 
    while (1) { 
     cout << "Menu" << endl; 
     *//cant enter the file when pressed choice 1* 
     cout << "1.Enter 2.Display 3.exit" << endl; 
     cout << "Enter your choice" << endl; 
     cin>>choice; 
     switch (choice) { 
      case 1: 
       f.Write(); 
       break; 
      case 2: 
       f.Read(); 
       break;     help me 
      case 3: 
       return 0; 
     } 
    } 
    return 0; 
} 
*`//cant enter the file`* 

請有人可以幫我解決這個問題。

+1

究竟是什麼錯誤?這是一個編譯器錯誤?這些「幫助我」是什麼? – user463035818

+4

..btw這是一個奇蹟,爲什麼你考慮一個頁面充滿志願者,花時間幫助別人作爲「自我」 – user463035818

+2

我認爲你混淆了'ios :: out'和'ios :: in',for寫你需要'ios :: out'和閱讀'ios :: in'!?此外,您從不輸出任何數據到文件。 – xander

回答

1

fin.open("rahul.txt", ios::in);中使用的打開模式要求文件已經存在。並且放置在「當前目錄」中,無論如何,因爲您沒有指定路徑。

模式in也只允許你從文件中讀取。

fout.open("rahul.txt", ios::out);中使用的開放模式將創建一個空文件進行寫入(替換任何以前具有相同名稱的文件)。試圖從該文件讀取將失敗兩個的原因 - 該文件始終爲空,並且它僅用於寫入。