[swift-users] file io in Swift 2.2 for Linux (would like to be pointed in the right direction)

John Myers myersj at shawanoschools.com
Wed May 18 17:02:02 CDT 2016

I've been having trouble figuring out how to read and write data to a
textfile, and not finding much out there for Swift on Linux.  I found code
for reading data from a file on StackOverflow that works for me, but
cludged together my own code for writing to a file.  I'm not sure exactly
what I'm doing, but am making some progress.  Can anyone point me toward a
good source of help for reading and writing data in Swift on Linux.  Thanks!

This is the code that I found that works for reading data:

//  Try to read from a file

//  5/16/2016

import Glibc  //import a Linux library

let path = "Resources/sampleIn.txt"

let BUFSIZE = 1024

print("attempting to open a file for input")

let fp = fopen(path, "r")

if fp == nil {print("error reading file")}

if fp != nil {


 var buf = [CChar](count:BUFSIZE, repeatedValue:CChar(0))

 while fgets(&buf, Int32(BUFSIZE), fp) != nil {

   print(String.fromCString(buf)!, terminator:"")



This is the code I pieced together for writing data:

import Glibc  //import a Linux library
let path = "Resources/sampleOut.txt"let BUFSIZE =
1024print("attempting to open a file for Output")let fp = fopen(path,
"w+")if fp == nil {print("error writing file")}if fp != nil {
  print("Type a few words to be saved to a file")
  var fewWords=readLine()!

Any help would be appreciated.

John Myers
Mathematics and Computer Science Teacher

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160518/aeb4d1f6/attachment.html>

More information about the swift-users mailing list