你能用指针指向一个fstream文件吗?

时间:2016-06-19 18:38:41

标签: c++ parsing linked-list fstream

我正在创建一个名为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;
}

1 个答案:

答案 0 :(得分:0)

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();
    }
....
}

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