使用链表读取文件(.csv 大小1663kb,一万多条数据),控制台闪退,空间不足。 原因:char BookName[1000];等,绝大部分字符串都不会超过1000字节,直接静态字符串浪费空间。
class Book
{
public:
char BookName[1000];
char Writer[1000];
char PublishDate[20];
char ISBN[30];
char ebook[2];
char paperbook[2];
char Publisher[1000];
char BriefIntroduction[1000];
int i_o;
Book *next;
};
改为,字符指针,动态分配空间
class Book
{
public:
char *BookName;
char *Writer;
char PublishDate[20];
char ISBN[30];
char ebook[2];
char paperbook[2];
char *Publisher;
char *BriefIntroduction;
int i_o;
Book *next;
};
static void save_file()
{
Book *p;
fstream file;
string s1,s2,s3,s4,s5,s6,s7,s8,s9;
char a1[1000];
file.open("library//big.csv",ios::in | ios::out);
if(!file)
{
cout<<"[save_file] big.csv not open file"<<endl;
return;
}
getline(file,s1,',');
head_ptr->BookName=new char[strlen(s1.c_str())+1];
strcpy(head_ptr->BookName,s1.c_str());
getline(file,s2,',');
head_ptr->Writer=new char[strlen(s2.c_str())+1];
strcpy(head_ptr->Writer,s2.c_str());
getline(file,s3,',');
strcpy(head_ptr->PublishDate,&s3[0]);
getline(file,s4,',');
strcpy(head_ptr->ISBN,&s4[0]);
getline(file,s5,',');
strcpy(head_ptr->ebook,&s5[0]);
getline(file,s6,',');
strcpy(head_ptr->paperbook,&s6[0]);
getline(file,s7,',');
head_ptr->Publisher=new char[strlen(s7.c_str())+1];
strcpy(head_ptr->Publisher,s7.c_str());
getline(file,s8);
head_ptr->BriefIntroduction=new char[strlen(s8.c_str())+1];
strcpy(head_ptr->BriefIntroduction,s8.c_str());
node = head_ptr;
while(!file.eof())
{
p = new Book[sizeof(Book)];
getline(file,s1,',');
if(s1=="")
{
break;
}
p->BookName=new char[strlen(s1.c_str())+1];
strcpy(p->BookName,s1.c_str());
getline(file,s2,',');
p->Writer=new char[strlen(s2.c_str())+1];
strcpy(p->Writer,&s2[0]);
getline(file,s3,',');
strcpy(p->PublishDate,&s3[0]);
getline(file,s4,',');
strcpy(p->ISBN,&s4[0]);
getline(file,s5,',');
strcpy(p->ebook,&s5[0]);
getline(file,s6,',');
strcpy(p->paperbook,&s6[0]);
getline(file,s7,',');
p->Publisher=new char[strlen(s7.c_str())+1];
strcpy(p->Publisher,&s7[0]);
getline(file,s8,'\n');
p->BriefIntroduction=new char[strlen(s8.c_str())+1];
strcpy(p->BriefIntroduction,&s8[0]);
p->next=NULL;
node -> next= p;
node = p;
n++;
}
file.close();
delete p;
}
总结:大量数据存储,每一个结构体分配的长度不相同,使用定长char浪费内存,使用动态空间的分配节约内存。
|