-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();
}
存在しますか? – SingerOfTheFall
'ofstream'はファイルを開くのではなく、後で開く新しいファイルを作成するためのものです。 –
問題を避けるために、常に適切なストリームタイプを使用してください。読み込み時のみ 'std :: ifstream'を使い、書き込むときは' std :: ofstream'を使います。 – zett42