-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