visual studio 2012 - update records in file (c++) -
i wanted ask how can append strings end of fixed number of lines (fixed position). trying , searching books , websites answer couldn't find doing wrong.
my structure :
const int numberofdays=150 ; const int numberofstudents=2; struct students { char attendance[numberofdays]; int rollno; char fullname[50],fathersname[50]; }
creating text file
ofstream datafile("data.txt", ios::out );
then take input user , save file.
how save data text files :
datafile <<attendance <<endl<< rollno <<endl<< fullname <<endl<< fathersname <<endl ;
how looks in text files :
p // p present - 1st line 1 // roll number monte cristo // full name black michael // fathers name // absent - 5th line 2 // roll number johnson // full name nikolas // fathers name
how try update file. (updating attendance everyday)
datafile.open("data.txt", ios::ate | ios::out | ios::in); if (!datafile) { cerr <<"file couldn't opened"; exit (1); } (int i=1 ; i<=numberofstudents ; i++) { long int offset = ( (i-1) * sizeof(students) ); system("cls"); cout <<"\t\tpresent : p \n\t\t absent : a"<<endl; cout <<"\nroll #"<<i<<" : "; cin >> ch1; if (ch1 != 'p') ch1 = 'a'; datafile.seekp(offset); datafile <<ch1; datafile.seekg(0); }
i want add (append) characters 'p' or 'a' first or fifth line, tried every possible way unable it.
what doing common, inefficient if size of data grows. 2 solutions have fixed size records , index files.
for fixed-size records, in file write exact bytes of data structure rather variable length text. mean don't have text file more, binary file. can calculate position seek easily.
to create index file, write 2 files @ once, 1 variable size record file, , other write binary value either offset of data start of file. since index fixed size, can seek index, read it, seek position in data file. if new record fit, can update in place, otherwise fill in blanks , put updated record @ end of data file, update index file point new location. how pc databases worked.
fixed size records rather inflexible, , time you've implemented index file system , tested it, now-a-days use in-process database instead.
Comments
Post a Comment