-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();
}
它存在嗎? – SingerOfTheFall
'ofstream'並不打算打開一個文件,而是創建一個新的文件,然後打開。 –
始終使用適當的流類型來避免問題。所以當只讀時,只使用'std :: ifstream',只寫時使用'std :: ofstream'。 – zett42