[ Team LiB ] Previous Section Next Section

Chapter 16. Working with Files

The Foundation framework enables you to get access to the file system to perform basic operations on files and directories. This is provided by NSFileManager, whose methods include the capability to

  • Create a new file

  • Read from an existing file

  • Write data to a file

  • Rename a file

  • Remove (delete) a file

  • Test for the existence of a file

  • Determine the size of a file as well as other attributes

  • Make a copy of a file

  • Test two files to see whether their contents are equal

Many of these operations can also be performed on directories. For example, you can create a directory, read its contents, or delete it. Another feature is the ability to link files. That is, the ability to have the same file exist under two different names, perhaps even in different directories.

To open a file and perform multiple read and write operations on the file, you use the methods provided by NSFileHandle. The methods in this class enable you to

  • Open a file for reading, writing, or updating (reading and writing)

  • Seek to a specified position within a file

  • Read or write a specified number of bytes from and to a file

The methods provided by NSFileHandle can also be applied to devices or sockets. However, we will focus only on dealing with ordinary files in this chapter.

If you want to write programs that will run on different machines (or even under different operating system versions on the same machine), you should try to make your programs as independent of the underlying structure of the file system as possible. This implies that you should not make any assumptions about the existence of particular directories (for example, /tmp) or the location of particular files. Luckily, the Foundation framework provides routines that enable you to more easily write portable programs.

    [ Team LiB ] Previous Section Next Section