读取二进制文件时可用内存

时间:2014-11-14 12:38:45

标签: c++ c file memory fread

我有一个二进制文件,我保存我的结构:

struct vec
{
    string author;
    string name;
    int pages;
    string thread;
    vec *next;
};

写入文件功能:

    void logic::WriteInfoToFile()
{
    if (first != NULL)
    {
        pFile = fopen(way.c_str(), "wb");
        if (pFile != NULL)
        {
            fseek(pFile, 0, SEEK_SET);
            temp = first;
            while (temp != NULL)
                {
                    WriteString(temp->author,pFile);
                    WriteString(temp->name,pFile);
                    fwrite(&temp->pages,sizeof(int), 1, pFile);
                    WriteString(temp->thread,pFile);
                    temp = temp->next;
                }       
        }   
        fclose(pFile);
    }
}

写srtig函数:

void logic::WriteString(string s, FILE *pFile)
{
    if (pFile != NULL)
    {   
        char *str = new char[s.length() + 1];
        strcpy(str, s.c_str());
        int size = strlen(str);
        fwrite(&size, sizeof(int), 1, pFile);
        fwrite(str, size, 1, pFile);
        delete [] str;
    }
}

读取文件:

void logic::ReadInfoFromFile()
{
    pFile = fopen(way.c_str(), "rb");
    if (pFile != NULL)
    {       
        fseek(pFile, 0, SEEK_END);
        if (ftell(pFile) != 0)
        {   
            fseek(pFile, 0, SEEK_SET);
            int check;
            while (check != EOF)
            //while (!feof(pFile))
            {
                temp = new vec;
                temp->author = ReadString(pFile);
                temp->name = ReadString(pFile);
                fread(&temp->pages, sizeof(int), 1, pFile);
                temp->thread = ReadString(pFile);
                temp->next = NULL;
                if (first == NULL)
                {
                    first = temp;
                    first->next = NULL;
                }
                else
                {
                    temp->next = first;
                    first = temp;
                }
                recordsCounter++;

                check = fgetc(pFile);
                fseek(pFile, -1, SEEK_CUR);
            }
        }
    }
    fclose(pFile);
}

读取字符串:

string logic::ReadString(FILE *pFile)
{
    string s;
    if (pFile != NULL)
    {
        int size = 0;
        fread(&size, sizeof(int), 1, pFile);
        char *str = new char[size];
        fread(str, size, 1, pFile);
        str[size] = '\0';
        s = str;
        //delete [] str;   //WHY?????????!!!!!
        return s; 
    }   
    else
        return s = "error";
}

麻烦在读取字符串函数,我释放内存。 “delete [] str”我在这一行上遇到程序崩溃。

但如果我不豁免记忆效果不错。

请帮帮我!

1 个答案:

答案 0 :(得分:3)

一个人分配size个字符,但覆盖大小+ 1(终端'\ 0')。内存管理器不喜欢这样。

char *str = new char[size];
fread(str, size, 1, pFile);
str[size] = '\0'