Reading Files in Objective-C
Our first program will demonstrate reading files. Here’s the full source code:
This program demonstrates various file reading operations in Objective-C:
We start by reading the entire file content using NSString
’s stringWithContentsOfFile:encoding:error:
method.
Then we open the file using NSFileHandle
for more controlled reading operations.
We read a specific number of bytes from the beginning of the file.
We demonstrate seeking to different positions in the file using seekToFileOffset:
.
We use NSInputStream
for buffered reading, which can be more efficient for many small reads.
To run the program, save it as ReadingFiles.m
and compile it using:
Before running the program, create a test file:
Now you can run the compiled program:
The output will depend on the content of your /tmp/dat
file, but it should display the file content and the results of various read operations.
Next, we’ll look at writing files.