How to resolve the algorithm Take notes on the command line step by step in the Swift programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Take notes on the command line step by step in the Swift programming language
Table of Contents
Problem Statement
Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then all the arguments, joined with spaces, prepended with a tab, and appended with a trailing newline, are written to NOTES.TXT. If NOTES.TXT doesn't already exist in the current directory then a new NOTES.TXT file should be created.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Take notes on the command line step by step in the Swift programming language
Source code in the swift programming language
import Foundation
let args = Process.arguments
let manager = NSFileManager()
let currentPath = manager.currentDirectoryPath
var err:NSError?
// Create file if it doesn't exist
if !manager.fileExistsAtPath(currentPath + "/notes.txt") {
println("notes.txt doesn't exist")
manager.createFileAtPath(currentPath + "/notes.txt", contents: nil, attributes: nil)
}
// handler is what is used to write to the file
let handler = NSFileHandle(forUpdatingAtPath: currentPath + "/notes.txt")
// Print the file if there are no args
if args.count == 1 {
let str = NSString(contentsOfFile: currentPath + "/notes.txt", encoding: NSUTF8StringEncoding, error: &err)
println(str!)
exit(0)
}
let time = NSDate()
let format = NSDateFormatter()
let timeData = (format.stringFromDate(time) + "\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
format.dateFormat = "yyyy.MM.dd 'at' HH:mm:ss zzz"
// We're writing to the end of the file
handler?.seekToEndOfFile()
handler?.writeData(timeData!)
var str = "\t"
for i in 1..<args.count {
str += args[i] + " "
}
str += "\n"
let strData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
handler?.writeData(strData!)
You may also check:How to resolve the algorithm Apply a digital filter (direct form II transposed) step by step in the Scala programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the jq programming language
You may also check:How to resolve the algorithm Convex hull step by step in the Tcl programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the VBScript programming language
You may also check:How to resolve the algorithm Sum of a series step by step in the RLaB programming language