一、写在前面
本节分析为文件系统相关源码的最后一篇分析,本次分析的重点在于介绍目录与逻辑文件系统系统相关源码,学习文件系统的高层逻辑与宏观结构.
二、源码分析
1、文件目录:Directory
正如上一节所讲到的,想要找到文件的内容,只需要找到该文件的header,但header的扇区信息却没有办法获得.文件目录Directory就是用于提供文件名称到文件头扇区号转换这一功能的.
Directory是文件目录的内存表示,文件目录本身也是作为一个文件存在的,整个文件位于1号扇区.因此建立了Directory对象后需要读取1号扇区的内容得到目录文件数据.
class DirectoryEntry {
public:
bool inUse; // Is this directory entry in use?
int sector; // Location on disk to find the
// FileHeader for this file
char name[FileNameMaxLen + 1]; // Text name for file, with +1 for
// the trailing '\0'
};
class Directory {
public:
Directory(int size); // Initialize an empty directory
// with space for "size" files
~Directory(); // De-allocate the directory
void FetchFrom(OpenFile *file); // Init directory contents from disk
void WriteBack(OpenFile *file); // Write modifications to
// directory contents back to disk
int Find(char *name); // Find the sector number of the
// FileHeader for file: "name"
bool Add(char *name, int newSector); // Add a file name into the directory
bool Remove(char *name); // Remove a file from the directory
void List(); // Print the names of all the files
// in the directory
void Print(); // Verbose print of the contents
// of the directory -- all the file
// names and their contents.
private:
int tableSize; // Number of directory entries
DirectoryEntry *table; // Table of pairs:
// <file name, file header location>
int FindIndex(char *name); // Find the index into the directory
// table corresponding to "name"
};
directory.h中定义了两个类,表示文件目录的Directory和表示一个目录条目的DirectoryEntry.DirectoryEntry相对比较简单,其中有三个数据成员,inUse用于标识该条目是否被占用,sector表示该条目对应文件头的扇区号,name表示文件的名称.本类没有成员方法.
Directory类有两个数据成员,tableSize表示目录具有的条目数量,table为一个数组指针,数组内容为前面提到的目录条目DirectoryEntry.
下面对Directory的成员函数进行简介.
- FetchFrom: 读取目录文件填充Directory对象的条目数据
- WriteBack:在对Directory对象进行更改后写回至目录文件