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 { let 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() } // Begin Main if CommandLine.arguments.count != 2 { print("Syntax: " + CommandLine.arguments[0] + " {filename}") exit(1) } var filespec:String = CommandLine.arguments[1] do { try readTextFile(filespec) } catch let ex as RuntimeError { print("Error: " + ex.localizedDescription) } exit(EXIT_SUCCESS)
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() } // Begin Main if CommandLine.arguments.count != 2 { print("Syntax: " + CommandLine.arguments[0] + " {filename}") exit(1) } var filespec:String = CommandLine.arguments[1] do { try readTextFile(filespec) } catch let ex as RuntimeError { print("Error: " + ex.localizedDescription) } exit(EXIT_SUCCESS)
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 decimal 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(String(c!) + " ", terminator: "") count += 1 if count % 20 == 0 { print() } c = Utils.getbyte(ifh!) } if count % 20 != 0 { print() } try ifh!.close() } // Begin Main if CommandLine.arguments.count != 2 { print("Syntax: " + CommandLine.arguments[0] + " {filename}") exit(1) } var filespec:String = CommandLine.arguments[1] do { try readBinaryFile(filespec) } catch let ex as RuntimeError { print("Error: " + ex.localizedDescription) } exit(EXIT_SUCCESS)
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)!) } // 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)!) try ofh!.close() } // Begin Main if CommandLine.arguments.count != 2 { print("Syntax: " + CommandLine.arguments[0] + " {filename}") exit(1) } var filespec:String = CommandLine.arguments[1] do { try writeTextFile(filespec) } catch let ex as RuntimeError { print("Error: " + ex.localizedDescription) } exit(EXIT_SUCCESS)
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)!) try ofh!.close() } // Begin Main if CommandLine.arguments.count != 2 { print("Syntax: " + CommandLine.arguments[0] + " {filename}") exit(1) } var filespec:String = CommandLine.arguments[1] do { try writeTextFile(filespec) } catch let ex as RuntimeError { print("Error: " + ex.localizedDescription) } exit(EXIT_SUCCESS)
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() } // Begin Main 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)
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() } // Begin Main 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)
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() } // Begin Main 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)
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() } // Begin Main 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)
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]]