2013-03-27 159 views
18

我只是試圖創建一個文本文件,如果它不存在,我似乎無法得到fstream來做到這一點。fstream不會創建文件

#include <fstream> 
using std::fstream; 

int main(int argc, char *argv[]) { 
    fstream file; 
    file.open("test.txt"); 
    file << "test"; 
    file.close(); 
} 

我需要在open()功能,以獲得它來創建文件中指定什麼?我讀過,你不能指定ios::in,因爲它會預期現有的文件存在,但我不確定是否需要爲尚不存在的文件指定其他參數。

+0

我認爲你必須使用:。開( 「test.txt的」,fstream的::中) ; – FacundoGFlores 2013-03-27 19:20:01

回答

14

您應該添加的fstream ::出去開的方法是這樣的:

file.open("test.txt",fstream::out); 

更多關於fstream的標誌的信息,請訪問以下鏈接: http://www.cplusplus.com/reference/fstream/fstream/open/

+1

謝謝你,這個伎倆。 – raphnguyen 2013-03-27 19:23:58

+0

我不允許'file.open(「test.txt」,fstream :: in | fstream :: out | fstream :: binary);'對於還不存在的文件? – raphnguyen 2013-03-27 19:29:42

+4

如果你想讓fstream :: in工作在一個不存在的文件上,你應該添加fstream :: trunc。 – haitaka 2013-03-27 19:41:34

10

您需要添加一些參數。此外,實例和開放可以放在同一行:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc); 
1

這樣做:

#include <fstream> 
#include <iostream> 
using std::fstream; 

int main(int argc, char *argv[]) { 
    fstream file; 
    file.open("test.txt",std::ios::out); 
    file << fflush; 
    file.close(); 
}