Search code examples
cdata-structuresb-tree

How can i implement the operations of Disk-Read() and Disk-Write() on B-Tree?


I'm implementing B-trees in c language. To implement the b-trees I am following a certain pseudocode. In following this pseudocode i came across Disk-Read () and Disk-Write() operations that i don't know how to implement. The idea is to save all the nodes in secondary memory excluding the root of the B-tree and every time I have to read a node I perform a Disk-Read () operation in secondary memory and every time I want to write to it to modify its value I perform a Disk-Write () operation in secondary memory. Could anyone help me to implement these two procedures in c language?

I insert the pseudocodes of the search operation and the creation of an empty b-tree where these two procedures are called.

B-TreeCreate(T)
  x = Allocate()
  x.leaf = True
  x.n = 0
  DiskWrite(x)
  T.root = x

B-TreeSearch(x,k)
 i = 1
 while ((i ≤ x.n) and (k > x.keyi )) i = i + 1
  if ((i ≤ x.n) and (k = x.keyi ))
    then return (x, i)
  if (x.leaf = True)
   then return nil
  DiskRead(x.ci )
return BTreeSearch(x.ci,k)

Thanks again


Solution

  • Typically you would use either open() coupled with read()/write() or fopen() coupled with fread()/fwrite(). If trying to make more than a toy implementation you likely want to abstract this part away so that the IO system is easily replaced. (For example, if building for Windows there may be reason to use CreateFile() along with ReadFile()/WriteFile() instead). With proper I/O abstraction it would also be possible to have your btree backed by a compressed file.

    Thee three sets of functions take different arguments, in different orders, but in the end all perform the same operations, that is opening a file and either transferring bytes from secondary storage to memory or transferring bytes from memory to secondary storage.