2012-04-20 11 views
2

バイナリファイルを読み込んでデータベースに格納しようとしていますが、文字列型をデータベースに格納しようとするとセグメント化エラーが発生します。正確には、エラーがプッシュ機能の内部で発生します。バイナリファイルから行を読むC++

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++; 
} 
+1

ちょうどニックピンクになりますが、バイナリファイルに_lines_はありません。 –

答えて

3

このコードは悪いです:あなたはc_str()によって返されたバッファに書き込むことはできません

 infile.read((char*)(name.c_str()), sizeof(string)); 

、あなたを保持するのに十分な長さが保証されていません結果。 sizeof(string)は、文字列が保持できるサイズとはまったく関係ありません。 infile.readの結果を保持するために独自のchar[]バッファを割り当て、その後stringに変換する必要があります。

+0

もし私が間違っていないなら、私は何とか文字列またはchar *のサイズを知る必要がありますか?それをどうにかしていますか?もし私がinfile.read(name、100)をしていると言う。 char名[100]を持っていれば、それは次の100文字で読み込むことになりますか?助けてくれてありがとう。 – dajee

+0

文字列の長さを示す指標が必要です。文字列が最初に格納された方法によって異なります。彼らはヌル終了ですか?改行は終了しましたか?固定長ですか? –

+0

名前はコロンで終わり、crns - 1〜3の範囲で改行が終了します – dajee

関連する問題