]> git.llucax.com Git - z.facultad/75.52/treemulator.git/blob - src/btree.c
e6f09e10bf2846d75d942844ab939d24f1f4c06e
[z.facultad/75.52/treemulator.git] / src / btree.c
1
2 #include "btree.h"
3
4 static void write_tree_header (BTree *tree);
5 static void write_block (BTree *tree, uchar *block, uint num);
6
7 BTree *btree_create (const char *filename, unsigned int block_size)
8 {
9         BTree *tree;
10         uchar *node;
11
12         tree = malloc (sizeof(BTree));
13         if (!tree)
14                 return NULL;
15
16         tree->fp = fopen (filename, "wb");
17         if (!tree->fp) {
18                 free (tree);
19                 return NULL;
20         }
21
22         /* Nombre de archivo */
23         tree->filename = malloc(sizeof(char)+1);
24         strcpy (tree->filename, filename);
25         
26         /* Inicializo el header */
27         tree->header.block_size = block_size;
28         write_tree_header (tree);
29
30         /* Creo el primer bloque vacio */
31         node = calloc (1, block_size);
32         write_block (tree, node, 0);
33
34         return tree;
35 }
36
37 int btree_close (BTree *tree)
38 {
39         fclose (tree->fp);
40         free (tree->filename);
41         free (tree);
42
43         return 0;
44 }
45
46 static void write_tree_header (BTree *tree)
47 {
48         fseek (tree->fp, 0L, SEEK_SET);
49         fwrite (&tree->header, 1, sizeof (BTreeHeader), tree->fp);
50 }
51
52 static void write_block (BTree *tree, uchar *block, uint num)
53 {
54         fseek (tree->fp, num*tree->header.block_size + sizeof (BTreeHeader), SEEK_SET);
55         fwrite (block, 1, tree->header.block_size, tree->fp);
56 }
57