fs.cpp

来自「一个简单的虚拟机和虚拟操作系统」· C++ 代码 · 共 112 行

CPP
112
字号
#include "StdAfx.h"
#include "fs.h"
#include<memory>
using namespace std;
char*sname = "disk.bin";
FS::FS()
{
	root = new Dictionary("root",NULL);
	try{
		CFile file(sname,CFile::modeRead|CFile::shareDenyWrite);
		CArchive ar(&file,CArchive::load);
		this->load(ar);
		current = root;
	}catch(...){
		MessageBox(0,"载入文件系统失败!","警告",MB_OK|MB_ICONWARNING);
		this->reset();
	}
	
	
}
FS::~FS()
{
	try{
		CFile file(sname,CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite);
		CArchive ar(&file,CArchive::store);
		this->save(ar);
	}catch(...){
		MessageBox(0,"存储文件系统失败!","警告",MB_OK|MB_ICONWARNING);
	}
	delete root;
}
bool FS::free(int num,int*tofree)
{
	if(num<=0||num>=BLOCK_NUM)
		return false;

	for(int i = 0;i<num;i++)
		used[tofree[i]] = false;

	freeSize += num*BLOCK_SIZE;

	return true;
}
bool FS::allocate(int num,int*alloc)
{
	if(num<=0||num*BLOCK_SIZE>freeSize)
		return false;

	for(int i = 0,j = 0;i<BLOCK_NUM&&j<num;i++)
	if(!used[i])
	{
		alloc[j++] = i;
		used[i] = true;
	}

	freeSize -= num*BLOCK_SIZE;

	return true;
}
int FS::getFreeSize()const
{
	return freeSize;
}
char* FS::getBlock(int index)const
{
	return disk.getBlock(index);
}
bool FS::readBlock(int index,char* buffer)const
{
	return disk.readBlock(index,buffer);
}
bool FS::writeBlock(int index,const char* buffer)
{
	return disk.writeBlock(index,buffer);
}
void FS::save(CArchive&ar)const
{
	ar<<(CString)"\r\n虚拟机磁盘文件,勿编辑!\r\n作者:张东进\r\n\r\n";
	root->save(ar);
	ar<<freeSize;
	for(int i = 0;i<DISK_SIZE;i++)
		ar<<disk.data[i];
	for(int i = 0;i<BLOCK_NUM;i++)
		ar<<used[i];
}
void FS::load(CArchive&ar)
{
	CString inf;
	ar>>inf;
	root->load(ar);
	ar>>freeSize;
	for(int i = 0;i<DISK_SIZE;i++)
		ar>>disk.data[i];
	for(int i = 0;i<BLOCK_NUM;i++)
		ar>>used[i];
}
void FS::reset()
{
	if(root!=NULL)
	try{
		delete root;
	}catch(...){}
	root = new Dictionary("root",NULL);
	current = root;
	freeSize = DISK_SIZE;
	memset(used,0,sizeof(bool)*BLOCK_NUM);
}
void FS::format()
{
	this->reset();
	memset(disk.data,0,DISK_SIZE);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?