2012-04-20 101 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_。 – 2012-04-20 05:47:38

回答

3

此代码是坏:

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

不能写入由c_str()返回的缓冲区,它不能保证足够长的时间来保存您的结果。顺便说一下,sizeof(string)与字符串可容纳的大小无关。您需要分配您自己的char[]缓冲区来保存infile.read的结果,然后再转换为string

+0

如果我没有错,我不得不知道字符串或char *的大小?无论如何要这样做?还说如果我做infile.read(名字,100);并有字符名称[100],这是否意味着我会在接下来的100个字符中读取?谢谢您的帮助。 – dajee 2012-04-20 20:44:16

+0

你需要一些指示字符串的时间长度,这一切都取决于字符串如何存储在第一位。它们是否以null结尾? Newline终止了?固定长度? – 2012-04-20 21:13:11

+0

名称被冒号终止,并且crns - 可以从1到3的范围是换行符终止 – dajee 2012-04-20 21:19:06