CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Threaded View

  1. #1
    Join Date
    Apr 2002
    Posts
    61

    working with binary files

    I have a few functions I'm using to write values to a binary file. The problem is when I read from the file to retrieve values all I get is the last value written.

    The structure I am inserting is:
    Code:
    struct tsDataS
    {
    	unsigned	ts		: 32;
    	unsigned	volID	: 8;
    	unsigned	offset	: 32;
    };
    I calll the function add to insert (update) the value:
    Code:
    bool timestamp::add(tsData &ts)
    {
    
    	if(!myDB) return 0;
    
    	//change this to seek for empty spots first
    	fstream mFile;
    	int location, findRec;
    
    	objKey1.ts = TS_EMPTY;
    
    	//do we have an open entry space?
    	findRec = seekLocation(objKey1, TS_TST);//used to determine the record number
    	
    	mFile.open(myDB,ios::binary|ios::out);
    	location = (findRec - 1)*sizeof(ts);
    
    	mFile.seekp (location);//used to determine location of record
    	mFile.write((char*)&ts,sizeof(ts));
    
    	//replace old stamp
    	if(findRec < DBSize)
    	{
    		//increment counter
    		activeTScount++;
    	}
    
    	//need to make a new entry
    	else
    	{
    		//increment counters
    		DBSize++;
    		activeTScount++;
    	}
    	return 1;
    
    }
    And then add calls this to get the location of any "empty" (TS_EMPTY == ts) values:

    Code:
    int timestamp::seekLocation(tsData &ts, int tok)
    //Find a timestamp matching field tok in ts
    {
    
    	fstream seekFile;
    	int count =0;
    	bool found = false;
    	seekFile.open(myDB,ios::binary | ios::in);
    	seekFile.seekg(0,ios::beg);
    	while(seekFile.read((char*)&objKey1,sizeof(objKey1)))
    	{
    		++count;
    	if( tok == TS_VOL )
    		if(ts.volID == objKey1.volID)
    		{
    			found = true;
    			break;
    		}
    	else if ( tok == TS_OFF )
    		if(ts.offset == objKey1.offset)
    		{
    			found = true;
    			break;
    		}
    	else if ( tok == TS_TST )
    		if(ts.ts == objKey1.ts)
    		{
    			found = true;
    			break;
    		}
    	else if ( tok == TS_VOL + TS_OFF )
    		if(ts.offset == objKey1.offset && ts.volID == objKey1.volID)
    		{
    			found = true;
    			break;
    		}
    	}
    	seekFile.close();
    	
    	if(found) return count;
    	return count + 1;
    
    }
    Also another interesting point is that sizeof(objKey1) == 12 and sizeof(ts) == 4 even thought they are both struct tsDataS which I thought should equal 9??

    thanks,
    Devan
    Last edited by DevLip; March 30th, 2004 at 11:58 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured