是否有可能在一個文件上打開一個fstream,這個文件不存在於ios :: in & ios :: out中而不會出現錯誤?fstream進出不存在的文件
回答
#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。
Did you mean「filestr.fail( )「和」filestr <<「hello」<< endl;「?! – Secko 2010-05-24 11:02:00
@Secko是的,謝謝。 – 2010-05-24 11:51:07
#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);
是沒有任何錯誤的。無論哪種方式,文件測試創建。
更新: 要在文件打開fstream
不用於輸入和輸出(隨機存取)沒有得到一個錯誤的存在,你應該提供在open
(或構造函數)調用fstream::in | fstream::out | fstream::trunc
。由於該文件不存在,因此在零字節處截斷文件不是戲劇性的。打開指定唯一ios::in
時,因爲你永遠無法從流中讀取數據,所以最好提前失敗是不存在的文件時
您會希望有一個錯誤。
那麼,爲什麼不打開一個通過類fstream的對象不存在的文件會拋出錯誤呢?例如:fstream myfile; myfile.open(「this_file_doesn't_exist.txt」); //這不會引發任何錯誤。 – Ketcomp 2015-07-17 15:27:49
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
我還沒有檢查,以保證它會打開沒有錯誤,但我覺得它應該很有信心。
- 1. 不能寫入fstream文件
- 2. fstream不會創建文件
- 3. std :: fstream不會打開當前進程的文件,但open()會?
- 4. 正在重寫fstream文件
- 5. fstream的將不打印到文件
- 6. fstream的替換文件
- 7. 數據沒有被保存在文本文件中(C++ Fstream庫)
- 8. std :: fstream :: tellg()不正確地輸出文件遊標指針?
- 9. 不存在的文件不斷出現
- 10. DirectX Windows 8.1 fstream不會加載文件
- 11. fstream文件無法讀取
- 12. std :: fstream文件大於2GB
- 13. FStream讀取txt文件
- 14. C++ fstream多輸入文件
- 15. 文件流與<fstream>
- 16. 使用fstream從C++的* .txt文件讀取數字使用fstream
- 17. 加載二進制文件使用fstream的
- 18. 用fstream和seekp替換二進制文件中的數據
- 19. PHP列出不存在的文件
- 20. fstream:無法在文件中間寫入
- 21. std :: fstream在Windows上讀取文件C++
- 22. 定製文件類中的fstream對象的生存期
- 23. 退出後Fstream輸出
- 24. C++:使用fstream修補二進制文件
- 25. fstream的在出代碼::塊錯誤
- 26. 檢索文件描述符:: fstream的
- 27. 打開與fstream的,但文件名字符的文本文件不是ASCII
- 28. fstream |讀寫操作既不好也不壞|讀寫大文件
- 29. 使用fstream將文件數據從當前位置保存到文件結尾
- 30. 不fstream支持文件的動態創建
不要忘了接受答案,或讓他們知道您是否嘗試過他們的解決方案(或填寫更多詳細信息以便他們可以定製他們的答案)來幫助答覆者。 – 2010-05-26 23:40:08