2017-03-01 15 views
-1

こんにちは私は2つのtxtファイルを扱っています。最初のものでは、私はfstreamでファイルを開きますが、fstreamで2番目のファイルを開こうとしているときに動作しませんが、ofstreamで開くようにしようとすると動作します。何が起こっているのか?以下はその機能です。おかげFstreamはファイルを開きません、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()の2番目のパラメータを指定しないと、読み取りモードが仮定され、ファイルが存在しない場合は開かれません。

本当にファイル名のスペルを間違えていませんか?

関連する問題