2013-03-27 157 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(); 
}