-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibDisk.c
91 lines (79 loc) · 1.79 KB
/
libDisk.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
#include "libDisk.h"
#define BLOCKSIZE 256
typedef struct node{
int disk;
char* filename;
struct node* next;
}node;
node* addNode(node* base){//fix this up
node* temp;
if(base != NULL){
temp = base;
base = calloc(sizeof(node),1);
base->disk = temp->disk + 1;
base->next = temp;
}else{
base = calloc(sizeof(node),1);
base->disk = 0;
}
return base;
}
char* getDisk(node* head, int num){
while(head && head->next && head->disk != num){
head = head->next;
}
return head->filename;
}
node *head = NULL; //head = neweset node
int openDisk(char *filename, int nBytes){
FILE* fd;
if(nBytes > 0){
if(!(fd = fopen(filename,"w+"))){
return DISKNOCREAT;
}else{
head = addNode(head);
}
}else{
if(!(fd = fopen(filename,"r+"))){
return DISKNOREAD;
//error
}else{
head = addNode(head);
}
}
if(nBytes == -1)
return PLACEHOLDER;
fclose(fd);
head->filename = filename;
return head->disk;
}
int readBlock(int disk, int bNum, void *block){
FILE* fd;
if(!(fd = fopen(getDisk(head, disk),"r"))){
return DISKNOREAD;
}
fseek(fd, bNum * BLOCKSIZE, SEEK_SET);
if(fread(block, 1, BLOCKSIZE, fd) < BLOCKSIZE){
return INCOMPREAD;
}
fclose(fd);
return 0;
}
int writeBlock(int disk, int bNum, void *block){
FILE* fd = 0;
int temp;
if(!(fd = fopen(getDisk(head, disk),"r+"))){
return DISKNOREAD;
}
fseek(fd, bNum * BLOCKSIZE, SEEK_SET);
if((temp = fwrite(block, 1, BLOCKSIZE, fd)) < BLOCKSIZE){
return INCOMPWRIT;
}
fclose(fd);
//add recovery?
return 0;
}
//to-do :
/*
error-check in read/write
*/