2017-03-01 111 views
-1

嗨,我正在處理兩個txt文件。在第一個,我用fstream打開文件,但是當我試圖用fstream打開第二個文件不起作用時,但是如果我嘗試使用ofstream作品打開它。任何線索是怎麼回事?下面是功能。由於Fstream doens't打開一個文件,ofstream是

void stack::read() 
{ 
    string name = "file.txt", line; 
    fstream file; 
    file.open(name.c_str());//open the file 
    char cc; 

    if (!file) 
    { 
     cout << "Error could not open the file" << endl; 
     return; 
    } 
    else 
    { 
     //file was opened succesful 
     while (file) 
     { 
      file.get(cc);//get each character of the string 
      push(cc);//insert the character into the stack 

     } 
    } 
    file.close();//close the file 
} 

void stack::write() 
{ 
    item *r = stackPtr;//point to the top element of the stack 
    ofstream file; 
    string name = "f.txt"; 
    file.open(name.c_str()); 

    if (!file) 
    { 
     cout << "Could not open the file" << endl; 
     return; 

    } 
    else 
    { 
     while (r != NULL)//while r has data write to the file 
     { 
      file << r->character; //write to the file 
      r = r->prev;//move to the prev element in the stack 
     } 
    } 
    file.close(); 
} 
+3

它存在嗎? – SingerOfTheFall

+0

'ofstream'並不打算打開一個文件,而是創建一個新的文件,然後打開。 –

+0

始終使用適當的流類型來避免問題。所以當只讀時,只使用'std :: ifstream',只寫時使用'std :: ofstream'。 – zett42

回答

6

如果文件不存在,它可以與ofstream打開(它會創建同名的新文件)。但fstream.open()沒有第二個參數假定讀取模式,如果該文件不存在,它將不會被打開。

你確定你沒有拼錯文件名嗎?

相關問題