Download Unix system programming in OCaml
Transcript
Files ;; handle_unix_error copyrec ();; Exercise 6 Copy hard links cleverly. As written above copy_rec creates n duplicates of the same file whenever a file occurs under n different names in the hierarchy to copy. Try to detect this situation, copy the file only once and make hard links in the destination hierarchy. Answer page 122. *** 2.16 Complete example: Tape ARchive The tar file format (for tape archive) can store a file hierarchy into a single file. It can be seen as a mini file system. In this section we define functions to read and write tar files. We also program a command readtar such that readtar a displays the name of the files contained in the archive a and readtar a f extracts the contents of the file f contained in a. Extracting the whole file hierarchy of an archive and generating an archive for a file hierarchy is left as an exercise. File format specification A tar archive is a set of records. Each record represents a file; it starts with a header which encodes the information about the file (its name, type, size, owners, etc.) and is followed by the contents of the file. The header is a block of 512 bytes structured as shown in table 3. The file contents is stored right after the header, its size is rounded to a multiple of 512 bytes (the extra space is filled with zeros). Records are stored one after the other. If needed, the file is padded with empty blocks to reach at least 20 blocks. Since tar archives are also designed to be written on brittle media and reread many years later, the header contains a checksum field which allows to detect when the header is damaged. Its value is the sum of all the bytes of the header (to compute that sum we assume that the checksum field itself is made of zeros). The kind header field encodes the file type in a byte as follows4 : '\0' or '0' REG '1' '2' '3' '4' '5' '6' '7' LINK LNK CHR BLK DIR FIFO CONT Most of the cases correspond to the values of the Unix file type file_kind stored in the st_kind field of the stats structure. LINK is for hard links which must lead to another file already stored within the archive. CONT is for ordinary file, but stored in a contiguous area of memory (this is a feature of some file systems, we can treat it like an ordinary file). The link header field stores the link when kind is LNK or LINK. The fields major and minor contain the major and minor numbers of the peripheral when kind is CHR or BLK. These three fields are not used in other cases. 4 This field can also take different values to encode pathological cases, for example when the value of a field exceeds its size or in extensions of the tar format. 34