-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisk.c
102 lines (79 loc) · 1.77 KB
/
disk.c
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
/*
* CS3600 Project 2: A User-Level File System
*
* This file is the file for reading/writing the virual disk.
* You **SHOULD NOT** touch anything in this file.
*/
#include <math.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "disk.h"
const int BLOCKSIZE = 512;
const int DEPTH = 20;
int fd = -1;
/***************** DO NOT MODIFY THE FUNCTIONS BELOW ***************/
/* Creates and onnects the disk */
int dcreate_connect() {
fd = open(DISKFILE, O_RDWR | O_CREAT, 0777);
if (fd < 0) {
perror("dconnect unable to access the disk file");
return 1;
}
return 0;
}
/* Connects the disk */
int dconnect() {
fd = open(DISKFILE, O_RDWR);
if (fd < 0) {
perror("dconnect unable to access the disk file");
return 1;
}
return 0;
}
/* Unconnects the disk */
int dunconnect() {
if (fd > 0) {
close(fd);
fd = -1;
return 0;
} else {
perror("disk is not connected");
}
return 1;
}
/* Read a block from disk */
int dread(int blocknum, char *buf) {
// printf("DEBUG: Reading from block %d\n", blocknum);
if (fd == -1) {
perror("disk is not connected");
return -1;
}
if(lseek(fd, blocknum*BLOCKSIZE, SEEK_SET)<0)
return -2;
if (read(fd, buf, BLOCKSIZE) != BLOCKSIZE) {
perror("dread");
return -3;
}
return BLOCKSIZE;
}
/* Write a block to disk */
int dwrite(int blocknum, char *buf) {
// printf("DEBUG: Writing to block %d\n", blocknum);
if (fd == -1) {
perror("disk is not connected");
return -1;
}
if(lseek(fd, blocknum*BLOCKSIZE, SEEK_SET)<0)
return -2;
if (write(fd, buf, BLOCKSIZE) != BLOCKSIZE) {
perror("dwrite");
return -3;
}
return BLOCKSIZE;
}