2010-05-24 165 views
7

是否有可能在一個文件上打開一個fstream,這個文件不存在於ios :: in & ios :: out中而不會出現錯誤?fstream進出不存在的文件

+5

不要忘了接受答案,或讓他們知道您是否嘗試過他們的解決方案(或填寫更多詳細信息以便他們可以定製他們的答案)來幫助答覆者。 – 2010-05-26 23:40:08

回答

0
#include <iostream> 
#include <fstream> 
using namespace std; 

int main() { 
    fstream f("test.txt", fstream::in | fstream::out); 
    cout << f.fail() << endl; 
    f << "hello" << endl; 
    f.close();  
    return 0; 
} 

這段代碼打印1並不會創造「的test.txt」的文件,如果不退出。所以不可能在沒有出錯的文件上打開和fstream。

+0

Did you mean「filestr.fail( )「和」filestr <<「hello」<< endl;「?! – Secko 2010-05-24 11:02:00

+0

@Secko是的,謝謝。 – 2010-05-24 11:51:07

2
#include <fstream> 

ofstream out("test", ios::out); 
if(!out) 
{ 
    cout << "Error opening file.\n"; 
    return 1; 
} 

ifstream in("test", ios::in); 
if(!in) 
{ 
    cout << "Error opening file.\n"; 
    return 1; 
} 

如果發生錯誤,則顯示消息並返回一(1)。但是,編譯並執行ofstream out("test", ios::out);ifstream in("test", ios::in);是沒有任何錯誤的。無論哪種方式,文件測試創建。

8

更新: 要在文件打開fstream不用於輸入和輸出(隨機存取)沒有得到一個錯誤的存在,你應該提供在open(或構造函數)調用fstream::in | fstream::out | fstream::trunc。由於該文件不存在,因此在零字節處截斷文件不是戲劇性的。打開指定唯一ios::in時,因爲你永遠無法從流中讀取數據,所以最好提前失敗是不存在的文件時

希望有一個錯誤。

+1

那麼,爲什麼不打開一個通過類fstream的對象不存在的文件會拋出錯誤呢?例如:fstream myfile; myfile.open(「this_file_doesn't_exist.txt」); //這不會引發任何錯誤。 – Ketcomp 2015-07-17 15:27:49

0
std::fstream f("test.txt", std::ios_base::out); 
f.close(); //file now exists always 
f.open("test.txt", fstream::in | std::ios_base::out); 
//f is open for read and write without error 

我還沒有檢查,以保證它會打開沒有錯誤,但我覺得它應該很有信心。