c++filefstreamfixed-length-record

Writing Fixed length records into a file c++


I'm trying to write N fixed length record of type struct

const int N = 101;
char dummay[] = "#####";

struct hashTable
{
   char  name[51];
   int RRN;
};
int main(){
    fstream f("hashFile.txt");
    f.seekp(0,ios::beg);
    hashTable h;
    for (int i = 0 ; i < N ; i++ ) {
       strcpy(h.name,dummay);
       h.RRN = i;
       f.write((char*)&h,sizeof h);
     }

and when I'm trying to output these records again, only the first 25 records works well!

f.seekp(0,ios::beg);
for (int i = 0 ; i < N ; i++ )
{
    f.read((char*)&h,sizeof h);
    cout << h.RRN << endl << h.name << endl;
}

the complete code, why this happens and how to solve it ?!


Solution

  • You are obviously writing binary data into your file (the int, the null terminator in name and the 45 garbage chars that might follow the name).

    So open it in binary mode and it'll work well:

    fstream f("hashFile.txt", ios::binary); 
    

    When reading the file in text mode, depending on your os, some binary chars might be interpreted as end of file marker. For example Ctrl+Z on windows (which happen by chance to be ascii code 26)