2016-09-05 30 views
15

我得到了fstreamoftream之間的不同行爲,我無法解釋。爲什麼不把std :: fstream寫入文件?

當我使用fstream什麼也沒有發生,即沒有文件被創建

int main() 
{ 
    std::fstream file("myfile.txt"); 
    file << "some text" << std::endl; 
    return 0; 
} 

,但是當我改變fstreamoftream,它的工作原理。

爲什麼?

fstream CTOR的第二個參數是ios_base::openmode mode = ios_base::in | ios_base::out這使我認爲該文件是以讀寫模式打開的,對吧?

+3

這應該工作。緩衝?我認爲我們需要一個完整的[mcve]。 –

+1

我只有這個代碼的功能,它不起作用。我沒有什麼可寫的了。 MVS2015。 – Narek

+0

也許您在寫入文件時檢查得太早,例如「close()」僅在銷燬fstream時才被調用 – CppChris

回答

27

ios_base::in requires the file to exist

如果您只提供ios_base::out,那麼只有當文件不存在時纔會創建該文件。

+--------------------+-------------------------------+-------------------------------+ 
| openmode   | Action if file already exists | Action if file does not exist | 
+--------------------+-------------------------------+-------------------------------+ 
| in     | Read from start    | Failure to open    | 
+--------------------+-------------------------------+-------------------------------+ 
| out, out|trunc  | Destroy contents    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| app, out|app  | Append to file    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in    | Read from start    | Error       | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in|trunc  | Destroy contents    | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 
| out|in|app, in|app | Write to end     | Create new     | 
+--------------------+-------------------------------+-------------------------------+ 

PS:

一些基本的錯誤處理也被證明用於理解這是怎麼回事:

#include <iostream> 
#include <fstream> 

int main() 
{ 
    std::fstream file("triangle.txt"); 
    if (!file) { 
    std::cerr << "file open failed: " << std::strerror(errno) << "\n"; 
    return 1; 
    } 
    file << "Some text " << std::endl; 
} 

輸出:

C:\temp> mytest.exe 
file open failed: No such file or directory 

C:\temp>