i have a binary file where i save my struct:
struct vec
{
string author;
string name;
int pages;
string thread;
vec *next;
};
write to file function:
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);
}
}
write srtig function:
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;
}
}
read file:
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);
}
read string:
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";
}
trouble is in read string function, where i free memory. " delete [] str " i get crash of program on this line.
but if i dont exempt memorry works good.
Help me please!