-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisk.c
More file actions
94 lines (78 loc) · 1.86 KB
/
disk.c
File metadata and controls
94 lines (78 loc) · 1.86 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
/*
Do not modify this file.
Make all of your changes to main.c instead.
*/
#include "disk.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
extern ssize_t pread(int __fd, void *__buf, size_t __nbytes, __off_t __offset);
extern ssize_t pwrite(int __fd, const void *__buf, size_t __nbytes, __off_t __offset);
struct disk
{
int fd;
int block_size;
int nblocks;
};
struct disk *disk_open(const char *diskname, int nblocks)
{
struct disk *d;
d = malloc(sizeof(*d));
if (!d)
return 0;
d->fd = open(diskname, O_CREAT | O_RDWR, 0777);
if (d->fd < 0)
{
free(d);
return 0;
}
d->block_size = BLOCK_SIZE;
d->nblocks = nblocks;
if (ftruncate(d->fd, d->nblocks * d->block_size) < 0)
{
close(d->fd);
free(d);
return 0;
}
return d;
}
void disk_write(struct disk *d, int block, const char *data)
{
if (block < 0 || block >= d->nblocks)
{
fprintf(stderr, "disk_write: invalid block #%d\n", block);
abort();
}
int actual = pwrite(d->fd, data, d->block_size, block * d->block_size);
if (actual != d->block_size)
{
fprintf(stderr, "disk_write: failed to write block #%d: %s\n", block, strerror(errno));
abort();
}
}
void disk_read(struct disk *d, int block, char *data)
{
if (block < 0 || block >= d->nblocks)
{
fprintf(stderr, "disk_read: invalid block #%d\n", block);
abort();
}
int actual = pread(d->fd, data, d->block_size, block * d->block_size);
if (actual != d->block_size)
{
fprintf(stderr, "disk_read: failed to read block #%d: %s\n", block, strerror(errno));
abort();
}
}
int disk_nblocks(struct disk *d)
{
return d->nblocks;
}
void disk_close(struct disk *d)
{
close(d->fd);
free(d);
}