gpt4 book ai didi

c++ - 使用打开的文件流创建类

转载 作者:行者123 更新时间:2023-11-28 03:04:56 25 4
gpt4 key购买 nike

我创建了一个应该读取 DNA 序列的类:它包含一个 if 流私有(private)成员:

接口(interface):

class Sequence_stream {
const char* FileName;
std::ifstream FileStream;
std::string FileFormat;

public:
Sequence_stream(const char* Filename, std::string Format);
NucleotideSequence get();
};

实现:

Sequence_stream::Sequence_stream(const char* Filename, std::string Format)
{
FileName = Filename;
FileStream.open(FileName);
FileFormat = Format;
std::cout << "Filestream is open: " << FileStream.is_open() << std::endl;
}

NucleotideSequence Sequence_stream::get()
{
if (FileStream.is_open())
{
char currentchar;
int basepos = 0;
std::string name;
std::vector<Nucleotide> sequence;
currentchar = FileStream.get();
if (currentchar == '>' && false == FileStream.eof()) { // Check that the start of the first line is the fasta head character.
currentchar = FileStream.get(); // Proceed to get the full name of the sequence. Get characters until the newline character.
while(currentchar != '\n' && false == FileStream.eof())
{
if (true == FileStream.eof()) {
std::cout << "The file ends before we have even finished reading in the name. Returning an empty NucleotideSequence" << std::endl;
return NucleotideSequence();
}
name.append(1, currentchar);
currentchar = FileStream.get();
} // done getting names, now let's get the sequence.
currentchar = FileStream.get();
while(currentchar != '>' && false == FileStream.eof())
{
if(currentchar != '\n'){
basepos++;
sequence.push_back(Nucleotide(currentchar, basepos));
}
currentchar = FileStream.get();
}
if(currentchar == '>')
{
FileStream.unget();
}
return NucleotideSequence(name, sequence);
} else {
std::cout << "The first line of the file was not a fasta format description line beginning with '>'. Are you sure the file is of FASTA format?" << std::endl;
return NucleotideSequence();
}

} else {
std::cout << "The filestream is not open..." << std::endl;
return NucleotideSequence();
}
}

但是如果我测试它:

int main()
{
std::cout << "Let's try and read in a sequence!" << std::endl;
std::cout << "First we'll create a stream!" << std::endl;
Sequence_stream MyDNAStream("~/Dropbox/1_20dd5.fasta", "fasta");
std::cout << "Done!" << std::endl;
std::cout << "Now let's try and get a sequence!" << endl;
NucleotideSequence firstsequence = MyDNAStream.get();
return 0;
}

我看到 if 流没有打开:

Let's try and read in a sequence!
First we'll create a stream!
Filestream is open: 0
Done!
The filestream is not open...
logout

[Process completed]

虽然我认为构造函数打开了 if 流。我需要做什么来纠正这个问题,以便创建对象并包含一个开放流? (我知道我还没有包含一个析构函数,它将在对象被破坏时关闭流)。

谢谢,本。

最佳答案

您的示例表明 is_open 返回了 false。我认为您应该在构造函数中检查该文件确实已打开,如果没有则抛出。

在您的情况下,我怀疑这是由于将“~/Dropbox/1_20dd5.fasta”作为输入参数传递所致。您是否使用完整路径名进行了测试,没有〜?我不知道处理真实路径扩展的 C++ 库(如 python 的 os.path)。

关于c++ - 使用打开的文件流创建类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com