我正在尝试读取二进制文件并将其存储到数据库中,但是当我尝试将字符串类型存储到数据库中时出现分段错误。准确的说,错误发生在push函数内部:
new_node->name = name;
我似乎无法在网上找到一个好的解决方案,而且我漫无目的地尝试不同的东西......任何帮助将不胜感激。
//
// loadbin.cpp
//
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
#include "studentsDB.h"
int main( int argc, char* argv[] ) {
string name;
string id;
int numCourses;
int crn;
vector<int> crns;
studentsDB sDB;
studentsDB::node *students = 0;
int in = 1;
if( argc > 1 ) {
ifstream infile(argv[in], ios::binary );
while( !infile.eof() ) {
infile.read( ( char* )(name.c_str()), sizeof( string ) );
infile.read( ( char* )(id.c_str()), sizeof( string ) );
infile.read( ( char* ) &numCourses, sizeof( int ) );
do{
crns.push_back( crn );
}
while( infile.read( ( char* ) &crn, sizeof( int ) ) );
sDB.push( &students, (string)name, (string)id, numCourses, crns );
}
//sDB.printList( students );
}
else
cout << "Not enough argument" << endl;
}
void studentsDB::push( struct node** head_ref, string name, string id,
int numCourses, vector<int>crns ) {
struct node* new_node = ( struct node* ) malloc(sizeof(struct node));
new_node->name = name;
//new_node->id = id;
new_node->numCourses = numCourses;
//new_node->crns = crns;
new_node->next = (*head_ref);
(*head_ref) = new_node;
size++;
}