Pure Programmer
Blue Matrix


Cluster Map

File I/O

L1

This page is under construction. Please come back later.

FileIO1.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply copies a file to the console character by
 * character like the Unix 'cat' program.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func readTextFile(_ filespec:String) throws -> Void {
	var ifh:StreamReader? = StreamReader(filespec)
	if ifh == nil {
		throw RuntimeError("Problem opening input file!")
	}
	var c:Int?
	c = ifh!.getCodepoint()
	while c != nil {
		print(Utils.chr(c!), terminator: "")
		c = ifh!.getCodepoint()
	}
	ifh!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	let FILESPEC:String = CommandLine.arguments[1]
	do {
		try readTextFile(FILESPEC)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	} catch {
		print("Unexpected File Read Error")
	}
	exit(EXIT_SUCCESS)
}
main()

Output
FileIO1.swift:13:6: warning: variable 'ifh' was never mutated; consider changing to 'let' constant 11 | 12 | func readTextFile(_ filespec:String) throws -> Void { 13 | var ifh:StreamReader? = StreamReader(filespec) | `- warning: variable 'ifh' was never mutated; consider changing to 'let' constant 14 | if ifh == nil { 15 | throw RuntimeError("Problem opening input file!") Lincoln's Gettysburg Address, given November 19, 1863 on the battlefield near Gettysburg, Pennsylvania, USA Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate-we can not consecrate-we can not hallow-this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us-that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion-that we here highly resolve that these dead shall not have died in vain-that this nation, under God, shall have a new birth of freedom-and that government of the people, by the people, for the people, shall not perish from the earth. FileIO1.swift:13:6: warning: variable 'ifh' was never mutated; consider changing to 'let' constant 11 | 12 | func readTextFile(_ filespec:String) throws -> Void { 13 | var ifh:StreamReader? = StreamReader(filespec) | `- warning: variable 'ifh' was never mutated; consider changing to 'let' constant 14 | if ifh == nil { 15 | throw RuntimeError("Problem opening input file!") Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Vor vier Punkten und sieben Jahren haben unsere Väter auf diesem Kontinent eine neue Nation hervorgebracht, die in Freiheit empfangen wurde und sich dem Vorschlag verschrieben hat, dass alle Menschen gleich geschaffen sind. Τέσσερα σκορ και πριν από επτά χρόνια οι πατέρες μας έφεραν σε αυτή την ήπειρο, ένα νέο έθνος, που σχεδιάστηκε στην Ελευθερία και αφιερώθηκε στην πρόταση ότι όλοι οι άνθρωποι δημιουργούνται ίσοι. أربع نقاط وقبل سبع سنوات قدم آباؤنا في هذه القارة ، أمة جديدة ، تم تصورها في الحرية ، ومكرسة لفرضية أن جميع الرجال خلقوا متساوين. ארבע ציונים ולפני שבע שנים אבותינו הציגו ביבשת זו, אומה חדשה, שהגתה בחירות, והוקדשה לטענה שכל הגברים נוצרים שווים. ... Graphemes that take two codepoints Canada 🇨🇦 China 🇨🇳 France 🇫🇷 Greece 🇬🇷 Israel 🇮🇱 Japan 🇯🇵 Mexico 🇲🇽 UK 🇬🇧 US 🇺🇸
FileIO2.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply copies a file to the console line by line.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func readTextFile(_ filespec:String) throws -> Void {
	let IFH:StreamReader? = StreamReader(filespec)
	if IFH == nil {
		throw RuntimeError("Problem opening input file!")
	}
	var line:String?
	line = IFH!.getLine()
	while line != nil {
		print(line!)
		line = IFH!.getLine()
	}
	IFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	let FILESPEC:String = CommandLine.arguments[1]
	do {
		try readTextFile(FILESPEC)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	} catch {
		print("Unexpected File Read Error")
	}
	exit(EXIT_SUCCESS)
}
main()

Output
Lincoln's Gettysburg Address, given November 19, 1863 on the battlefield near Gettysburg, Pennsylvania, USA Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate-we can not consecrate-we can not hallow-this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us-that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion-that we here highly resolve that these dead shall not have died in vain-that this nation, under God, shall have a new birth of freedom-and that government of the people, by the people, for the people, shall not perish from the earth. Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. Vor vier Punkten und sieben Jahren haben unsere Väter auf diesem Kontinent eine neue Nation hervorgebracht, die in Freiheit empfangen wurde und sich dem Vorschlag verschrieben hat, dass alle Menschen gleich geschaffen sind. Τέσσερα σκορ και πριν από επτά χρόνια οι πατέρες μας έφεραν σε αυτή την ήπειρο, ένα νέο έθνος, που σχεδιάστηκε στην Ελευθερία και αφιερώθηκε στην πρόταση ότι όλοι οι άνθρωποι δημιουργούνται ίσοι. أربع نقاط وقبل سبع سنوات قدم آباؤنا في هذه القارة ، أمة جديدة ، تم تصورها في الحرية ، ومكرسة لفرضية أن جميع الرجال خلقوا متساوين. ארבע ציונים ולפני שבע שנים אבותינו הציגו ביבשת זו, אומה חדשה, שהגתה בחירות, והוקדשה לטענה שכל הגברים נוצרים שווים. ... Graphemes that take two codepoints Canada 🇨🇦 China 🇨🇳 France 🇫🇷 Greece 🇬🇷 Israel 🇮🇱 Japan 🇯🇵 Mexico 🇲🇽 UK 🇬🇧 US 🇺🇸
FileIO3.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program reads bytes from a file and prints them in hexadecimal format.
 * 
 * Copyright © 2021 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func readBinaryFile(_ filespec:String) throws -> Void {
	let IFH:FileHandle? = FileHandle(forReadingAtPath: filespec)
	if IFH == nil {
		throw RuntimeError("Problem opening input file!")
	}
	var c:UInt8?
	var count:Int = 0
	c = Utils.getbyte(IFH!)
	while c != nil {
		print(Utils.format("{0:02x} ", c!), terminator: "")
		count += 1
		if count % 16 == 0 {
			print()
		}
		c = Utils.getbyte(IFH!)
	}
	if count % 16 != 0 {
		print()
	}
	try IFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	let FILESPEC:String = CommandLine.arguments[1]
	do {
		try readBinaryFile(FILESPEC)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	} catch {
		print("Unexpected File Read Error")
	}
	exit(EXIT_SUCCESS)
}
main()

Output
4c 69 6e 63 6f 6c 6e 27 73 20 47 65 74 74 79 73 62 75 72 67 20 41 64 64 72 65 73 73 2c 20 67 69 76 65 6e 20 4e 6f 76 65 6d 62 65 72 20 31 39 2c 20 31 38 36 33 0a 6f 6e 20 74 68 65 20 62 61 74 74 6c 65 66 69 65 6c 64 20 6e 65 61 72 20 47 65 74 74 79 73 62 75 72 67 2c 20 50 65 6e 6e 73 79 6c 76 61 6e 69 61 2c 20 55 53 41 0a 0a 46 6f 75 72 20 73 63 6f 72 65 20 61 6e 64 20 73 65 76 65 6e 20 79 65 61 72 73 20 61 67 6f 20 6f 75 72 20 66 61 74 68 65 72 73 20 62 72 6f 75 67 68 74 20 ... 68 69 73 20 6e 61 74 69 6f 6e 2c 20 75 6e 64 65 72 20 47 6f 64 2c 20 73 68 61 6c 6c 20 68 61 76 65 20 61 20 6e 65 77 20 62 69 72 74 68 20 6f 66 20 66 72 65 65 64 6f 6d 2d 61 6e 64 20 74 68 61 74 20 67 6f 76 65 72 6e 6d 65 6e 74 20 6f 66 20 74 68 65 20 70 65 6f 70 6c 65 2c 20 62 79 20 74 68 65 20 70 65 6f 70 6c 65 2c 20 66 6f 72 20 74 68 65 20 70 65 6f 70 6c 65 2c 20 73 68 61 6c 6c 20 6e 6f 74 20 70 65 72 69 73 68 20 66 72 6f 6d 20 74 68 65 20 65 61 72 74 68 2e 0a 46 6f 75 72 20 73 63 6f 72 65 20 61 6e 64 20 73 65 76 65 6e 20 79 65 61 72 73 20 61 67 6f 20 6f 75 72 20 66 61 74 68 65 72 73 20 62 72 6f 75 67 68 74 20 66 6f 72 74 68 20 6f 6e 20 74 68 69 73 20 63 6f 6e 74 69 6e 65 6e 74 2c 20 61 20 6e 65 77 20 6e 61 74 69 6f 6e 2c 20 63 6f 6e 63 65 69 76 65 64 20 69 6e 20 4c 69 62 65 72 74 79 2c 20 61 6e 64 20 64 65 64 69 63 61 74 65 64 20 74 6f 20 74 68 65 20 70 72 6f 70 6f 73 69 74 69 6f 6e 20 74 68 61 74 20 61 6c 6c 20 6d 65 6e 20 61 72 ... 20 74 77 6f 20 63 6f 64 65 70 6f 69 6e 74 73 0a 43 61 6e 61 64 61 20 f0 9f 87 a8 f0 9f 87 a6 0a 43 68 69 6e 61 20 f0 9f 87 a8 f0 9f 87 b3 0a 46 72 61 6e 63 65 20 f0 9f 87 ab f0 9f 87 b7 0a 47 72 65 65 63 65 20 f0 9f 87 ac f0 9f 87 b7 0a 49 73 72 61 65 6c 20 f0 9f 87 ae f0 9f 87 b1 0a 4a 61 70 61 6e 20 f0 9f 87 af f0 9f 87 b5 0a 4d 65 78 69 63 6f 20 f0 9f 87 b2 f0 9f 87 bd 0a 55 4b 20 f0 9f 87 ac f0 9f 87 a7 0a 55 53 20 f0 9f 87 ba f0 9f 87 b8 20 0a
FileIO4.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply writes characters from the alphabet to a file.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func writeTextFile(_ filespec:String) throws -> Void {
	FileManager.default.createFile(atPath: filespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: filespec)
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
// Latin alphabet
	for c:Int in 0x41...0x5A {
		OFH!.write(Utils.chr(c).data(using: .utf8)!)
	}
	OFH!.write("\n".data(using: .utf8)!)
// Greek alphabet
	for c:Int in 0x391...0x3A9 {
		OFH!.write(Utils.chr(c).data(using: .utf8)!)
	}
	OFH!.write("\n".data(using: .utf8)!)
// Cyrillic alphabet
	for c:Int in 0x410...0x42F {
		OFH!.write(Utils.chr(c).data(using: .utf8)!)
	}
	OFH!.write("\n".data(using: .utf8)!)
// Katakana alphabet
	for c:Int in 0x30A0...0x30FF {
		OFH!.write(Utils.chr(c).data(using: .utf8)!)
	}
	OFH!.write("\n".data(using: .utf8)!)
	OFH!.synchronizeFile()
	OFH!.closeFile()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	let FILESPEC:String = CommandLine.arguments[1]
	do {
		try writeTextFile(FILESPEC)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	} catch {
		print("Unexpected File Read Error")
	}
	exit(EXIT_SUCCESS)
}
main()

Output
$ cat output/testFileIO4.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ΢ΣΤΥΦΧΨΩ АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ
FileIO5.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply writes lines with the alphabet to a file.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func writeTextFile(_ filespec:String) throws -> Void {
	FileManager.default.createFile(atPath: filespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: filespec)
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
	OFH!.write("ABCDEFGHIJKLMNOPQRSTUVWXYZ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.write("ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.write("АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.write("゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.write("ダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.write("ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ".data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
	OFH!.closeFile()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	let FILESPEC:String = CommandLine.arguments[1]
	do {
		try writeTextFile(FILESPEC)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	} catch {
		print("Unexpected File Write Error")
	}
	exit(EXIT_SUCCESS)
}
main()

Output
$ cat output/testFileIO5.txt ABCDEFGHIJKLMNOPQRSTUVWXYZ ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ ゠ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタ ダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶヷヸヹヺ・ーヽヾヿ
FileIO6.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply writes the bytes 0 - 256 to a binary file.
 * 
 * Copyright © 2021 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func writeBinaryFile(_ filespec:String) throws -> Void {
	FileManager.default.createFile(atPath: filespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: filespec)
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
	for b:Int in 0...255 {
		OFH!.write(Data([UInt8(b)]))
	}
	try OFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 2 {
		print("Syntax: " + CommandLine.arguments[0] + " {filename}")
		exit(1)
	}
	var filespec:String = CommandLine.arguments[1]
	do {
		try writeBinaryFile(filespec)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	}
	exit(EXIT_SUCCESS)
}
main()

Output
FileIO6.swift:28:6: warning: variable 'filespec' was never mutated; consider changing to 'let' constant 26 | exit(1) 27 | } 28 | var filespec:String = CommandLine.arguments[1] | `- warning: variable 'filespec' was never mutated; consider changing to 'let' constant 29 | do { 30 | try writeBinaryFile(filespec) FileIO6.swift:30:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 28 | var filespec:String = CommandLine.arguments[1] 29 | do { 30 | try writeBinaryFile(filespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 31 | } catch let ex as RuntimeError { 32 | print("Error: " + ex.localizedDescription) $ od -t x1 output/testFileIO6.bin od: output/testFileIO6.bin: No such file or directory
FileIO7.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply copies one file to another, character by
 * character like the Unix 'cat' program.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func copyTextFile(_ fromFilespec:String, _ toFilespec:String) throws -> Void {
	let IFH:StreamReader? = StreamReader(fromFilespec)
	FileManager.default.createFile(atPath: toFilespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: toFilespec)
	if IFH == nil {
		throw RuntimeError("Problem opening input file!")
	}
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
	var c:Int?
	c = IFH!.getCodepoint()
	while c != nil {
		OFH!.write(Utils.chr(c!).data(using: .utf8)!)
		c = IFH!.getCodepoint()
	}
	IFH!.close()
	try OFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 3 {
		print("Syntax: " + CommandLine.arguments[0] + " {fromFilespec} {toFilespec}")
		exit(1)
	}
	var fromFilespec:String = CommandLine.arguments[1]
	var toFilespec:String = CommandLine.arguments[2]
	do {
		try copyTextFile(fromFilespec, toFilespec)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	}
	exit(EXIT_SUCCESS)
}
main()

Output
FileIO7.swift:37:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 35 | exit(1) 36 | } 37 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 38 | var toFilespec:String = CommandLine.arguments[2] 39 | do { FileIO7.swift:38:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 36 | } 37 | var fromFilespec:String = CommandLine.arguments[1] 38 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 39 | do { 40 | try copyTextFile(fromFilespec, toFilespec) FileIO7.swift:40:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 38 | var toFilespec:String = CommandLine.arguments[2] 39 | do { 40 | try copyTextFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 41 | } catch let ex as RuntimeError { 42 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO7.txt ../../data/text/GettysburgAddress.txt diff: output/testFileIO7.txt: No such file or directory FileIO7.swift:37:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 35 | exit(1) 36 | } 37 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 38 | var toFilespec:String = CommandLine.arguments[2] 39 | do { FileIO7.swift:38:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 36 | } 37 | var fromFilespec:String = CommandLine.arguments[1] 38 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 39 | do { 40 | try copyTextFile(fromFilespec, toFilespec) FileIO7.swift:40:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 38 | var toFilespec:String = CommandLine.arguments[2] 39 | do { 40 | try copyTextFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 41 | } catch let ex as RuntimeError { 42 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO7.utf8 ../../data/text/UnicodeTest.utf8 diff: output/testFileIO7.utf8: No such file or directory
FileIO8.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program simply copies one file to another, line by line.
 * 
 * Copyright © 2020 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func copyTextFile(_ fromFilespec:String, _ toFilespec:String) throws -> Void {
	let IFH:StreamReader? = StreamReader(fromFilespec)
	FileManager.default.createFile(atPath: toFilespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: toFilespec)
	if IFH == nil {
		throw RuntimeError("Problem opening input file!")
	}
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
	var line:String?
	line = IFH!.getLine()
	while line != nil {
		OFH!.write(line!.data(using: .utf8)!);OFH!.write("\n".data(using: .utf8)!)
		line = IFH!.getLine()
	}
	IFH!.close()
	try OFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 3 {
		print("Syntax: " + CommandLine.arguments[0] + " {fromFilespec} {toFilespec}")
		exit(1)
	}
	var fromFilespec:String = CommandLine.arguments[1]
	var toFilespec:String = CommandLine.arguments[2]
	do {
		try copyTextFile(fromFilespec, toFilespec)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	}
	exit(EXIT_SUCCESS)
}
main()

Output
FileIO8.swift:36:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 34 | exit(1) 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { FileIO8.swift:37:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] 37 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 38 | do { 39 | try copyTextFile(fromFilespec, toFilespec) FileIO8.swift:39:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { 39 | try copyTextFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 40 | } catch let ex as RuntimeError { 41 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO8.txt ../../data/text/GettysburgAddress.txt diff: output/testFileIO8.txt: No such file or directory FileIO8.swift:36:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 34 | exit(1) 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { FileIO8.swift:37:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] 37 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 38 | do { 39 | try copyTextFile(fromFilespec, toFilespec) FileIO8.swift:39:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { 39 | try copyTextFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 40 | } catch let ex as RuntimeError { 41 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO8.utf8 ../../data/text/UnicodeTest.utf8 diff: output/testFileIO8.utf8: No such file or directory
FileIO9.swift
#!/usr/bin/env swift;
/******************************************************************************
 * This program reads bytes from a binary file and copies them to another file.
 * 
 * Copyright © 2021 Richard Lesh.  All rights reserved.
 *****************************************************************************/

import Foundation
import Utils

func copyBinaryFile(_ fromFilespec:String, _ toFilespec:String) throws -> Void {
	let IFH:FileHandle? = FileHandle(forReadingAtPath: fromFilespec)
	FileManager.default.createFile(atPath: toFilespec, contents: nil)
	let OFH:FileHandle? = FileHandle(forWritingAtPath: toFilespec)
	if IFH == nil {
		throw RuntimeError("Problem opening input file!")
	}
	if OFH == nil {
		throw RuntimeError("Problem opening output file!")
	}
	var c:UInt8?
	c = Utils.getbyte(IFH!)
	while c != nil {
		OFH!.write(Data([UInt8(c!)]))
		c = Utils.getbyte(IFH!)
	}
	try IFH!.close()
	try OFH!.close()
}

func main() -> Void {
	if CommandLine.arguments.count != 3 {
		print("Syntax: " + CommandLine.arguments[0] + " {fromFilespec} {toFilespec}")
		exit(1)
	}
	var fromFilespec:String = CommandLine.arguments[1]
	var toFilespec:String = CommandLine.arguments[2]
	do {
		try copyBinaryFile(fromFilespec, toFilespec)
	} catch let ex as RuntimeError {
		print("Error: " + ex.localizedDescription)
	}
	exit(EXIT_SUCCESS)
}
main()

Output
FileIO9.swift:36:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 34 | exit(1) 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { FileIO9.swift:37:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] 37 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) FileIO9.swift:39:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 40 | } catch let ex as RuntimeError { 41 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO9.txt ../../data/text/GettysburgAddress.txt diff: output/testFileIO9.txt: No such file or directory FileIO9.swift:36:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 34 | exit(1) 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { FileIO9.swift:37:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] 37 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) FileIO9.swift:39:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 40 | } catch let ex as RuntimeError { 41 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO9.utf8 ../../data/text/UnicodeTest.utf8 diff: output/testFileIO9.utf8: No such file or directory FileIO9.swift:36:6: warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 34 | exit(1) 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] | `- warning: variable 'fromFilespec' was never mutated; consider changing to 'let' constant 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { FileIO9.swift:37:6: warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 35 | } 36 | var fromFilespec:String = CommandLine.arguments[1] 37 | var toFilespec:String = CommandLine.arguments[2] | `- warning: variable 'toFilespec' was never mutated; consider changing to 'let' constant 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) FileIO9.swift:39:3: error: errors thrown from here are not handled because the enclosing catch is not exhaustive 37 | var toFilespec:String = CommandLine.arguments[2] 38 | do { 39 | try copyBinaryFile(fromFilespec, toFilespec) | `- error: errors thrown from here are not handled because the enclosing catch is not exhaustive 40 | } catch let ex as RuntimeError { 41 | print("Error: " + ex.localizedDescription) $ diff -q output/testFileIO9.jpg ../../data/images/GlowingCat.jpg diff: output/testFileIO9.jpg: No such file or directory
swift

Questions

Projects

More ★'s indicate higher difficulty level.

References