Fstream不打开文件,ofstream确实

-1 c++ fstream ofstream

嗨我正在使用两个txt文件.在第一个,我用fstream打开文件,但是当我试图用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();
}
Run Code Online (Sandbox Code Playgroud)

Aja*_*iya 6

如果该文件不存在,则可以打开它ofstream(它将使用该名称创建一个新文件).但是fstream.open()没有第二个参数假定读取模式,如果文件不存在,则不会打开它.

你确定你没有拼错文件名吗?