C语言实现位示图磁盘管理算法:连续分配和离散分配
#include <stdio.h> #include <stdlib.h>
#define MAX_ROW 10 #define MAX_COL 10
int bitmap[MAX_ROW][MAX_COL]; // 位示图
// 初始化位示图 void initBitmap(int m, int n) { int i, j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { bitmap[i][j] = 0; } } }
// 显示位示图 void showBitmap(int m, int n) { int i, j; printf('Bitmap:\n'); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { printf('%d ', bitmap[i][j]); } printf('\n'); } }
// 连续分配 int allocateContiguous(int m, int n, int size) { int i, j, k, count; for (i = 0; i < m; i++) { count = 0; for (j = 0; j < n; j++) { if (bitmap[i][j] == 0) { count++; if (count == size) { // 分配成功,修改位示图 for (k = j - size + 1; k <= j; k++) { bitmap[i][k] = 1; } return i * n + j - size + 1; } } else { count = 0; } } } // 分配失败 return -1; }
// 离散分配 int allocateDispersed(int m, int n, int size) { int i, j, k, count; int *blocks = (int *)malloc(size * sizeof(int)); for (i = 0; i < m; i++) { count = 0; for (j = 0; j < n; j++) { if (bitmap[i][j] == 0) { blocks[count] = i * n + j; count++; if (count == size) { // 分配成功,修改位示图 for (k = 0; k < size; k++) { bitmap[blocks[k] / n][blocks[k] % n] = 1; } free(blocks); return blocks[0]; } } else { count = 0; } } } // 分配失败 free(blocks); return -1; }
// 回收某文件占用的盘块 void recycleFile(int m, int n, int file) { int i, j; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (bitmap[i][j] == file) { bitmap[i][j] = 0; } } } }
// 回收某个磁盘块 void recycleBlock(int m, int n, int block) { int i = block / n; int j = block % n; bitmap[i][j] = 0; }
int main() { int m = 4, n = 5; initBitmap(m, n); showBitmap(m, n);
// 连续分配
int size = 3;
int block = allocateContiguous(m, n, size);
if (block != -1) {
printf('Allocated %d contiguous blocks starting from %d\n', size, block);
} else {
printf('Failed to allocate %d contiguous blocks\n', size);
}
showBitmap(m, n);
// 离散分配
size = 2;
block = allocateDispersed(m, n, size);
if (block != -1) {
printf('Allocated %d dispersed blocks starting from %d\n', size, block);
} else {
printf('Failed to allocate %d dispersed blocks\n', size);
}
showBitmap(m, n);
// 回收某文件占用的盘块
recycleFile(m, n, 1);
showBitmap(m, n);
// 回收某个磁盘块
recycleBlock(m, n, 6);
showBitmap(m, n);
return 0;
原文地址: https://www.cveoy.top/t/topic/f1Eq 著作权归作者所有。请勿转载和采集!