Dear all, I have a program that it should write a struct in binary file.My struct is here: /////////////////// struct book{ string name; string author; string publisher; string translator; bool translation; bool stock; }; //////////////////////// Then i wrote the following function that write to file: //////////////////////////// void WriteFile::addNode(string name, string publisher, string author, bool stock,string translator , bool translation ){ book * tmp = new book; int line = 1; short unsigned i; string memory; short unsigned size = 100 - strlen((const char *)name.data()); memory = '`'; for (i =0 ;i<size;i++) memory += '`'; tmp->name = name + memory; size = 100 - strlen((const char *)publisher.data()); memory = '`'; for (i =0 ;i<size;i++) memory += '`'; tmp->publisher = publisher + memory; size = 100 - strlen((const char *)author.data()); memory = '`'; for (i =0 ;i<size;i++) memory += '`'; tmp->author = author + memory; size = 100 - strlen((const char *)translator.data()); memory = '`'; for (i =0 ;i<size;i++) memory += '`'; tmp->translator = translator + memory; tmp->stock = stock; tmp->translation = translation; fseek(bookFilePtr,0L,SEEK_END); fwrite(ptr,408,1,bookFilePtr); /////////////////////////// Note that i wanted to use fixed length of each field, So, for example if a field has 30 character, i fill 71 character "`" at end of field. 30 +71= 101 So 4*string*101+2*bool*4=408 = length of struct. Then i wrote the following function to read all of records: /////////////////////////////////////////////// void ReadFile::printList(){ fseek(bookFilePtr,0L,SEEK_SET); // set to begin of file int counter = 1; long int line = 1; int pageCounter = 1; while ( fread(bookPtrObj,408,1,bookFilePtr) == 1 ){ string output; mvprintw(++line, 27,"***Title*****************Value*********" ); output = "Name: " + bookPtrObj->name; mvprintw(++line, 27, output.data()); output = "Publisher: " + bookPtrObj->publisher; mvprintw(++line, 27,output.data()); output = "Author: " + bookPtrObj->author; mvprintw(++line, 27,output.data()); output = "Translator: " + bookPtrObj->translator; if (bookPtrObj->translation == true ) mvprintw(++line, 27,output.data()); if (bookPtrObj->stock != true ) mvprintw(++line, 27,"Stock: The given book doesn't exist."); else mvprintw(++line, 27,"Stock: The given book exist."); if ( pageCounter % 3 == 0){ mvprintw(++line, 27,"Press any key to see next page..."); getch(); clear(); line = 1; } pageCounter++; refresh(); fseek(bookFilePtr, counter * sizeof(struct book) ,SEEK_SET); // seek to next data counter ++; } } /////////////////////////////////////////////// But i get the segmentation fault on read each field. Because i didn't specify length of each field in read.How i specify length of each field in reading? --mohsen
Attachment:
signature.asc
Description: This is a digitally signed message part