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());
}