Title: File Access cont'
1File Access (cont.)
- define OPEN_MAX 20 / max files open at once
/ - extern FILE _iobOPEN_MAX
- define stdin (_iob0)
- define stdout (_iob1)
- define stderr (_iob2)
- enum _flags
- _READ 01, / file open for reading /
- _WRITE 02, / file open for writing /
- _UNBUF 04, / file is unbuffered /
- _EOF 010, / EOF has occurred on this
file / - _ERR 020 / error occurred on this file
/ -
2Case study
- List directory list file size of files or
directory - for directory list file size of all files under
the directory recursively - Storage System
- Malloc vs Free implementation using system call
3Unix file system structure
- Directory
- A file that contains a list of filenames and
inode numbers which are index into the inode
list. - Inode
- All information about a file except its name is
kept.
4Unix file system structure
5File system call
- ltsys/type.hgt ltsys/stat.hgt
- int stat(char , struct stat )
- Take a filename and returns all of the
information in the inode for that file, -1 for
error. - int fstat(int fd, struct stat )
- Take a file descriptor and returns all of the
information in the inode for that file, -1 for
error.
6Our data structures for directory
One for directory, one for directory entry
7System Level data structure for directory entry
includeltsys/dir.hgt
8Function relationship
Opendir
Closedir
Readdir
dirwalk
fsize
9fsize list the size and name of files or
directories
10Type of file
11Dirwalk recursively list name and size for files
inside directories
12Opendir open a directory
13Closedir close a directory
14Readdir read directory
15Storage system
- Free storage is kept as a list of free blocks
- Each block contains a header (size, a pointer to
the next block) and the space itself. - Blocks are kept in order of increasing storage
address and the last block points to the first
16How to find free blocks
- Malloc
- Looks for a block which satisfies the request and
the block will be deleted from the free list and
returned to the user. - Free
- Find a proper place to insert the block being
freed.
17Block format
- Block head
- A pointer to the next block
- A record of block size
- Alignment
- All blocks are multiple of header size
18A block returned by malloc
19malloc
20malloc(2)
21morecore
22sbrk(n)
- Unix system call sbrk(n) returns a pointer to n
more bytes of storage. Return -1 for no space. - Used in Morecore
23free
24Pointer functions
- Syntax
- type ( name) (argument list)
- Compare function prototypes
- type name (argument list)
25Pointer functions Usage
int find_average(int a) int i, sum0
for ( i0 ilt20 i) sum ai return
sum/20
int find_max(int a) int i int maxa0
for ( i0 ilt20 i) max max gt ai
? max ai return max
26Pointer functions Usage (cont.)
- int main()
-
- int job, result, score20
- score20.
- int (func)(int )
- scanf(d, job)
- func job 1 ? find_average find_max
- result func(score)
- return 0