-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisk.c
More file actions
129 lines (101 loc) · 2.42 KB
/
disk.c
File metadata and controls
129 lines (101 loc) · 2.42 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
https://powcoder.com
代写代考加微信 powcoder
Assignment Project Exam Help
Add WeChat powcoder
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "disk.h"
/******************************************************************************/
static int active = 0; /* is the virtual disk open (active) */
static int handle; /* file handle to virtual disk */
/******************************************************************************/
int make_disk(char *name)
{
int f, cnt;
char buf[BLOCK_SIZE];
if (!name) {
fprintf(stderr, "make_disk: invalid file name\n");
return -1;
}
if ((f = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0) {
perror("make_disk: cannot open file");
return -1;
}
memset(buf, 0, BLOCK_SIZE);
for (cnt = 0; cnt < DISK_BLOCKS; ++cnt)
write(f, buf, BLOCK_SIZE);
close(f);
return 0;
}
int open_disk(char *name)
{
int f;
if (!name) {
fprintf(stderr, "open_disk: invalid file name\n");
return -1;
}
if (active) {
fprintf(stderr, "open_disk: disk is already open\n");
return -1;
}
if ((f = open(name, O_RDWR, 0644)) < 0) {
perror("open_disk: cannot open file");
return -1;
}
handle = f;
active = 1;
return 0;
}
int close_disk()
{
if (!active) {
fprintf(stderr, "close_disk: no open disk\n");
return -1;
}
close(handle);
active = handle = 0;
return 0;
}
int block_write(int block, char *buf)
{
if (!active) {
fprintf(stderr, "block_write: disk not active\n");
return -1;
}
if ((block < 0) || (block >= DISK_BLOCKS)) {
fprintf(stderr, "block_write: block index out of bounds\n");
return -1;
}
if (lseek(handle, block * BLOCK_SIZE, SEEK_SET) < 0) {
perror("block_write: failed to lseek");
return -1;
}
if (write(handle, buf, BLOCK_SIZE) < 0) {
perror("block_write: failed to write");
return -1;
}
return 0;
}
int block_read(int block, char *buf)
{
if (!active) {
fprintf(stderr, "block_read: disk not active\n");
return -1;
}
if ((block < 0) || (block >= DISK_BLOCKS)) {
fprintf(stderr, "block_read: block index out of bounds\n");
return -1;
}
if (lseek(handle, block * BLOCK_SIZE, SEEK_SET) < 0) {
perror("block_read: failed to lseek");
return -1;
}
if (read(handle, buf, BLOCK_SIZE) < 0) {
perror("block_read: failed to read");
return -1;
}
return 0;
}