2011-10-14 54 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