2011-10-14 53 views
-1

嗨,我试图用一个fstream的文件句柄做以下几点:fstream的只是不会创建文件

  • 写入读取文件
  • 创建文件(如果不存在)
  • 到文件

    问题: 出于某种原因,我无法使它创建文件。

    filepath= name + "/mails.txt"; 
    mkdir(name.c_str(),0600); 
    log.open(filepath.c_str(), ios::in|ios::out|ios::ate); 
    if(!log.is_open())cout<<"error"<<endl; 
    log<<flush; 
    

    如果文件存在它的工作,但是当文件不存在它不会。

    编辑:因为我不好未能邮政在注释中的代码我在这里尝试:d

    user::user(string aaa) 
    { 
    string filepath; 
    name=aaa; 
    filepath= name + "/mails.txt"; 
    mkdir(name.c_str(),0666); 
    
    
    //toch("mails.txt",0600); 
    log.open(name.c_str(), ios::in|ios::out|ios::ate); 
    if(!log.is_open()){ 
        log.close(); 
        log.open(name.c_str(), ios::in|ios::out|ios::trunc); 
    } 
    if(!log.is_open())cout<<"error"<<endl; 
    log<<flush; 
    cout<<"message written"<<endl; 
    } 
    

    如果有一个系统commant喜欢的mkdir用于创建.TXT它会帮助过我想

  • 回答

    2

    使用ios::in时,Fstream无法创建文件。它只能打开现有的文件。
    你应该怎么做,首先,检查它是否打开一个文件。如果没有,关闭它,清除它的状态,并用ios::out打开 - 这将创建该文件。

    编辑:

    如果指定ios::trunc您可以使用ios::in文件。但是,如果文件存在,那么您将删除其所有内容。

    +0

    试过:不工作! – asdf

    +0

    你究竟做了什么?你能粘贴你的代码吗? –

    +0

    user :: user(string aaa) { string filepath; name = aaa; filepath = name +“/mails.txt”; mkdir(name.c_str(),0666); //toch("mails.txt",0600); log.open(name.c_str(),ios :: in | ios :: out | ios :: ate);如果(!log.is_open()){ log.close(); log.open(name.c_str(),ios :: in | ios :: out | ios :: trunc); } if(!log.is_open())cout <<“error”<< endl; log << flush; cout <<“message written”<< endl; } – asdf