0

I wrote a program that first writes the contents of a vector into a file and then I try to read it back from the file but it seg faults. If I don't push it into the new vector c and print from it, it prints only 1 element of the vector. If we make mystring really big like say 40000 then it prints ". . ". Is this the right way to fread? Do we need to fseek (to the next element) within the for loop? Please help. Its different from the other question since we are using fread and fwrite.

  dir.files.push_back(".");
  dir.files.push_back("..");

  //write dir to blk1
  fseek(dFile, fs->inodeList[0].bid1, SEEK_SET);
  fwrite (&dir.files[0], sizeof(vector<string>::value_type), dir.files.size(), dFile);
  rewind(dFile);

  fclose (dFile);

  vector<string> c;
  char mystring[15];

  dFile = fopen ("virtual_disk.txt","r");
  if (dFile == NULL) perror ("Error opening file");

  fseek(dFile, fs->inodeList[0].bid1, SEEK_SET);
  for(int a =0; a <= dir.files.size(); a++)
  {
    fread(&mystring[0],sizeof(char),(size_t)15,dFile);
    cout << mystring << endl; // here it will print "."
    c.push_back(mystring); //if we have this line, it seg faults
  }


  for(int j =0; j< c.size(); j++) {
      printf("%s \n", c[j].c_str());
  }
D. Rao
  • 423
  • 2
  • 6
  • 16
  • `sizeof(vector::value_type)` -- `sizeof` is a constant computed at compile-time, and gives the size of the class. You need to ponder on the simple fact that the size of a `std::string` class is the same whether or not the string is empty, or contains the entire contents of the novel "War and Peace". Once you understand that fully, the problem with writing `sizeof(vector::value_type)` bytes to a file, and expecting the contents of the string to be written, whether it's empty or is a classical novel, should now be very obvious. – Sam Varshavchik Feb 12 '17 at 18:20
  • are you saying that our fwrite is incorrect? Can you be more specific? – D. Rao Feb 12 '17 at 19:14
  • Yes. An attempt to `fwrite` a `std::string` to a file, like that, will be completely and totally wrong. Try to do just that. Forget about reading. Just try to write a `std::string` to a file, in this manner, then look at all the binary garbage in the file, then reread the duplicate question again, for a full explanation. – Sam Varshavchik Feb 12 '17 at 20:24

0 Answers0