Swift: Working with files


(0 comments)

We can use file handling functions in C to work with file pointers.
In the example below, we declare the file pointer fp, open the file hello.txt and then write to the file two lines of text, the first line is "Hello", the second line is "World!"

import Foundation

let filename = "hello.txt"
var fp: UnsafeMutablePointer<FILE>?

fp = fopen(filename, "w")
if fp == nil { perror("fopen"); exit(EXIT_FAILURE) }

let line1 = "Hello\n", line2 = "World!\n"
fwrite(line1, 1, line1.count,  fp)
fwrite(line2, 1, line2.count,  fp)
fclose(fp)

Next, we open the file hello.txt for reading. Each text line of the file is read into the bytes array 'data'. If the line of text contains a newline, it is replaced with a terminating null byte. Data is converted to a NSString string, then further converted to a String. Then the text is rendered

import Foundation

let filename = "hello.txt"
var fp: UnsafeMutablePointer<FILE>?

var data: [CChar] = Array(repeating: 0, count: 260)
fp = fopen(filename, "r")
if fp == nil { perror("fopen"); exit(EXIT_FAILURE) }

while fgets(&data, 260, fp) != nil {
    let index_newline = data.firstIndex(of: 10)
    if index_newline != nil {
        data[index_newline!] = 0
    }
    
    let text_ns = NSString(utf8String: data)
    if text_ns != nil {
        let text = String(text_ns!)
        print(text)
    }
}

fclose(fp)

Currently unrated

Comments

There are currently no comments

New Comment

required

required (not published)

optional

required


What is 9 - 5?

required