File I/O

This page is under construction. Please come back later.
#!/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
$ swiftc FileIO1.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ swiftc FileIO1.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
#!/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
$ swiftc FileIO2.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ swiftc FileIO2.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
#!/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
$ swiftc FileIO3.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ swiftc FileIO3.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
#!/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
$ swiftc FileIO4.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ cat output/testFileIO4.txt
cat: output/testFileIO4.txt: No such file or directory
#!/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
$ swiftc FileIO5.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ cat output/testFileIO5.txt
cat: output/testFileIO5.txt: No such file or directory
#!/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
$ swiftc FileIO6.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ od -t x1 output/testFileIO6.bin
od: output/testFileIO6.bin: No such file or directory
#!/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
$ swiftc FileIO7.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO7.txt
diff: output/testFileIO7.txt: No such file or directory
$ swiftc FileIO7.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO7.utf8
diff: output/testFileIO7.utf8: No such file or directory
#!/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
$ swiftc FileIO8.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO8.txt
diff: output/testFileIO8.txt: No such file or directory
$ swiftc FileIO8.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO8.utf8
diff: output/testFileIO8.utf8: No such file or directory
#!/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
$ swiftc FileIO9.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/GettysburgAddress.txt output/testFileIO9.txt
diff: output/testFileIO9.txt: No such file or directory
$ swiftc FileIO9.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/text/UnicodeTest.utf8 output/testFileIO9.utf8
diff: output/testFileIO9.utf8: No such file or directory
$ swiftc FileIO9.swift -I . -L . -lUtils
error: link command failed with exit code 1 (use -v to see invocation)
ld: library not found for -lUtils
clang: error: linker command failed with exit code 1 (use -v to see invocation)
$ diff -q ../../data/images/GlowingCat.jpg output/testFileIO9.jpg
diff: output/testFileIO9.jpg: No such file or directory
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
- Base64 Decoding
- Base64 Encoding
- ChaCha20 Cipher
- Number of Primes
- One-Way Hash
- Palindrome Search
- Spell Checker
- XOR Cipher
References
- [[Swift Community]]
- [[Swift Language Guide]]
- [[Swift Language Reference]]
- [[Swift Programming Language]], Apple Inc.
- [[Swift Doc]]
- [[We Heart Swift]]
- [[Swift Cookbook]]
- [[Swift Playground]]
- [[Swift at TutorialsPoint]]
- [[Hacking with Swift]]
Pure Programmer


