Low-level file writing in Swift?

Something I never see in Swift tutorials, but I would need almost immediately for what I want to do, is low-level disk file writing, e.g. writing bytes, ints, strings, etc. to a file on disk. I guess it doesn't come up much in app development :) The most I've been able to glean so far is it might have something to do with the Data class???

If anyone can point me to resources/APIs I should look at, I'd greatly appreciate it :slight_smile:

Thanks,

Matt

1 Like

FileHandle from Foundation is likely the class you want to look at. It's got the low-level primitives for writing Data buffers to files.

2 Likes

And for some inspiration on how to convert integers to their binary representation, check out ByteBuffer from swift-nio.

There are a few options available here:

  • Data (a raw binary blob) can be written to a file location
  • FileHandle, as mentioned by @harlanhaskins, is an object-oriented wrapper around a file descriptor. As such, it has the standard functionality you might expect related to functions like open, write, and close
  • OutputStream is like a write socket. IIRC, it requires an active runloop in order to process its pending data and write it out.
  • DispatchWriteSource is like a combination of FileHandle and OutputStream: it writes to a file descriptor, but isn't tied to a runloop. It's generally a "lower level" construct for streaming data out.

There are probably others, but those would be the most commonly-used ones.

2 Likes

for solutions that don’t involve Foundation or Apple APIs, remember that Swift is capable of calling the C standard library so you have access to fread, fwrite, etc

like other people said, be very careful when reading multibyte values as the read data may not be properly aligned (but i think it currently is by implementation since the pointer allocate(capacity:) functions all align to 8 bytes)

allocate(capacity:) ends up calling malloc(3), which is 16-byte aligned on most modern 64-bit systems.

https://www.sqlite.org/aff_short.html