How to file handle in Swift using FileHandler

The FileHandle class in Swift can be used to interact with files. The Foundation framework's FileHandle provides a simple method for interacting with files at a low level utilizing file descriptorsFile descriptors are integer values that uniquely identify open files and enable low-level file operations in an operating system, providing efficient resource management and fine-grained control over file interactions..

The FileHandle class is designed to make it easier to read, write, seek, and close files, among other file actions. It acts as a bridge between the underlying file system and your Swift code. You can read data from a file, write data to a file, seek specific locations inside a file, and manage file descriptors with FileHandle.

FileHandle object creation in Swift

When a file is opened for either reading or writing (read: both reading and writing), a FileHandle object may be created, and a file must be closed using the closeFile method after it has been opened and used for its intended purpose.
Here's an example that opens a file for reading (thus the forReadingAtPath statement), then closes it without making any changes to the file.

main.swift
textfile.txt
import Foundation
let filePath1 = "textfile.txt"
let file: FileHandle? = FileHandle(forReadingAtPath: filePath1)
if file == nil {
print("File open failed")
} else {
print("File opened successfully. Closing file...")
file?.closeFile()
}
  1. We import the Foundation framework, which includes the FileHandle class and other file-related functionality.

  2. The filePath1 variable holds the path to the file we want to open for reading. In this case, it's set to "textfile.txt".

  3. We declare a variable file of type FileHandle? (optional FileHandle). It will be assigned the result of opening the file for reading.

  4. The FileHandle(forReadingAtPath:) initializer is used to attempt to open the file at the specified path for reading. If the file doesn't exist or cannot be opened for reading, the file variable will be assigned nil.

  5. We check if the file variable is nil. If it is nil, it means that the file open operation failed, and we print a corresponding error message.

  6. If the file variable is not nil, which means the file open operation was successful. We print a success message and proceed to close the file using the closeFile() method of FileHandle. It's essential to close the file to release any associated resources properly.

This code snippet demonstrates the process of opening a file for reading using FileHandle and handling the case when the file open operation fails.

File offsets and seeking using FileHandler

Swift FileHandle objects preserve an offset showing the current file location. The offset is normally set to 0, which denotes the start of the file. The offset must be changed appropriately to read or write data in various file locations. The FileHandle class offers ways to work with the offset.

The seekToEndOfFile method pushes the offset to the file's end to append data. Setting the offset to a specified position within the file is possible using the seek(toFileOffset:) function. Use the offsetInFile method to obtain the current offset value. The offset is kept as a 64-bit unsigned integer to accommodate big files. With these techniques, the exact location inside a file can be attained with FileHandle objects in Swift.

It is important to understand file offsets since they are crucial to utilizing the FileHandle class to work with files. It is impossible to predict the location in a file where data will be read or written without knowing where the current offset is.

In the example that follows, a file is opened, a seek to offset 11 is made, ten characters are read, and then they are printed to the console.

main.swift
textfile.txt
Welcome to Educative

Alternatively, the readDataToEndOfFile method will read all the data in the file, starting at the current offset and ending at the end of the file.

Writing data to a file

Here's an example code snippet that demonstrates how to write data to a file using FileHandle in Swift.

main.swift
textfile.txt
Welcome to Educative. This code is written in swift

The code imports the Foundation framework and opens a file for updating. It reads the file's contents, overwrites part of the file, and displays the updated contents. Finally, the file is closed.

File truncation

File truncation allows you to delete the file permanently. Once the file has been deleted, it can't be retrieved.

Using the truncateFile(atOffset:) method, a file can be truncated at the supplied offset. If you call this function with an offset of 0, all contents of the file will be deleted.

import Foundation
let filePath = "textfile.txt"
// Open the file handle for truncating
if let fileHandle = FileHandle(forUpdatingAtPath: filePath) {
// Truncate the file at the desired offset
let truncateOffset: UInt64 = 100
fileHandle.truncateFile(atOffset: truncateOffset)
print("File truncated at offset: \(truncateOffset)")
// Close the file handle
fileHandle.closeFile()
} else {
print("Failed to open the file for truncating.")
}

Conclusion

Low-level file interactions in Swift are made simpler by the use of FileHandle. Using file descriptors allows for reading, writing, seeking, and closing files. You can open, read, and write files with error handling using FileHandle. Using seeking, you can set the file offset to read or write at particular areas. Truncation makes it easier to erase file contents that are located outside of a specified offset.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved