从二进制文件获取输入时发生访问冲突错误



好的,所以我试图从二进制文件读取输入。我已经改变了这段代码一点,但这个版本,我得到一个访问违反错误…所以它试图访问不存在的东西。下面是我的问题区域的源代码:

void HashFile::fileDump (ostream &log)
{
    HashNode *temp = new HashNode;
    fstream bin_file;
    bin_file.open ("storage_file.bin", ios::in | ios::binary);  
    for(int i = 0; i < table_size; i++)
    {
        bin_file.seekg( i * sizeof(HashNode) );
        bin_file.read( (char *)&temp, sizeof(HashNode) );
        printDump(HashNode(temp->title, temp->artist, temp->type, temp->year,
        temp->price), log, i);
    }
    bin_file.close();
}
void HashFile::printDump(HashNode A, ostream &log, int N)
{
    log << "(" << N << ") " << A.title << ", " << A.artist
        << ", " << A.type << ", " << A.year << ", $"
        << setprecision(2) << A.price << endl;
}

我知道我应该有一些错误检查。现在错误发生在printDump函数中。每当我尝试输出到日志,我得到一个访问冲突错误。但是,我将日志更改为cout,我的代码将运行得很好。它将读取我正确创建的二进制文件,直到到达最后一个元素。对于我所测试的,table_size应该等于5。所以我进入了for循环,I是递增的,直到它达到5,然后继续下去。table_size被更改为一些随机值,即使我没有实际接触它。我在内存中写table_size的地址吗?

下面是我的Node的定义:

class HashNode
{
    public:
        HashNode();
        ~HashNode();
        HashNode(string title, string artist, string type, int year, float price);
        friend class HashFile;
    private:
        char title [35];
        char artist [25];
        char type [12];
        int year;
        float price;
};

This

bin_file.read( (char *)&temp, sizeof(HashNode) );

应该是这个

bin_file.read( (char *)temp, sizeof(HashNode) );

你对指针感到困惑。

这段代码是否真的能工作很大程度上取决于Node的定义,你还没有展示。

代码泄漏内存,因为temp永远不会被删除。最好不要分配temp,就像这样

void HashFile::fileDump (ostream &log)
{
    HashNode temp;
    fstream bin_file("storage_file.bin", ios::in | ios::binary);  
    for(int i = 0; i < table_size; i++)
    {
        bin_file.seekg( i * sizeof(HashNode) );
        bin_file.read( (char *)&temp, sizeof(HashNode) );
        printDump(HashNode(temp.title, temp.artist, temp.type, temp.year, temp.price), log, i);
    }
}

不清楚为什么您觉得需要从temp创建一个新节点,为什么不直接将temp传递给printDump ?这样的

        printDump(temp, log, i);

但是没有看到Node的定义,我不能肯定。

也不需要关闭文件,它会自动发生,在构造函数中打开文件会更简洁一点。

编辑

好了,看了Node的定义,这是我的建议

void HashFile::fileDump(ostream &log)
{
    fstream bin_file("storage_file.bin", ios::in | ios::binary);  
    for(int i = 0; i < table_size; i++)
    {
        bin_file.seekg(i * sizeof(HashNode));    
        HashNode temp;
        bin_file.read((char *)&temp, sizeof(HashNode));
        printDump(temp, log, i);
    }
}

我还将printDump更改为使用const引用,这避免了复制Node对象(它相当大)。

void HashFile::printDump(const HashNode& A, ostream &log, int N)
{
    log << "(" << N << ") " << A.title << ", " << A.artist
        << ", " << A.type << ", " << A.year << ", $"
        << setprecision(2) << A.price << endl;
}

最新更新