File IO in Swift for Linux


(John Myers) #1

I've just finished reading a very spirited debate on the merits
of streaming versus reading in an entire file. I'm convinced that both are
ideal depending on the situation. Thank you for the responses I received
on my original post. I had tried previously on StackOverflow, having
joined just for that purpose, but found myself censured and 'put on hold'
for asking a poor question, so I certainly enjoy and appreciate your guy's
help and support. Yesterday I discovered what I consider to be an elegant
solution (because of it's simplicity and that I comprehend the code) on the
sample code of the IBM BlueMix playground website. I include it here in
only slightly modified form. They didn't have a 'create file' version, but
I can work on trying to come up with that when I get a chance. (Or, any of
you can suggest that reverse version). Here it is... (I did test it, and
it works)

/* Opens a file and prints it to the
   console. Shows how file input can be done in swift.
   From IBM BlueMix Swift Playground sample code selections.
*/

#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
    import Darwin
#else
    import Glibc
#endif

let stream = fopen("Resources/sampleIn.txt", "r")

var s = ""
while (true) {
    let c = fgetc(stream)
    if c == -1 {
        break
    }
    s = String(Character(UnicodeScalar(UInt32(c))))
    print(s, terminator:"")

}

Thanks!
John

···

--
John Myers
Mathematics and Computer Science Teacher
Math Department Chair
Shawano Community High School
220 County Road B
Shawano, WI 54166
------------------------------------------------------------------
myersj@shawanoschools.com
(715) 526-2175 ext 2114