C++ 您可以使用指针指向fstream文件吗?
我正在制作一个名为docList的链接列表,为ifstream文件分配一个唯一的标记和一个指针,但除非文件本身是指针,否则它似乎不起作用 我正在将一个大得多的文件解析为单独的文件以添加到docList中,实现可能也会导致这种情况C++ 您可以使用指针指向fstream文件吗?,c++,parsing,linked-list,fstream,C++,Parsing,Linked List,Fstream,我正在制作一个名为docList的链接列表,为ifstream文件分配一个唯一的标记和一个指针,但除非文件本身是指针,否则它似乎不起作用 我正在将一个大得多的文件解析为单独的文件以添加到docList中,实现可能也会导致这种情况 class docList { public: int docNumber; ofstream*file; docList* bottom; docList(); void addDocument( ofstream); };
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;
}
int parseFile()//获取一个文件并按段落拆分为多个文件
{
bool open=true;
int fileNumber=1;
字符串文件名;
字符串文件行;
ifstreammyfile;
cout>文件名;
myFile.open(文件名);
if(!myFile.is_open())//检查是否找到文件
{
库特
<所有的C++流对象都是不可复制的,全局的代码如<代码> STD::CUD:STD::CURR等> /CUT>,不可移动。因此,通常的方式是通过引用<代码>和代码>来传递。但是由于引用只能在声明点上被绑定,并且在以后绑定<代码>流<代码>时,只能使用指针或areference\u 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!
使用智能指针可能看起来不错,但通常情况下,将资源占用的时间过长并不好在我看来,这个问题缺少了一些关键的东西:一个实际的问题。标题中有一个问题,但这里有很多代码似乎与之无关。
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();
}
....
}