2013-01-02 57 views
0

我有這樣的代碼:如何確保cin正確打開文件?

static std :: ifstream s_inF(argv[j]); 
std :: cin.rdbuf(s_inF.rdbuf()); 

我怎樣才能確保它正常打開的文件,有沒有問題?

我的意思是,我想寫出類似:

static std :: ifstream s_inF(argv[j]); 
std :: cin.rdbuf(s_inF.rdbuf()); 
if(.....) 
{ 
    cout << "can not open the file" << endl; 
    return 0; 
} 
... 
..... 
.... 
cin.close(); 

什麼建議嗎?

回答

2

所有對象都是std::basic_ios子類 - 像s_inFstd::cin,你的情況 - 有有operator bool如果流已經準備好I/O操作返回true。

這意味着你可以簡單地直接對其進行測試,例如:

static std::ifstream s_inF(argv[j]); 
std::cin.rdbuf(s_inF.rdbuf()); 
if (!s_inF) 
{ 
    cout << "can not open the file" << endl; 
    return 0; 
} 
// ... 
cin.close();