Вы находитесь на странице: 1из 52

Operating Systems Project: The File System

The File System & Directory System Module

Maitreya Natu
Erhan Atilla Avinal
Shivkundan Singh Tej
Tam H. Vu

1
Operating Systems Project: The File System

Contents
Overview...........................................................................................................................................................3
Project Description...........................................................................................................................................4
Disk organization module............................................................................................................................4
File System Module.....................................................................................................................................5
File attributes...........................................................................................................................................5
File Operations........................................................................................................................................5
Directory System Module............................................................................................................................5
Directory attributes.................................................................................................................................5
Directory Operations...............................................................................................................................5
Presentation Shell.........................................................................................................................................6
Interface to file system......................................................................................................................................7
Disk Organization.............................................................................................................................................8
Bitmap..........................................................................................................................................................8
Descriptors...................................................................................................................................................8
Data Blocks..................................................................................................................................................8
Class descriptions.............................................................................................................................................9
DESCRIPTOR Class...................................................................................................................................9
DISK Class...................................................................................................................................................9
FILE Class.................................................................................................................................................10
FS Class (File System)...............................................................................................................................10
DIRECTORY Class...................................................................................................................................11
DS Class (Directory System).....................................................................................................................12
FDS Class (combination of File and Directory classes)............................................................................13
GUI Class...................................................................................................................................................14
System Specification......................................................................................................................................15
Conclusion......................................................................................................................................................16
References.......................................................................................................................................................17
Appendix A - User Guide...............................................................................................................................18
format.........................................................................................................................................................18
list...............................................................................................................................................................18
cd ......................................................................................................................................................19
makedir......................................................................................................................................................19
movedir......................................................................................................................................................19
rndir............................................................................................................................................................20
cpdir...........................................................................................................................................................20
deldir..........................................................................................................................................................21
createfile.....................................................................................................................................................21
copy............................................................................................................................................................21
rnfile .....................................................................................................................................................22
cpfile ....................................................................................................................................................22
delfile ......................................................................................................................................................23
writefile .....................................................................................................................................................23
print............................................................................................................................................................24
x..................................................................................................................................................................24
Appendix B - Class Diagram..........................................................................................................................25
Appendix C - Source Code.............................................................................................................................26

2
Operating Systems Project: The File System

Overview
Most popular secondary memory devices are very complex to interact with. OS provides
extensive services for managing data on secondary memory. These data are organized
into files. An OS generally has many different files. Directories are provided to help
organize these in some way. The sole purpose of a directory is to record information
about other files and directories. File System is part of OS that is responsible for
managing files, directories and resources on which these reside.

The project develops a simple file system over an emulated I/O system. The project
focuses on following issues:
• Present a logical and abstract view of files and directories to users by hiding the
physical details of the secondary storage devices and I/O operations.
• Providing tree structured directories to help organize files.
• Providing extensive tools for creating and manipulating information in files and
directories.

File &
User Directory
I/O System
System

User interacts with the File and Directory System using commands – create, open, read,
write etc. File and Directory System views the disk as an array of blocks. I/O system
provides an abstract view of logical blocks to File and Directory System.

3
Operating Systems Project: The File System

Project Description
The project can be broadly divided into 4 modules:
• The disk organization module
• The file system module
• The directory system module
• The user interface module

Disk organization module

This module interacts with the BLOCK I/O subsystem to read and write to disk blocks.
The module hides the intricacies of storage devices from the other modules and provides
a higher level of abstraction of the disk in terms of Bitmap, Descriptors and DataBlocks.
This can be viewed from the following figure.

/(root)

File1 Dir1 Dir2

File 2 File 3
Tree containing files and directories

Bitmap Descriptors Data blocks

Logical view of disk as 1D blocks

Physical Disk

4
Operating Systems Project: The File System

File System Module

This module is concerned mainly with the delivery of file contents to the calling
programs and with writing information to files. A file system view files as a sequence of
logical records. The module provides users to read and write variable sized blocks in
files. These variable sized blocks are mapped down to the sequence of blocks of fixed
size.

File attributes
A file system maintains file attribute information, some of which are readily available to
the user while others are used by OS for its various file and directory manipulation
functions. The stored attributes include:
Name, Size, Owner, Protection, Descriptor Number.

File Operations
The module provides tools for creating file in the present directory tree. The present file
can be opened for reading and writing. The file has owner and protection information
associated with it, which can protect the file from invalid access. Purely sequential access
is too restrictive. So it provides command for seek and rewind the files.

Directory System Module

This module provides directories for organization of files into groups relative to their
content or protection. The module creates a tree structured hierarchy which makes it easy
to search and maintain. The leaves of the tree are files while all the intermediate nodes
are directories.

Directory attributes
A directory system also maintains attributes like files either for user’s information or for
OS specific purpose. These attributes are:
Name, Number of children, Parent, Owner, Protection, Descriptor Number.

Directory Operations
A directory associates symbolic names to files given by user to data necessary to locate
the file on the media. The directory operations include creating, deleting, renaming,
moving, changing the current directory.

5
Operating Systems Project: The File System

Presentation Shell

The functionality of the file system can be tested by this shell which provides a set of
programs to exercise various functions provided by the file system. The shell provides an
interactive interface with a set of command and an online help to use the file system
tools.

6
Operating Systems Project: The File System

Interface to file system


In an operating system design the file system is placed above the BLOCK I/O System.
The block I/O System provides the tools for reading and writing to the blocks and thus
hides the details of secondary storage devices. This interface gives an abstraction of the
disk as a one dimensional sequence of blocks.

The file system (disk organization module) organizes this 1D array of blocks into a
format suitable to store file and directory. The Users to file system are provided with files
and directories and a set of commands to manipulate them.

Symbolic File Name Open File objects

File System Interface


File & Directory Operations

File & Directory System Files and Directories

readDescriptor(), writeDescriptor(),
readDataBlock(), writeDataBlock()
Bitmap, Descriptors, Data blocks
Device Organization Methods

I/O System Interface


readBlock() writeBlock()

BLOCK I/O Subsystem Raw disk blocks

7
Operating Systems Project: The File System

Disk Organization
The disk is divided into 3 parts

Bitmap
The bitmap describes which blocks of the disk are free and which are occupied by
existing files and directories. Each bit corresponds to one logical block. The bitmap is
consulted by the file system whenever a file or directory grows as the result of a write
operation and when it is destroyed.

Descriptors
Each file and directory is assigned a descriptor which contains the information required
to locate the file or directory on the disk. The descriptor contains length of the file or
directory and the block addresses where it is stored.

Data Blocks
In this area the data of files and directories is stored.

/ (root)

Dir File

1 1 0 0 0 0 ……………………………………………… 0
Bitmap

2 2 1
2 0 40
1 0 2 …………………………….
0 0 0
0 0 0
… …. ….
Descriptor

Name D O P 40 bytes of
Dir 2 4 7 data of file
File 3 4 7 ………………………….

Data Blocks

8
Operating Systems Project: The File System

Class descriptions

DESCRIPTOR Class

Purpose: This class encapsulates the information stored in a descriptor.


Data:
 type: Unused(0), File(1), Directory(2)
 Size: Length of file or Number of entries in directory
 block_addresses[]: Array of block addresses occupied by file or directory
Methods:
None

DISK Class

Purpose: This class simulates a formatted disk. It contains the formatting information of
the file system. It provides methods to manipulating the disk content thus hiding the
internal details of lower level bit and byte manipulation.
Data:
BLOCK_SIZE: the size of a logical block
NUMBER_OF_DESCRIPTORS: The maximum number of descriptors that can be
created
DESCRIPTOR_SIZE: size of a descriptor
NUMBER_OF_BLOCKS: The maximum number of blocks allowed
MAXIMUM_FILE_SIZE: The maximum file size that can be created
Bitmap: A data structure to store the use/unuse bits for each block on disk
Descriptor_Array: A data structure to store all the descriptors for files and
directories.
Block_Array: A data structure to store the logical blocks where data is written.
Methods:
disk():
Purpose: Initialize the Descriptor_Array
Inputs: None
Return Values: None
Functions Calling: main()
Functions Called: None
int formatDisk():
Purpose: Formats the disk, which includes
- Clearing all the bits in Bitmap
- Initializing the descriptor of root directory
Inputs: None
Return Values: None
Functions Calling: main()
Functions Called: None

9
Operating Systems Project: The File System

DESCRIPTOR readDescriptor(int descriptor_number):


Purpose: return the required Descriptor
Inputs: Descriptor Number
Return Values: DESCRIPTOR instance
int writeDescriptor (int descriptor_number, DESCRIPTOR d):
Purpose: writes the Descriptor
Inputs: Descriptor Number, DESCRIPTOR instance
Return Values: 1 if successful else 0
int readBlock(int block_number, byte data[]):
Purpose: reads a data block into the byte array passed
Inputs: Block Number, data to read into
Return Values: 1 if successful else 0
int writeBlock(int block_number, byte data[]):
Purpose: writes a data block
Inputs : Block Number, data to write
Return Values: 1 if successful else 0
short findFreeBlock():
Purpose: find a free data block
Inputs: None
Return Values: block number if successful else -1
int findFreeDescriptor():
Purpose: find a free descriptor
Inputs: None
Return Values: descriptor number if successful else -1

FILE Class

Purpose: This class encapsulates the information about a file.


Data:
Name: name of the file
Descriptor_Number: descriptor number of the file
Current_Position: Position of the read write pointer
Location : The directory in which the file is stored
Owner: User ID of the owner of the file
Protection: Protection Bits of the file (7 = rwx)
Use: Status about the current usage of the file
Methods:
printFile()
Purpose: To print the system information of the file.
Inputs: None
Return Values: None

FS Class (File System)

10
Operating Systems Project: The File System

Purpose: This class provides tools to manipulate files.


Data:
None.
Methods: the names are self-explanatory
File createFile( String file_name, int owner,
Directory location, int protection)
Purpose: To create a new file.
Inputs: Name, owner, location, protection of the new file
Return Values: File instance
File openFile (String name)
Purpose: To open a file.
Inputs: Name of the file
Return Values: File instance

int readFile(File fd, int number_of_bytes, byte[] data)


Purpose: To read data from a file.
Inputs: File instance, number of byte to read, and data to read to
Return Values: 1 if succesful else 0
int writeFile(File fd, int number_of_bytes, byte[] data)
Purpose: To write data to a file.
Inputs: File instance, number of byte to write, and data to write from
Return Values: 1 if succesful else 0
File copyFile(String originalName, String newName)
Purpose: To copy a file to a new one in the same directory.
Inputs: Name of the two files
Return Values: File instance of the new file
void rewind(File fd)
Purpose: To reset position of the file to 0
Inputs: File instance
Return Values: none
void changeProtection(File fd, int protectionBits)
Purpose: To update the file’s Protection bits
Inputs: File instance, new protection
Return Values: none

DIRECTORY Class

Purpose: This class encapsulates the information about a directory.


Data:
Name: name of the directory
Descriptor_Number: descriptor number of the directory
Block_Number: data block number where the directory resides
Parent: The parent directory
Owner: User ID of the owner of the directory
Protection: Protection Bits of the directory (7 = rwx)

11
Operating Systems Project: The File System

Children: number of subdirectories and files that the directory has


Methods:
printDirectory()
Purpose: To print the system information of the directory.
Inputs: None
Return Values: None

DS Class (Directory System)

Purpose: This class provides tools to manipulate files.


Data:
static String currentPath
static Directory currentDir
Method: method names are self-explanatory. We explain only when it needs be
DS():
Purpose: To initialize the root directory.
Inputs: none
Return Values: DS instance

Directory createDir( String dir_name, byte owner,


Directory location, byte protection)
Purpose: To create a new directory at location.
Inputs: name, owner, protection, location of the new directory
Return Values: Directory instance

int renameDirectory(Directory dir, String new_name)


Purpose: To rename a directory.
Inputs: Directory instance and the new name
Return Values: 1 if successful else 0
int changeDirectory(String new_path)
Purpose: To change the working (current) directory to another location.
Inputs: path of the new location
Return Values: 1 if successful else 0
void changeProtection(String name, int protection)
Purpose: To update the directory’s Protection bits
Inputs: Directory instance, new protection
Return Values: none
int moveDirectory(Directory dir, String new_path)
Purpose: To move a directory to a new location
Inputs: Directory instance, new location
Return Values: 1 if successful else 0
int deleteDirectory(Directory dir)
Purpose: To delete a directory, it only works if the directory is empty
Inputs: Directory instance

12
Operating Systems Project: The File System

Return Values: 1 if successful else 0


int deleteFile(File file)
Purpose: To delete a file
Inputs: File instance
Return Values: 1 if successful else 0
File findFile_local(Directory location, String file_name)
Purpose: Finds in current directory the file with name file_name
Inputs: Directory instance, name of the file
Return Values: File instance, if found, the instance’s name will match with
file_name, otherwise, it is null
Directory findDirectory(String dir_name)
Purpose: To find a directory with name dir_name. Currently, it supports
only two options: if the first character of dir_name is ‘/’, it will search from the root,
otherwise, it will search in only current
Inputs: Name of the directory
Return Values: Directory instance
Directory findDirectory_local(Directory location, String dir_name)
Purpose: Finds in current directory the directory with name dir_name
Inputs: Directory instance, name of the directory
Return Values: Directory instance, if found, the instance’s name will match
with dir_name, otherwise, it is null

Directory getCurrentPath()
Purpose: To get the current directory
Inputs: none
Return Values: Directory instance
int printCurrentPath()
Purpose: To print the information of the current directory
Inputs: none
Return Values: 1 if successful else 0
int listDir (Directory location)
Purpose: To list the entries of the current directory
Inputs: Directory instance
Return Values: 1 if successful else 0

int addFile (File file)


Purpose: To add a file to the current directory
Inputs: File instance
Return Values: 1 if successful else 0

FDS Class (combination of File and Directory classes)

Purpose: This class is to call to GUI class


Data:
public static disk d;

13
Operating Systems Project: The File System

public static FS fileSys;


public static DS dirSys;
Method:
void main (String args[])

GUI Class
Purpose: This class is to implement the user interface of our system
Data:
DS dirSys;
FS fileSys;
disk d;
byte OWNER_UI = 1;
byte PROTECTION_UI = 7;
int MAXBYTE = 32767;
Method:
void error(String err): to print error message to the screen
char confirm(String str): to receive input from user
void printCommandPromt(): to print the command prompt to accept user’s input
int renameFile (ArrayList parameters): to rename a file with parameters from user
int deleteFile(ArrayList parameters): to delete a file with parameters from user
int createFile(ArrayList parameters): to create a file with parameters from user
int changeFileProtection(ArrayList parameters) : to change a file’s protection mode
with parameters from user
int printFile(ArrayList parameters): to print the content of a file with parameters
from user
int copyFile(ArrayList parameters): to copy a file with parameters from user
int moveDir(ArrayList parameters): to move a directory to a new location with
parameters from user
int renameDir(ArrayList parameters): to rename a directory with parameters
from user
int deleteDir(ArrayList parameters): to delete a directory with parameters
from user
int appendFile(ArrayList parameters): to write data to a file with parameters
from user
int createDir(ArrayList parameters): to create a directoty with parameters
from user
int changeDirProtection(ArrayList parameters): to change a directoty’s protection
with parameters from user
int changeDir(ArrayList parameters): to change current directoty to a new
location with parameters from user
int listDir(String dirname,ArrayList options): list content of a directory with options
from user
int formatDisk()
void showHelp(): display command syntax

14
Operating Systems Project: The File System

System Specification

As a consequence of the system's design, our File System has the following specification:

• Maximum file/directory name length: 26


(32 bytes are for each directory in a data block, including 4 bytes for descriptor
number, 1 byte for Protection, 1 byte for Owner).
• Number of data block: 512
• Block size: 512 bytes
• Data storage size: 512 x 512 = 218 bytes = 28MB
• Maximum file size: 13 x 512 = 6656 bytes
• Maximum number of entries (including both directories and files) in the system:
10 x 512/32=160
(10 blocks for descriptors - not a part of 512 data blocks, each descriptor occupies
32 bytes)
• Protection bits: r-w-x bits are associated with each file and directory

15
Operating Systems Project: The File System

Conclusion
The summary of tasks which are performed in this project :

1) Emulated the disk structure.

2) Designed and implemented the File and Directory System on top the I/O System.
This supports the user/file system interface.

3) Designed and implemented a command language for the presentation shell, which
demonstrates the functionality of our file system interactively.

4) Our file system works for a variety of command sequences exploring all aspects
of its behavior.

The future extensions of this project could be:

1) As our file and directory system provides a small upper limit on file and directory
size (of 6656 bytes). The limit can be increased by using multilevel indexing in
the descriptor.

2) Our file system provides same access rights to all users. Can be extended by
adding more bytes for storing protection information.

3) The present file system does not support symbolic links. This feature can be
extended by adding some link information in the directory & the descriptor
structure

16
Operating Systems Project: The File System

References
1) L.F Bic, A. C. Shaw, Operating Systems Principles, 2003.

2) The Java Tutorial, http://java.sun.com/docs/books/tutorial/.

3) Andrew Tanenbaum, Modern Operating Systems (2nd Edition).

17
Operating Systems Project: The File System

Appendix A - User Guide


File-Directory system has a user interface which lets users operate on files and
directories. The commands supported by the user interface are as follows:

format
This command formats the disk.

Usage : format

Sample output:
ui[/]> format
All information on the disk will be deleted permanently. Are you
sure? [y/n] : y
Format finished

list
List command lists the given directory. If no directory is given it lists the current
directory.

Usage : list [<directory name>] [-all] [-od] [-of]


<directory name> : Directory to be listed
-all : Details of files and directories in the directory i.e. owner, protection
-od : List directories only
-of : List files only

Sample output:

ui[/]> list -all

TYPE SIZE PROT. OWNER NAME


------------------------------------
<DIR> 7 1 documents
<DIR> 7 1 projects
<DIR> 7 1 pictures
<FILE> 25 7 1 file1

Total 1 files and 3 directories

ui[/]> list documents -of

TYPE SIZE NAME


--------------------
<FILE> 8 doc1

Total 1 files and 0 directories

18
Operating Systems Project: The File System

cd
This command changes directory to the given directory

Usage : cd <directory name>

Sample output:

ui[/]> cd documents
ui[documents]>

makedir
Makedir creates a new directory in the current directory.

Usage : makedir <directory name>

Sample output:

ui[/]> makedir pictures

movedir
This command moves a directory to another directory.

Usage : movedir <Directory name> <New directory name>

Sample output:

ui[/]> makedir dir1


ui[/]> makedir dir2
ui[/]> movedir dir1 dir2
ui[/]> list

TYPE SIZE NAME


--------------------
<DIR> dir2

Total 0 files and 1 directories


ui[/]> cd dir2
ui[dir2]> list

TYPE SIZE NAME


--------------------
<DIR> dir1

Total 0 files and 1 directories

19
Operating Systems Project: The File System

rndir
Renames a directory.

Usage : rndir <Directory name> <New directory name>

Sample output:
ui[/]> list

TYPE SIZE NAME


--------------------
<DIR> dir2

Total 0 files and 1 directories

ui[/]> rndir dir2 newname


ui[/]> list

TYPE SIZE NAME


--------------------
<DIR> newname

Total 0 files and 1 directories

cpdir
This command changes the protection of a directory.

Usage : cpdir <Directory name> <Protection>


<Protection> : This value could be between 0 and 7. It consists of three bits: read,
write, and execute.

Sample output:

ui[/]> list -all

TYPE SIZE PROT. OWNER NAME


------------------------------------
<DIR> 7 1 documents

Total 0 files and 1 directories

ui[/]> cpdir documents 5


ui[/]> list -all

TYPE SIZE PROT. OWNER NAME


------------------------------------
<DIR> 5 1 documents

Total 0 files and 1 directories

20
Operating Systems Project: The File System

deldir
This command deletes a given directory if it is not empty.

Usage : deldir <Directory name>

Sample output:

ui[/]> list

TYPE SIZE NAME


--------------------
<DIR> documents

Total 0 files and 1 directories

ui[/]> deldir documents


Delete Directory? [y/n] : y
ui[/]> list

File or directory not found

createfile
This command creates a new empty file in the current directory.

Usage : createfile <File name>

Sample output:

ui[/]> list

File or directory not found

ui[/]> createfile doc1


ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 0 doc1

Total 1 files and 0 directories

copy
This command copies a file in the current directory.

Usage : copy <File name> <New file name>

21
Operating Systems Project: The File System

Sample output:
ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 14 doc1

Total 1 files and 0 directories

ui[/]> copy doc1 doc2


ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 14 doc1
<FILE> 14 doc2

Total 2 files and 0 directories

ui[/]> print doc1


content of doc
ui[/]> print doc2
content of doc

rnfile
Rnfile command changes name of a given file.

Usage : rnfile <File name> <New file name>

Sample output:
ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 14 doc1

Total 1 files and 0 directories

ui[/]> rnfile doc1 doc2


ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 14 doc2

Total 1 files and 0 directories

cpfile
This command changes the protection of a file.

22
Operating Systems Project: The File System

Usage : cpfile <File name> <Protection>


<Protection>: This value could be between 0 and 7. It consists of three bits: read,
write, and execute.

Sample output:

ui[/]> list -all

TYPE SIZE PROT. OWNER NAME


------------------------------------
<FILE> 0 7 1 doc1

Total 1 files and 0 directories

ui[/]> cpfile doc1 3


ui[/]> list -all

TYPE SIZE PROT. OWNER NAME


------------------------------------
<FILE> 0 3 1 doc1

Total 1 files and 0 directories

delfile
This command is used to delete a file.

Usage : delfile <File name>

Sample output:
ui[/]> list

TYPE SIZE NAME


--------------------
<FILE> 0 doc1

Total 1 files and 0 directories

ui[/]> delfile doc1


Delete File? [y/n] : y
ui[/]> list

File or directory not found

writefile
This command appends data to a given file.

23
Operating Systems Project: The File System

Usage : writefile <File name> <Text to write to the file>

Sample output:
ui[/]> writefile file1 This is the content of a file

print
Print command prints the content of a given file to the screen.

Usage : print <File name>

Sample output:
ui[/]> print file1
This is the content of a file

x
This is used to exit the interface.

Usage : x

24
Operating Systems Project: The File System

Appendix B - Class Diagram

25
Operating Systems Project: The File System

Appendix C - Source Code

/*****************************************************************************
* Operating Systems Project: File & Directory System
* Author: Date: May 13th 2003
* Erhan Atilla Avinal
* Maitreya Natu
* Tam H. Vu
* Shivkundan Singh Tej *
* Course: CISC 663 Operating System *
*****************************************************************************
1. Purpose: The porject simulates the file and directory objects of a file
system moddule of an operating system and provides methods for their
manipulation.
2. Inputs: Commands to do operations on file and directories
3. Outputs: The file and directory structure is changed as per the user
instructions
4. Packages Imported:
import java.util.BitSet -- It contains methods to perform bits operations
5. Classes:
DESCRIPTOR
disk
File
FS
Directory
DS
6. Variables:
d -- object of disk class
fileSys -- instance of FS class
dirSys -- instance of DS class
7. Bugs:
None
******************************************************************************/
import java.util.*;
import java.io.*;

/******************************************************************************
class DESCRIPTOR
******************************************************************************
1. Purpose: This class encapsulates the information stored in a descriptor.
2. Data :
1) type: Unused(0), File(1), Directory(2)
2) Size: Length of file or Number of entries in directory
3) block_addresses[]: Array of block addresses occupied by file or directory
3. Methods:
None
******************************************************************************/

class DESCRIPTOR
{
public short type; //0: free, 1: file, 2: directory
public int Size; //size of file/directory
public short block_addresses[]=new short[13];
}//end class DECSRIPTOR

/******************************************************************************
class disk
******************************************************************************
1. Purpose: This class simualtes a formatted disk. It contains the formatting
information of the file system. It provides methods to manipulating the

26
Operating Systems Project: The File System

disk content thus hiding the internal details of lower level bit and byte
manipulation.
2. Data :
BLOCK_SIZE: the size of a logical block
NUMBER_OF_DESCRIPTORS: The maximum number of descriptors that can be created
DESCRIPTOR_SIZE: size of a descriptor
NUMBER_OF_BLOCKS: The maximum number of blocks allowed
MAXIMUM_FILE_SIZE: The maximum file size that can be created

Bitmap: A data structure to store the use/unuse bits for each block on disk
Descriptor_Array: A datastructure to store all the descriptors for files
and directories.
Block_Array: A datastructure to store the logoical blocks where data is
written.

3. Methods:
disk()
formatDisk()
readDescriptor()
writeDescriptor()
readBlock()
writeBlock()
findFreeBlock()
findFreeDescriptor()
******************************************************************************/

class disk
{
int BLOCK_SIZE=512;
int NUMBER_OF_BLOCKS=512;
int DESCRIPTOR_SIZE=32; // 2 + 4 + 26
int NUMBER_OF_DESCRIPTORS=160; //each descriptor occupies 32 Bytes
//10 Blocks reserved for descriptors
//(10*512)/32=160
int MAX_FILE_SIZE=13*BLOCK_SIZE;

BitSet Bitmap=new BitSet(512*8);

DESCRIPTOR Descriptor_Array[] =
new DESCRIPTOR[NUMBER_OF_DESCRIPTORS];

byte Block_Array[][]=new byte[NUMBER_OF_BLOCKS][BLOCK_SIZE];

/*****************************************************************************
disk()
******************************************************************************
1. Purpose: Initialize the Descriptor_Array
2. Inputs : None
3. Return Values: None
4. Functions Calling: main()
5. Functions Called : None
******************************************************************************/
disk()
{
for (int cnt =0; cnt < NUMBER_OF_DESCRIPTORS; cnt++)
Descriptor_Array[cnt]=new DESCRIPTOR();

}//disk()

/*****************************************************************************
formatDisk()
******************************************************************************
1. Purpose: Formats the disk
1) Clears all the bits in Bitmap
2) Initializes the descriptor of root directory
2. Inputs : None
3. Return Values: None
4. Functions Calling: main()
5. Functions Called : None
******************************************************************************/

27
Operating Systems Project: The File System

int formatDisk()
{
//set bits of first block to zeros
for (int cnt =0; cnt < BLOCK_SIZE; cnt++)
Bitmap.clear(cnt);

for (int cnt =0; cnt < NUMBER_OF_DESCRIPTORS; cnt++)


{
Descriptor_Array[cnt].type=0;
Descriptor_Array[cnt].Size=0;
}
/*******************************************
Instantialting the File System
*******************************************/
FDS.fileSys = new FS();

/*******************************************
Instantialting the Directory System
Root Dir is automatically created here
*******************************************/
FDS.dirSys = new DS();

return 1;
}//end formatDisk()

/*****************************************************************************
readDescriptor()
******************************************************************************
1. Purpose: return the required Descriptor
2. Inputs : Descriptor Number
3. Return Values: DESCRIPTOR instance
******************************************************************************/

DESCRIPTOR readDescriptor(int descriptor_number)


{
DESCRIPTOR d= Descriptor_Array[descriptor_number];
return d;
}

/*****************************************************************************
writeDescriptor()
******************************************************************************
1. Purpose: writes the Descriptor
2. Inputs : Descriptor Number, DESCRIPTOR instance
3. Return Values: 1 if successful else 0
******************************************************************************/
int writeDescriptor (int descriptor_number, DESCRIPTOR d)
{
if (descriptor_number < NUMBER_OF_DESCRIPTORS)
{
Descriptor_Array[descriptor_number]=d;
return 1;
}
else
return 0;

/*****************************************************************************
readBlock()
******************************************************************************
1. Purpose: reads a data block into the byte array passed
2. Inputs : Block Number, data to read into
3. Return Values: 1 if successful else 0
******************************************************************************/
int readBlock(int block_number, byte data[])
{
if ((block_number <0)||(block_number>=NUMBER_OF_BLOCKS))
return -1;
else {

28
Operating Systems Project: The File System

for (int cnt=0; cnt < BLOCK_SIZE; cnt++)


data[cnt]=Block_Array[block_number][cnt];

return 1;
}
}//end readBlock()

/*****************************************************************************
writeBlock()
******************************************************************************
1. Purpose: writes a data block
2. Inputs : Block Number, data to write
3. Return Values: 1 if successful else 0
******************************************************************************/

int writeBlock(int block_number, byte data[])


{

if ((block_number <0)||(block_number>=NUMBER_OF_BLOCKS))
return -1;
else {

for (int cnt=0; cnt < BLOCK_SIZE; cnt++)


Block_Array[block_number][cnt]=data[cnt];

Bitmap.set(block_number);
return 1;
}
}//end writeBlock()

/*****************************************************************************
findFreeBlock()
******************************************************************************
1. Purpose: find a free data block
2. Inputs : None
3. Return Values: block number if successful else -1
******************************************************************************/

short findFreeBlock()
{
for (short cnt =0; cnt< NUMBER_OF_BLOCKS;cnt++)
if (Bitmap.get(cnt)==false)
return cnt;
return -1;
}//end findFreeBlock()

/*****************************************************************************
findFreeDescriptor()
******************************************************************************
1. Purpose: find a free descriptor
2. Inputs : None
3. Return Values: descriptor number if successful else -1
******************************************************************************/

int findFreeDescriptor()
{
for (int cnt =0; cnt < NUMBER_OF_DESCRIPTORS; cnt++)
{
if (Descriptor_Array[cnt].type==0)
return cnt;
}
return -1;
}//end findFreeDescriptor()

}//end of class disk

/******************************************************************************
class File
******************************************************************************
1. Purpose: This class encapsulates the information about a file.

29
Operating Systems Project: The File System

2. Data :
1) Name: name of the file
2) Descriptor_Number: descriptor number of the file
3) Current_Position: Position of the read write pointer
4) Location : The directory in which the file is stored
5) Owner: User ID of the owner of the file
6) Protection: Protection Bits of the file (7 = rwx)
7) Use: Status about the current usage of the file
3. Methods:
1) printFile()
******************************************************************************/

class File
{
public String Name;
public int Descriptor_Number;
int Current_Position;
Directory Location;
public int Owner;
public int Protection;
int Use;

/*****************************************************************************
printFile()
******************************************************************************
1. Purpose: To print the system information of the file.
2. Inputs: None
3. Return Values: None
******************************************************************************/

void printFile()
{
System.out.println ("****************************************");
System.out.println ("File Name : "+ Name);
System.out.println ("Descriptor No : "+ Descriptor_Number);
System.out.println ("Current_Position: "+ Current_Position);
System.out.println ("Owner : "+ Owner);
System.out.println ("Protection : "+ Protection);
System.out.println ("****************************************");
}
}//end class File

/******************************************************************************
class FS
******************************************************************************
1. Purpose: This class provides tools to manipulate files.
2. Data :
None.
3. Methods:
1) createFile()
2) openFile()
3) readFile()
4) writeFile()
5) rewind()
6) changeProtection()
******************************************************************************/

class FS
{

static File createFile(String file_name, int owner, Directory location,


int protection)
{
//check if the file with given name
//already exists in the current directory
File f = DS.findFile_local(location, file_name);
if (f.Name != null)
{

30
Operating Systems Project: The File System

System.out.println("file already exists !!!");


return f;
}
File new_file= new File();

new_file.Name=file_name;

int dnum=FDS.d.findFreeDescriptor();

//if mo free deescriptor


if (dnum == -1)
{
System.out.println ("Disk Full!!!");
new_file.Descriptor_Number=-1;
return new_file;
}
else
{
new_file.Descriptor_Number=dnum;
new_file.Current_Position=0;
DESCRIPTOR newD = new DESCRIPTOR();
newD.type=1;
newD.Size=0;
FDS.d.writeDescriptor(dnum, newD);

//ask for current directory


new_file.Location=location;

new_file.Owner=owner;
new_file.Protection=protection;

//enter the file in current directory


DS.addFile(new_file);

return new_file;
}
}//end createFile()

static File openFile (String name)


{
//get current directory
//Directory cur_dir = Directory.getCurrentDirectory();

//ask for filedescriptor


File opened_file = DS.findFile_local(DS.currentDir,name);

if (opened_file.Name==null)
System.out.println ("File Not Found");

return opened_file;

}//end openfile()

static int readFile(File fd, int number_of_bytes, byte[] data)


{
int descriptor_no=fd.Descriptor_Number;

DESCRIPTOR fdes=new DESCRIPTOR();


fdes = FDS.d.readDescriptor(descriptor_no);

int pos = fd.Current_Position;

//if file has insufficient data


if ((pos+number_of_bytes) > fdes.Size)
{
number_of_bytes=fdes.Size-pos;
}

int block_no_index = pos / FDS.d.BLOCK_SIZE;


int current_block_no=fdes.block_addresses[block_no_index];

31
Operating Systems Project: The File System

int offset = pos % FDS.d.BLOCK_SIZE;

int cnt=0;
byte block_content[]=new byte[FDS.d.BLOCK_SIZE];
FDS.d.readBlock(current_block_no,block_content);
for (int cnt2=offset;((cnt2<FDS.d.BLOCK_SIZE)&&(number_of_bytes-- >
0));cnt2++)
{
data[cnt++]=block_content[cnt2];
}

while (number_of_bytes > 0)


{

current_block_no=fdes.block_addresses[++block_no_index];
for (int cnt2=0;((cnt2<FDS.d.BLOCK_SIZE)&&(number_of_bytes-- > 0));cnt2++)
{
data[cnt++]=block_content[cnt2];
}

fd.Current_Position+=number_of_bytes;
return cnt;
}//end of readfile

static int writeFile(File fd, int number_of_bytes, byte[] data)


{
int descriptor_no=fd.Descriptor_Number;

DESCRIPTOR fdes=new DESCRIPTOR();


fdes = FDS.d.readDescriptor(descriptor_no);
/* if (stat == -1)
{
System.out.println("Invalid File");
return -1;

}
*/ int pos = fdes.Size;

if ((pos+number_of_bytes) > FDS.d.MAX_FILE_SIZE)


{
System.out.println ("File Size Exceeded!");
return -1;
}

int block_no_index = pos / FDS.d.BLOCK_SIZE;


int current_block_no=fdes.block_addresses[block_no_index];
int offset = pos % FDS.d.BLOCK_SIZE;
if (fdes.Size==0)
current_block_no=-1;
int cnt2=0;

if (offset != 0) //partailly filled last block


{
byte[] block_data=new byte[FDS.d.BLOCK_SIZE];
int status = FDS.d.readBlock (current_block_no, block_data);

if (status == -1) //error while reading


return status;

for (int cnt1=offset;


((cnt1<FDS.d.BLOCK_SIZE)&&(cnt2 < number_of_bytes));
cnt1++,cnt2++)
block_data[cnt1]=data[cnt2];

FDS.d.writeBlock(current_block_no,block_data);
}//if (offset != 0)

while (cnt2 < number_of_bytes) //the current block if filled

32
Operating Systems Project: The File System

//and still data is remaining


{
short new_block_no = FDS.d.findFreeBlock();
fdes.block_addresses[++current_block_no]=new_block_no;
byte[] block_data=new byte[FDS.d.BLOCK_SIZE];

for (int cnt =0;


((cnt< FDS.d.BLOCK_SIZE)&&(cnt2 < number_of_bytes));
cnt++,cnt2++)
block_data[cnt]=data[cnt2];

FDS.d.writeBlock(new_block_no, block_data);

}//while (cnt2 < number_of_bytes)

fdes.Size+=number_of_bytes;
return number_of_bytes;
}//end writeFile()

public static void rewind(File fd)


{
fd.Current_Position=0;
}

public static File copyFile(String originalName, String newName)


{
File f1= FS.openFile(originalName);
File f2= FS.createFile(newName, 4, DS.currentDir, 7);
DESCRIPTOR tempD = new DESCRIPTOR();
tempD=FDS.d.readDescriptor(f1.Descriptor_Number);
byte data[]=new byte[tempD.Size];
readFile(f1, tempD.Size, data);
writeFile(f2, tempD.Size, data);
return f2;
}

public static void changeProtection(File fd, int protectionBits)


{
fd.Protection=protectionBits;
//Call to Directory Class to change file protection
//Change file protection (fd, protectionBits)
DS.changeProtection (fd.Name, protectionBits);
}

public static void renameFile (File fd, String newName)


{

int block_number =
FDS.d.Descriptor_Array[DS.currentDir.Descriptor_Number].block_addresses[0];
int size = FDS.d.Descriptor_Array[DS.currentDir.Descriptor_Number].Size;
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];
FDS.d.readBlock(block_number, data);
if (size!=0)
{
for (int i=0;i<16;i++)
{
int j=i*32;
for (int k=0;k<26;k++)
data_name[k] = data[k+j];
String str = new String(data_name);
str = str.trim();
int c = str.compareTo(fd.Name);

if ((c==0) && (FDS.d.Descriptor_Array[data[j+26]].type == 1)) //found


{
for (int k=0;k<26;k++)
data[k+j] = 0;

33
Operating Systems Project: The File System

for (int k=0;k<newName.length();k++)


data[k+j] = (byte)newName.charAt(k);

FDS.d.writeBlock(block_number, data);
fd.Name = newName;
/*file.Name = newName.trim();
file.Descriptor_Number = data[j+26];
file.Protection = data[j+30];
file.Owner = data[j+31];*/
}
}
}

//Call to Directory to change the name entry of the file


//renameFile(fd, newName);
//or
//renameFile(fd.Name, newName);
fd.Name= newName;

static int deleteFile(String file_name)


{
//check if the file with given name
//exists in the current directory
File f = DS.findFile_local(DS.currentDir, file_name);
if (f.Name == null)
{
System.out.println("file does not exist !!!");
return 0;
}
else
{
DESCRIPTOR tempD=new DESCRIPTOR();
tempD.type=0;
tempD.Size=0;
FDS.d.writeDescriptor(f.Descriptor_Number, tempD);
//Call to the directory class to remove the file entry from current dir
//removeFile(file_name);
}
return 1;
}
}//class FS

class Directory
{
public String Name;
public int Block_Number;
public int Descriptor_Number;
public Directory Parent;
public int Protection;
public int Children;
public int Owner;

void printDirectory()
{
System.out.println ("****************************************");
System.out.println ("Directory Name : "+ Name);
System.out.println ("Descriptor No : "+ Descriptor_Number);
System.out.println ("No. of children : "+ Children);
System.out.println ("Owner : "+ Owner);
System.out.println ("Protection : "+ Protection);
System.out.println ("****************************************");
}
}

class DS
{
static String currentPath;

34
Operating Systems Project: The File System

static Directory currentDir;


DS(){
currentDir = new Directory();
currentDir.Name="/";
currentDir.Descriptor_Number = 0;
currentDir.Children=0;
currentDir.Parent = null;
currentDir.Protection = 7;
FDS.d.Descriptor_Array[0].type = 2;
}

static Directory createDir (String dir_name, byte owner, Directory location, byte
protection)
{
byte data[] = new byte[FDS.d.BLOCK_SIZE];

Directory new_dir = new Directory();


new_dir.Name = dir_name;
int dnum = FDS.d.findFreeDescriptor();

//if no free deescriptor


if (dnum == -1)
{
System.out.println ("Disk Full!!!");
new_dir.Descriptor_Number=-1;
return new_dir;
}
else
{
String s = findDirectory_local(location, dir_name).Name;

if (s != null)
{
System.out.println ("Directory name already exists!!!");
new_dir.Descriptor_Number=-1;
return new_dir;
}else
{
int parent_dnum = location.Descriptor_Number;

DESCRIPTOR parent_desc = FDS.d.readDescriptor(parent_dnum);

int children = location.Children;


int block_number;
if (children==0)
{
block_number = FDS.d.findFreeBlock();
}
else
block_number= FDS.d.Descriptor_Array[parent_dnum].block_addresses[0];

FDS.d.readBlock(block_number, data);
byte [] b = dir_name.getBytes();
for (int i=0;i<dir_name.length();i++){
data[children*32+i]=b[i];
}

data[children*32+26] = (byte)dnum;
data[children*32+30] = protection;
data[children*32+31] = owner;

FDS.d.writeBlock(block_number, data);
// parent_desc.Size++;

FDS.d.Descriptor_Array[parent_dnum].Size++;
FDS.d.Descriptor_Array[parent_dnum].block_addresses[0] = (byte)block_number;

// FDS.d.writeDescriptor(parent_dnum, parent_desc);

35
Operating Systems Project: The File System

FDS.d.Descriptor_Array[dnum].type = 2;
FDS.d.Descriptor_Array[dnum].Size = 0;

// FDS.d.Bitmap.set(dnum);

new_dir.Block_Number = block_number;
new_dir.Descriptor_Number = dnum;
new_dir.Owner = owner;
new_dir.Protection = protection;
new_dir.Parent = location;
location.Children++;

return new_dir;
}
}
}// end createDir()

static int renameDirectory(Directory dir, String new_name)


{
String str_name = dir.Name;
int block_number = dir.Block_Number;
byte data[] = new byte[FDS.d.BLOCK_SIZE];
FDS.d.readBlock(block_number, data);
byte data_name[] = new byte[26];
for (int i=0;i<dir.Parent.Children;i++)
{
int j=i*32;
for (int k=0;k<26;k++)
data_name[k] = data[k+j];
String str = new String(data_name);
str = str.trim();
int c = str.compareTo(str_name);
if (c==0) //found
{
byte [] b = new_name.getBytes();
for (int k=0;k<new_name.length();k++)
data[k+i*32]=b[k];
FDS.d.writeBlock(dir.Block_Number, data);

}
}
return 1;
} //rename directory

static int changeDirectory(String new_path)


{
int i = 0;
Directory new_dir = findDirectory(new_path);
int c = new_dir.Name.compareTo("");
if (c == 0)
i = -1;
else
{
currentDir = new_dir;
i = 1;
}
return i;
}

static void changeProtection(String name, int protection)


{
int block_number =
FDS.d.Descriptor_Array[currentDir.Descriptor_Number].block_addresses[0];
byte data[] = new byte[FDS.d.BLOCK_SIZE];
FDS.d.readBlock(block_number,data);
byte data_name[] = new byte[26];
for (int i=0;i<currentDir.Children;i++)
{
int j=i*32;
for (int k=0;k<26;k++)
data_name[k] = data[k+j];

36
Operating Systems Project: The File System

String str = new String(data_name);


str = str.trim();
int c = str.compareTo(name);
if (c==0) //found
{
data[j+30] = (byte)protection;
FDS.d.writeBlock(block_number, data);

}
}

}
static int moveDirectory(Directory dir, String new_path)
{
Directory new_parent = findDirectory(new_path);

if (new_parent.Name == null)
{
System.out.println (new_path +" is not a valid path");
return -1;
}
else
{
int old_block_number =
FDS.d.Descriptor_Array[dir.Parent.Descriptor_Number].block_addresses[0];
int new_block_number = 0;
if (new_parent.Children ==0)
{
new_block_number = FDS.d.findFreeBlock();
FDS.d.Bitmap.set(new_block_number);
FDS.d.Descriptor_Array[new_parent.Descriptor_Number].block_addresses[0]
= (byte)new_block_number;
}
else
new_block_number =
FDS.d.Descriptor_Array[new_parent.Descriptor_Number].block_addresses[0];
byte data[] = new byte[FDS.d.BLOCK_SIZE];
String dir_name = dir.Name;
FDS.d.readBlock(new_block_number, data);
int size = new_parent.Children;
byte [] b = dir_name.getBytes();
for (int i=0;i<dir_name.length();i++)
{
data[size*32+i]=b[i];
}
data[size*32+26] = (byte)dir.Descriptor_Number;
data[size*32+30] = (byte)dir.Protection;
data[size*32+31] = (byte)dir.Owner;
FDS.d.writeBlock(new_block_number, data);

FDS.d.readBlock(old_block_number, data);
byte data_name[] = new byte[26];
size = dir.Parent.Children;
if (size !=0)
{
for (int i=0;i<16;i++)
{
int j=i*32;
for (int k=0;k<26;k++)
data_name[k] = data[k+j];
String str = new String(data_name);
str = str.trim();
int c = str.compareTo(dir_name);
if (c==0) //found
{
for (int k=0;k<26;k++)
data[k+i*32]=0;
FDS.d.writeBlock(old_block_number, data);
}
}
}

37
Operating Systems Project: The File System

// dir.Block_Number = new_block_number;
dir.Parent = new_parent;
new_parent.Children++;
FDS.d.Descriptor_Array[new_parent.Descriptor_Number].Size++;
return 1;
}
}// moveDirectory()

static int deleteDirectory(Directory dir)


{
if (dir.Children > 0)
{
System.out.println ("Directory not empty");
return -1;
}
else
{
// int parent_dnum = dir.Parent_Descriptor_Number;
int dnum = dir.Descriptor_Number;
Directory parent_dir = dir.Parent;
parent_dir.Children--;
FDS.d.Descriptor_Array[parent_dir.Descriptor_Number].Size--;

byte data[] = new byte[FDS.d.BLOCK_SIZE];


byte data_name[] = new byte[26];
int block_number =
FDS.d.Descriptor_Array[dir.Descriptor_Number].block_addresses[0];
FDS.d.Bitmap.set(block_number);
FDS.d.Descriptor_Array[dir.Descriptor_Number].type =0;
FDS.d.readBlock(dir.Block_Number, data);

int i=0;
while (i<FDS.d.BLOCK_SIZE)
{
for (int k=0;k<26;k++)
data_name[k] = data[k+i];
String str = new String(data_name);
str=str.trim();
int c = str.compareTo(dir.Name);
if (c==0) //found
{
// delete name
for (int k=0;k<26;k++)
data[k+i]=0;
FDS.d.writeBlock(dir.Block_Number, data);
return 1;
}
else i=i+32;
}
}
return 1;
}// end deleteDirectory()

/* getFile() */

public static File findFile_local(Directory location, String file_name)


// search for directory with name dir_name within directory location
// returns directory object. If fails, object contains all nulls
{
File file = new File();
int block_number =
FDS.d.Descriptor_Array[location.Descriptor_Number].block_addresses[0];
int size = FDS.d.Descriptor_Array[location.Descriptor_Number].Size;
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];
FDS.d.readBlock(block_number, data);
if (size!=0)
{
for (int i=0;i<16;i++)
{
int j=i*32;

38
Operating Systems Project: The File System

for (int k=0;k<26;k++)


data_name[k] = data[k+j];
String str = new String(data_name);
str = str.trim();
int c = str.compareTo(file_name);

if ((c==0) && (FDS.d.Descriptor_Array[data[j+26]].type == 1)) //found


{
file.Name = str;
file.Descriptor_Number = data[j+26];
file.Protection = data[j+30];
file.Owner = data[j+31];
}
}
}
return file;
}

static Directory findDirectory(String dir_name)


// find directory with name dir_name in the directory system
// currently supports only full path (/dir1/dir2), or current directory (i.e, if
current dir is dir1,
// dir_name to be sought is "dir2/dir3", it searchs only in dir1
{

Directory dir = new Directory();


Directory dir2 = new Directory();
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];

if (dir_name.equals("/"))
{
DESCRIPTOR root_desc = FDS.d.readDescriptor(0);
dir.Name="/";
dir.Descriptor_Number = 0;
dir.Parent = null;
dir.Children = root_desc.Size;
dir.Block_Number = root_desc.block_addresses[0];
dir.Protection = 7;
return dir;
}

int index = dir_name.indexOf('/');


int index2 = 0;
String str2 = new String();
String str_name = new String();
if (index >=0) // found
{
Directory loc = new Directory();
if (index ==0)
{
DESCRIPTOR root_desc = FDS.d.readDescriptor(0);
loc.Name="/";
loc.Descriptor_Number = 0;
loc.Parent = null;
loc.Children = root_desc.Size;
loc.Block_Number = root_desc.block_addresses[0];
str_name = dir_name;
}
else
{
loc = currentDir;
str_name = "/"+dir_name;
}
index = str_name.indexOf('/');
while (index >=0)
{
index2 = index;
index = str_name.indexOf('/', index+1);
if (index >=0){

39
Operating Systems Project: The File System

str2 = str_name.substring(index2+1, index);


}
else
str2 = str_name.substring(index2+1, str_name.length());

dir2 = findDirectory_local(loc, str2);


// if ((int c= dir2.Name.compareTo("")) == 0)
// return dir;
// else //found
if (index >= 0)
loc = dir2;
else
dir = dir2;
}
}
else
dir = findDirectory_local(currentDir, dir_name);
return dir;
}
public static Directory findDirectory_local(Directory location, String dir_name)
// search for directory with name dir_name within directory location
// returns directory object. If fails, object contains all nulls
{
Directory dir = new Directory();
int block_number =
FDS.d.Descriptor_Array[location.Descriptor_Number].block_addresses[0];
int size = FDS.d.Descriptor_Array[location.Descriptor_Number].Size;
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];
FDS.d.readBlock(block_number, data);
if (size !=0)
{
for (int i=0;i<16;i++)
{
int j=i*32;
for (int k=0;k<26;k++)
data_name[k] = data[k+j];
String str = new String(data_name);
str = str.trim();
int c = str.compareTo(dir_name);

if ((c==0) && (FDS.d.Descriptor_Array[data[j+26]].type == 2)) //found


{
dir.Name = str;
dir.Descriptor_Number = data[j+26];
dir.Parent = location;
dir.Protection = data[j+30];
dir.Owner = data[j+31];
dir.Children = FDS.d.Descriptor_Array[data[j+26]].Size;
}
}
}
return dir;
}

static Directory getCurrentPath()


{
return currentDir;
}
public static int printCurrentPath()
{
System.out.println (currentDir.Name);
return 1;
}

// static int listDir (String dir_name)


static int listDir (Directory location)
{
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];

40
Operating Systems Project: The File System

int size = location.Children;


// int size = 2;
// Directory current_dir = getCurrentDir();
int block_number =
FDS.d.Descriptor_Array[location.Descriptor_Number].block_addresses[0];

FDS.d.readBlock(block_number, data);
System.out.println ("Current directory:"+location.Name);

System.out.println ("No of children :"+size);


System.out.println ("**********************************");
System.out.println ("Type Name dnum protection owner");

for (int cnt=0;cnt<size;cnt++){


//print name
for (int k=0;k<26;k++)
data_name[k] = data[k+cnt*32];
String str = new String(data_name);
str=str.trim();
int c = str.compareTo("");
if (c != 0)
{
int n=0;
int j=cnt*32+26;

n=data[j];
//print type
System.out.print (FDS.d.Descriptor_Array[n].type+" ");
//print name
System.out.print (str);
System.out.print (" ");

//print descriptor number


System.out.print (n+" ");

//print protection
System.out.print (data[j+4]+" ");
//print owner
System.out.println (data[j+5]);
}
}
return 1;
}//listDirectory()

static int listDir (Directory location , ArrayList dirs , ArrayList files )


{
byte data[] = new byte[FDS.d.BLOCK_SIZE];
byte data_name[] = new byte[26];
int size = location.Children;
Directory dir;
File f;
int block_number =
FDS.d.Descriptor_Array[location.Descriptor_Number].block_addresses[0];

FDS.d.readBlock(block_number, data);
/*
System.out.println ("Current directory:"+location.Name);
System.out.println ("No of children :"+size);
System.out.println ("**********************************");
System.out.println ("Type Name dnum protection owner");
*/
if (size!=0)
{
for (int cnt=0;cnt<16;cnt++){
//print name
for (int k=0;k<26;k++)
data_name[k] = data[k+cnt*32];

String str = new String(data_name);


str=str.trim();
int c = str.compareTo("");

41
Operating Systems Project: The File System

if (c != 0)
{
int n=0;
int j=cnt*32+26;

n=data[j];
//print type
if (FDS.d.Descriptor_Array[n].type == 1){
f = new File();
f.Name = str;
f.Protection = data[j+4];
f.Owner = data[j+5];
f.Descriptor_Number = n;
files.add(f);
}
else{
dir = new Directory();
dir.Name = str;
dir.Protection = data[j+4];
dir.Owner = data[j+5];
dirs.add(dir);
}
/* System.out.print (FDS.d.Descriptor_Array[n].type+" ");
//print name
System.out.print (str);
System.out.print (" ");

//print descriptor number


System.out.print (n+" ");

//print protection
System.out.print (data[j+4]+" ");
//print owner
System.out.println (data[j+5]); */
}
}
}
return 1;
}//listDirectory()

static int addFile (File file)


{
byte data[] = new byte[FDS.d.BLOCK_SIZE];
int size = currentDir.Children;
int block_number;

if(size==0)
{
block_number=FDS.d.findFreeBlock();
}
else
block_number =
FDS.d.Descriptor_Array[currentDir.Descriptor_Number].block_addresses[0];

FDS.d.readBlock(block_number,data);

byte data_name[] = file.Name.getBytes();


for (int i=0;i<file.Name.length();i++)
{
data[i+size*32] = data_name[i];
}
data[size*32+26] = (byte)file.Descriptor_Number;
data[size*32+30] = (byte)file.Protection;
data[size*32+31] = (byte)file.Owner;
FDS.d.writeBlock(block_number,data);
currentDir.Children++;
FDS.d.Descriptor_Array[currentDir.Descriptor_Number].Size++;
FDS.d.Descriptor_Array[currentDir.Descriptor_Number].block_addresses[0] =
(byte)block_number;
return 1;

42
Operating Systems Project: The File System

}//addFile()
static int deleteFile(File file)
{
int dnum = file.Descriptor_Number;
Directory parent_dir = currentDir;
parent_dir.Children--;

FDS.d.Descriptor_Array[parent_dir.Descriptor_Number].Size--;

byte data[] = new byte[FDS.d.BLOCK_SIZE];


byte data_name[] = new byte[26];
int block_number =
FDS.d.Descriptor_Array[parent_dir.Descriptor_Number].block_addresses[0];
// FDS.d.Bitmap.set(block_number);

FDS.d.Descriptor_Array[file.Descriptor_Number].type =0;
for (int j=0;j<13;j++)

FDS.d.Bitmap.clear(FDS.d.Descriptor_Array[file.Descriptor_Number].block_addresses[j]);

FDS.d.readBlock(block_number, data);

int i=0;
while (i<FDS.d.BLOCK_SIZE)
{
for (int k=0;k<26;k++)
data_name[k] = data[k+i];
String str = new String(data_name);
str=str.trim();
int c = str.compareTo(file.Name);
if (c==0) //found
{
// delete name
for (int k=0;k<26;k++)
data[k+i]=0;
FDS.d.writeBlock(block_number, data);
return 1;
} else i=i+32;
}
return 1;
}// end deleteFile()

class Command{
public String name;
public ArrayList parameters;
public ArrayList options;
public int error = 0;
public String errormessage;

public Command(String str){


StringTokenizer st = new StringTokenizer(str , " ");
String s;

parameters = new ArrayList();


options = new ArrayList();

if (st.hasMoreTokens()){
name = st.nextToken();
}
while (st.hasMoreTokens()){
s = st.nextToken();
if (s.charAt(0)=='-')
options.add(s);
else{
parameters.add(s);

43
Operating Systems Project: The File System

}
}
}
public String getParameter(int i){
if (parameters.size()>0)
return (String)parameters.get(i);
else
return "";
}
}

class GUI{

//Directory CurrentDir;
DS dirSys;
FS fileSys;
disk d;
byte OWNER_UI = 1;
byte PROTECTION_UI = 7;
int MAXBYTE = 32767;

// file functions
public GUI(DS ds , FS fs , disk dsk){
dirSys = ds;
fileSys = fs;
d = dsk;
}
void error(String err){
System.out.println(err);
}
char confirm(String str){
char c = ' ';
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.print(str + " : ");
c = reader.readLine().charAt(0);

}
catch(Exception e){
}
return c;
}

void printCommandPromt(){
System.out.print("ui["+ dirSys.currentDir.Name +"]> ");
}

private int renameFile(ArrayList parameters){


File f;

if (parameters.size()<2){
if (parameters.size()==0){
error("Usage : rnfile <File name> <New file name>");
return -1;
}
error("Not enough parameters");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(1));
if (f.Name != null){
error("Target file already exists");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("File does not exist");
return -1;
}

44
Operating Systems Project: The File System

fileSys.renameFile(f ,(String)parameters.get(1) );
return 0;
}

private int deleteFile(ArrayList parameters){


File f;

if (parameters.size()==0){
error("Usage : delfile <File name>");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("File does not exist");
return -1;
}
if (f.Protection != 2 && f.Protection != 3 && f.Protection != 6 &&
f.Protection != 7 ){
error("Protection error.");
return -1;
}

if (confirm("Delete File? [y/n]")=='y'){


dirSys.deleteFile(f);
}

return 0;
}
private int createFile(ArrayList parameters){
File f;

if (parameters.size()==0){
error("Usage : createfile <File name>");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name != null){
error("File already exists");
return -1;
}

fileSys.createFile((String)parameters.get(0),OWNER_UI,dirSys.currentDir,PROTECTION_UI);
return 0;
}

private int changeFileProtection(ArrayList parameters){


File f;

if (parameters.size()==0){
error("Usage : cpfile <File name> <Protection>");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("File does not exist");
return -1;
}
fileSys.changeProtection(f,Integer.parseInt((String)(parameters.get(1))));
return 0;
}

private int printFile(ArrayList parameters){


File f;
byte[] buffer = new byte[MAXBYTE];
int n;

if (parameters.size()==0){

45
Operating Systems Project: The File System

error("Usage : print <File name>");


return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("File does not exist");
return -1;
}
if (f.Protection < 4 ){
error("Protection error.");
return -1;
}
n = fileSys.readFile(f,MAXBYTE,buffer);
System.out.write(buffer,0,n);
System.out.println("");
return 0;
}

private int copyFile(ArrayList parameters){


File f;

if (parameters.size()<2){
if (parameters.size()==0){
error("Usage : copy <File name> <New file name>");
return -1;
}
error("Not enough parameters");
return -1;
}
f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(1));
if (f.Name != null){
error("Target file already exists");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("Source file does not exist");
return -1;
}
fileSys.copyFile( f.Name, (String)parameters.get(1));
return 0;
}

// directory functions
private int moveDir(ArrayList parameters){
Directory dir;

if (parameters.size()<2){
if (parameters.size()==0){
error("Usage : movedir <Directory name> <New directory name>");
return -1;
}
error("Not enough parameters");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(1));
if (dir.Name == null){
error("Target directory does not exist");
return -1;
}

if ( dir.Protection != 2 && dir.Protection != 3 && dir.Protection != 6 &&


dir.Protection != 7 ){
error("Target directory protection error.");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));

46
Operating Systems Project: The File System

if (dir.Name == null){
error("Source directory does not exist");
return -1;
}

dirSys.moveDirectory(dir,(String)parameters.get(1));
return 0;
}

private int renameDir(ArrayList parameters){


Directory dir;

if (parameters.size()<2){
if (parameters.size()==0){
error("Usage : rndir <Directory name> <New directory name>");
return -1;
}
error("Not enough parameters");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(1));
if (dir.Name != null){
error("Target directory already exists");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));
if (dir.Name == null){
error("Directory does not exist");
return -1;
}

dirSys.renameDirectory(dir ,(String)parameters.get(1) );
return 0;
}

private int deleteDir(ArrayList parameters){


Directory dir;

if (parameters.size()==0){
error("Usage : deldir <Directory name>");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));
if (dir.Name == null){
error("Directory does not exist");
return -1;
}

if ( dir.Protection != 2 && dir.Protection != 3 && dir.Protection != 6 &&


dir.Protection != 7 ){
error("Protection error.");
return -1;
}

if (confirm("Delete Directory? [y/n]")=='y'){


dirSys.deleteDirectory(dir);
}
else{
System.out.println("Directory not deleted");
}
return 0;
}

private int appendFile(ArrayList parameters){


File f;
byte[] buffer = new byte[MAXBYTE];

47
Operating Systems Project: The File System

int n;
String str;

if (parameters.size()==0){
error("Usage : writefile <File name> <Text to write to the file>");
return -1;
}

f = dirSys.findFile_local(dirSys.currentDir,(String)parameters.get(0));
if (f.Name == null){
error("File does not exist");
return -1;
}

if (f.Protection != 2 && f.Protection != 3 && f.Protection != 6 &&


f.Protection != 7 ){
error("Protection error.");
return -1;
}
str = new String();
for (n=1;n<parameters.size() ;n++ ){
if (n==parameters.size()-1){
str = str + (String)parameters.get(n);
}
else
str = str + (String)parameters.get(n) + " ";
}
buffer = str.getBytes();
n = fileSys.writeFile(f,str.length(),buffer);
return 0;
}

private int createDir(ArrayList parameters){


Directory dir;

if (parameters.size()==0){
error("Usage : makedir <Directory name> ");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));
if (dir.Name != null){
error("Directory already exists");
return -1;
}

if ( dirSys.currentDir.Protection != 2 && dirSys.currentDir.Protection != 3


&& dirSys.currentDir.Protection != 6 && dirSys.currentDir.Protection !=
7 ){
error("Protection error.");
return -1;
}

dirSys.createDir((String)parameters.get(0),OWNER_UI,FDS.dirSys.currentDir,PROTECTION_UI);
return 0;
}

private int changeDirProtection(ArrayList parameters){


Directory dir;

if (parameters.size()==0){
error("Usage : cpdir <Directory name> <Protection>");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));
if (dir.Name == null){
error("Directory does not exist");
return -1;

48
Operating Systems Project: The File System

dirSys.changeProtection(dir.Name,Integer.parseInt((String)(parameters.get(1))));
return 0;
}

private int changeDir(ArrayList parameters){


Directory dir;

if (parameters.size()==0){
error("Usage : cd <Directory name>");
return -1;
}

dir = dirSys.findDirectory((String)parameters.get(0));
if (dir.Name == null){
error("Directory does not exist");
return -1;
}
if ( dir.Protection <4 ){
error("Protection error.");
return -1;
}

dirSys.changeDirectory((String)parameters.get(0));
return 0;
}

private int listDir(String dirname,ArrayList options){


Directory dir;
ArrayList dirs = new ArrayList();
ArrayList files = new ArrayList();
int nfile = 0;
int ndir = 0;
int i;

if (dirname == "")
dir = dirSys.currentDir;
else
dir = dirSys.findDirectory(dirname);
if (dir.Name == null){
error("Directory not found : " + dirname);
return -1;
}
if ( dir.Protection <4 ){
error("Protection error.");
return -1;
}

dirSys.listDir(dir,dirs , files);
if (dirs.size()==0 && files.size() ==0){
System.out.println("");
System.out.println("File or directory not found");
System.out.println("");
return 0;
}
System.out.println("");
System.out.print("TYPE");
System.out.print("\tSIZE");
if (options.indexOf("-all")!=-1){
System.out.print("\tPROT.");
System.out.print("\tOWNER");
}
System.out.print("\tNAME");
System.out.println("");
if (options.indexOf("-all")!=-1)
System.out.print("------------------------------------");
else
System.out.print("--------------------");
System.out.println("");
if (options.indexOf("-of")==-1){

49
Operating Systems Project: The File System

ndir = dirs.size();

for (i=0;i<dirs.size();i++ ){
System.out.print(" <DIR>\t");
if (options.indexOf("-all")!=-1){
System.out.print("\t" +((Directory)dirs.get(i)).Protection);
System.out.print("\t" +((Directory)dirs.get(i)).Owner);
}
System.out.print("\t" +((Directory)dirs.get(i)).Name);
System.out.println("");
}
}
if (options.indexOf("-od")==-1){
nfile = files.size();
for (i=0;i<files.size();i++ ){
System.out.print("<FILE>");
System.out.print(" "
+d.Descriptor_Array[((File)files.get(i)).Descriptor_Number].Size);
if (options.indexOf("-all")!=-1){
System.out.print("\t" +((File)files.get(i)).Protection);
System.out.print("\t" +((File)files.get(i)).Owner);
}
System.out.print("\t" +((File)files.get(i)).Name);
System.out.println("");
}
}
System.out.println("");
System.out.println("Total " + nfile + " files and " + ndir + " directories");
System.out.println("");

return 0;
}

private int createLink(String linkname, String dirname){


return 0;
}

// other functions
private int clearScreen(){
return 0;
}

private int formatDisk(){


if (confirm("All information on the disk will be deleted permanently. Are you
sure? [y/n]")=='y'){
//System.out.println(d.findFreeBlock());
d.formatDisk();
dirSys.changeDirectory("/");
//System.out.println(d.findFreeBlock());
System.out.println("Format finished");
}
else{
System.out.println("Format canceled");
}
return 0;

}
private void showHelp(){
System.out.println("");
System.out.println("format - Formats the disk");
System.out.println("list - Lists the contents of the directories");
System.out.println("cd - Changes directory");
System.out.println("makedir - Creates a new directory");
System.out.println("movedir - Moves a directory");
System.out.println("rndir - Renames a directory");
System.out.println("cpdir - Changes the protection of a directory");
System.out.println("deldir - Deletes a directory");
System.out.println("createfile - Creates a new file");
System.out.println("copy - Copies a file");
System.out.println("rnfile - Renames a file");
System.out.println("cpfile - Changes the protection of a file");

50
Operating Systems Project: The File System

System.out.println("delfile - Deletes a file");


System.out.println("print - Prints the content of a file");
System.out.println("writefile - Writes to a file");
System.out.println("x - exits the interface");
System.out.println("");

void run(){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

String s ;
Command c;
while (true){
try{
printCommandPromt();
s = reader.readLine();
c = new Command(s);
if (c.error != 0){
System.out.println(c.errormessage);
}

if (c.name.compareTo("format")==0){
formatDisk();
}
else if (c.name.compareTo("list")==0){
listDir(c.getParameter(0) , c.options);
}
/****** Directory related operations ******/
else if (c.name.compareTo("cd")==0){
changeDir(c.parameters);
}
else if (c.name.compareTo("makedir")==0){
createDir(c.parameters);
}
else if (c.name.compareTo("movedir")==0){
moveDir(c.parameters);
}
else if (c.name.compareTo("rndir")==0){
renameDir(c.parameters);
}
else if (c.name.compareTo("cpdir")==0){
changeDirProtection(c.parameters);
}
else if (c.name.compareTo("deldir")==0){
deleteDir(c.parameters);
}
/****** File related operations ******/

else if (c.name.compareTo("createfile")==0){
createFile(c.parameters);
}
else if (c.name.compareTo("copy")==0){
copyFile(c.parameters);
}
else if (c.name.compareTo("rnfile")==0){
renameFile(c.parameters);
}
else if (c.name.compareTo("cpfile")==0){
changeFileProtection(c.parameters);
}
else if (c.name.compareTo("delfile")==0){
deleteFile(c.parameters);
}
else if (c.name.compareTo("print")==0){
printFile(c.parameters);
}
else if (c.name.compareTo("writefile")==0){
appendFile(c.parameters);
}
/******** Exit *******/

51
Operating Systems Project: The File System

else if (c.name.compareTo("help")==0){
showHelp();
}
else if (c.name.compareTo("x")==0){
return;
}
else{
error("Command not found");
}
}
catch(Exception e){
}
}
}
}

public class FDS


{
public static disk d;
public static FS fileSys;
public static DS dirSys;

public static void main (String args[])


{
d = new disk();
d.formatDisk();

GUI gui = new GUI(dirSys,fileSys,d);


gui.run();
}

52

Вам также может понравиться