-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisk.c
More file actions
executable file
·102 lines (84 loc) · 1.94 KB
/
disk.c
File metadata and controls
executable file
·102 lines (84 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include "disk.h"
#define DISK_MAGIC 0xdeadbeef
static FILE *diskfile;
static int nblocks = 0;
static int nreads = 0;
static int nwrites = 0;
int disk_init(const char *filename, int n)
{
diskfile = fopen(filename, "r+");
if (!diskfile)
diskfile = fopen(filename, "w+");
if (!diskfile)
return 0;
ftruncate(fileno(diskfile), n * DISK_BLOCK_SIZE);
nblocks = n;
nreads = 0;
nwrites = 0;
return 1;
}
int disk_size()
{
return nblocks;
}
static void sanity_check(int blocknum, const void *data)
{
if (blocknum < 0)
{
printf("ERROR: blocknum (%d) is negative!\n", blocknum);
abort();
}
if (blocknum >= nblocks)
{
printf("ERROR: blocknum (%d) is too big!\n", blocknum);
abort();
}
if (!data)
{
printf("ERROR: null data pointer!\n");
abort();
}
}
void disk_read(int blocknum, char *data)
{
sanity_check(blocknum, data);
fseek(diskfile, blocknum * DISK_BLOCK_SIZE, SEEK_SET);
if (fread(data, DISK_BLOCK_SIZE, 1, diskfile) == 1)
{
nreads++;
}
else
{
printf("ERROR: couldn't access simulated disk: %s\n", strerror(errno));
abort();
}
}
void disk_write(int blocknum, const char *data)
{
sanity_check(blocknum, data);
fseek(diskfile, blocknum * DISK_BLOCK_SIZE, SEEK_SET);
if (fwrite(data, DISK_BLOCK_SIZE, 1, diskfile) == 1)
{
nwrites++;
}
else
{
printf("ERROR: couldn't access simulated disk: %s\n", strerror(errno));
abort();
}
}
void disk_close()
{
if (diskfile)
{
printf("%d disk block reads\n", nreads);
printf("%d disk block writes\n", nwrites);
fclose(diskfile);
diskfile = 0;
}
}