2014-02-06 124 views
1

代碼:」文件無法打開。「 C++的fstream

int question_3() 
{ 
    fstream hardware("hardware.dat" , ios::binary | ios::in | ios::out); 

    if (!hardware) 
    { 
     cerr << "File could not be opened." << endl; 
     exit(1); 
    } 

    HardwareData myHardwareData; 

    for (int counter = 1; counter <= 100; counter++) 
    { 
     hardware.write(reinterpret_cast< const char * >(&myHardwareData), sizeof(HardwareData)); 
    } 

    cout << "Successfully create 100 blank objects and write them into the file." << endl; 
. 
. 
. 

結果:

enter image description here

爲什麼該文件無法打開?

如果文件「hardware.dat」不存在,程序將創建具有該名稱的文件。爲什麼不?

如果我第一次創建如下文件,程序將繼續。

![在這裏輸入的形象描述] [2]


感謝您的關注。


最終解決方案:

int question_3() 
{ 
    cout << "Question 2" << endl; 

    fstream hardware;           <---Changed 
    hardware.open("hardware.dat" , ios::binary | ios::out); <---Changed 

    if (!hardware) 
    { 
     cerr << "File could not be opened." << endl; 
     exit(1); 
    } 

    HardwareData myHardwareData; 

    for (int counter = 1; counter <= 100; counter++) 
    { 
     hardware.write(reinterpret_cast< const char * >(&myHardwareData), sizeof(HardwareData)); 
    } 

    cout << "Successfully create 100 blank objects and write them into the file." << endl; 

    hardware.close();             <---Changed 
    hardware.open("hardware.dat" , ios::binary | ios::out | ios::in); <---Changed 
. 
. 
. 

enter image description here

+0

那麼如何獲得許可?我不確定程序是否應該正常創建文件「hardware.dat」以便繼續。 – Casper

回答

3

爲什麼用ios::inios::out標誌打開文件(看起來你只是寫這個文件)? ios::in將要求現有的文件:

#include <fstream> 
#include <iostream> 
using namespace std; 
int main() 
{ 
    fstream f1("test1.out", ios::binary | ios::in | ios::out); 
    if(!f1) 
    { 
     cout << "test1 failed\n"; 
    } 
    else 
    { 
     cout << "test1 succeded\n"; 
    } 


    fstream f2("test2.out", ios::binary | ios::out); 
    if(!f2) 
    { 
     cout << "test 2 failed\n"; 
    } 
    else 
    { 
     cout << "test2 succeded\n"; 
    } 
} 

輸出:

[email protected] ~/Desktop/test $ ./a.out 
test1 failed 
test2 succeded 

也許你想使用ios::app

+0

OIC ...因爲我必須在即將到來的步驟中閱讀,所以我寫了ios :: in和ios :: out。你的意思是我必須在下面一行中輸入fstream硬件(「hardware.dat」,ios :: in | ios :: binary)。它更適合? Thx – Casper

+0

如果我輸入「fstream hardware(」hardware.dat「,ios :: binary | ios :: out | ios :: in);」在下面的行中,它會導致構建失敗。然後,我嘗試通過在上一行添加「刪除硬件」來解決此問題,但它不起作用。我能做什麼? Thx – Casper

+0

@CasperLi關閉文件,然後再次打開它。 – molbdnilo

1

如果同時指定了ios::inios::out,該文件必須存在 - 它不會被創建。

如果你只是寫作,只能使用ios::out

1

ios::in指定要打開現有文件進行閱讀。既然你不想縫上任何東西,只要堅持ios::out這將創建該文件,如果它不存在,並打開它寫入。