您可以使用指针指向 fstream 文件吗?

Can you use pointers to point to an fstream file?

我正在制作一个名为 docList 的链表,以分配一个唯一标记和一个指向 ifstream 文件的指针,但它似乎不起作用,除非文件本身是一个指针。

我正在将一个更大的文件解析为单独的文件以添加到 docList 中,实现也可能是造成这种情况的原因。

class docList {
public:
    int docNumber;
    ofstream*file;
    docList* bottom;

    docList();
    void addDocument( ofstream);
};

还有更多,但我认为这是所有相关代码。我也想向评论家学习

int parseFile() // takes a file and splits into multiple files by paragraphs
{
bool open = true;
int fileNumber = 1;

string fileName;
string fileLine;
ifstream myFile;

cout << "Name of file: ";
cin >> fileName;

myFile.open(fileName);

if( !myFile.is_open() ) // Checks if file is found
{
    cout << "File not found" << endl;
    open = false;
}
else    // File is available 
{
    ofstream fout;

    while( !myFile.eof() )
    {
        getline( myFile, fileLine );    // Get single line from main file

        stringstream sstream;
        string fileIndex;
        string outputFiles;

        sstream <<fileNumber;   // creating index for new files
        sstream >> fileIndex;
        outputFiles = "file" + fileIndex + ".txt";  

        fout.open(outputFiles); // writing to new files

        L1:
        {
            fout << fileLine << '\n';   // Writes paragraph of main file into seperate files
            getline( myFile, fileLine );
            if( myFile.eof() ) goto L2;
        }
        if( fileLine!= "" ) goto L1;

        L2:
            fout << fileLine;

        fileNumber++;

        doc.addDocument( fout );
        fout.close();
    }
}
myFile.close();
return fileNumber;
}
class docList {
public:
    .....
    ofstream* file;
    void addDocument(ofstream);
};

所有 C++ 流对象都是不可复制的,而全局对象如 std::cout, std::cerr, etc 是不可移动的。因此,传递它们的通常方法是通过引用 &。但是由于引用只能在声明点绑定,而你稍后绑定 stream,你只能使用指针或 reference_wrapper


另请注意,析构函数将关闭文件并释放资源.. 所以这样做会崩溃:

class docList {
public:
    .....
    ofstream* file;
    void addDocument(ofstream& of);
};

int parseFile(docList& doc){
    ....
    ofstream file;
    ....
    doc.addDocument(file);


}  //< --`file` will be closed and doc will now hold an invalid reference!

那闻起来像你的代码...

int parseFile()
{
    ......
    ofstream fout;

//    while( !myFile.eof() )   /// Bad idea! and also, your code can look better without using labels
    while( getline( myFile, fileLine ) )   //better
    {
        .....
        fout.open(outputFiles);
        ......
        doc.addDocument( fout );
        fout.close();
    }
....
}

使用智能指针可能看起来不错,但通常不好持有资源超过必要的时间