Fstream doens打开一个文件,ofstream确实

时间:2017-03-01 06:49:25

标签: 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();
}

1 个答案:

答案 0 :(得分:6)

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

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