ProgramGuru

Read input and work with files

Read input and work with files

A program may receive a student name from standard input or store a report on disk. Reading can fail or encounter the end of input, and a relative file path depends on the working directory. Treat these as explicit conditions rather than assuming every resource exists.

What you’ll learn

  • Write and read UTF-8 text at a temporary URL.
  • Handle resource failure and attempt cleanup without overwriting user files.

Read input and work with files in the example

  1. Temporary URL

    A program may receive a student name from standard input or store a report on disk.

    Temporary URL
  2. Write and read text

    <code>readLine()</code> returns an optional String because input may end.

    Write and read text
  3. Clean up artifact

    The program creates a uniquely named file in the temporary directory, writes UTF-8 text and reads it back.

    Clean up artifact
The program creates a uniquely named file in the temporary directory, writes UTF-8 text and reads it back. The defer attempts to remove the artifact when the scope ends. Paths and UUIDs are deliberately not printed, so the demonstrated transcript is stable.

How read input and work with files works

readLine() returns an optional String because input may end. Parse and validate it before arithmetic. Foundation supplies file and URL APIs for local storage. Use a disposable directory for the example; a temporary file is a practice artifact, not durable report storage.

Work through read input and work with files

Save this complete program as main.swift and run it with the Swift toolchain. It creates and removes its own temporary practice file.

Swift · complete program

import Foundation
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".txt")
do {
  defer { try? FileManager.default.removeItem(at: url) }
  try "Diya: 80".write(to: url, atomically: true, encoding: .utf8)
  let text = try String(contentsOf: url, encoding: .utf8)
  print(text)
} catch {
  print("File operation failed")
}

Expected output

Diya: 80

Follow the execution

The program creates a uniquely named file in the temporary directory, writes UTF-8 text and reads it back. The defer attempts to remove the artifact when the scope ends. Paths and UUIDs are deliberately not printed, so the demonstrated transcript is stable.

Practice: Read input and work with files

Your task: Why not write this practice file over an existing report?

Swift · complete program

import Foundation
let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".txt")
do {
  defer { try? FileManager.default.removeItem(at: url) }
  try "Diya: 80".write(to: url, atomically: true, encoding: .utf8)
  let text = try String(contentsOf: url, encoding: .utf8)
  print(text)
} catch {
  print("File operation failed")
}

Worked answer

An existing report is user data and could be destroyed or replaced. A unique temporary path isolates the exercise and cleanup keeps the practice artifact from becoming accidental permanent storage.

Keep practice files separate from user data

File access can fail because of permissions, missing directories or unavailable storage. The online compiler has its own temporary environment; its files are not files on your computer. A real application needs a suitable storage location and a deliberate recovery policy.

Check your decision

Why not write this practice file over an existing report?
Choose one answer. You can try again.

Answer and explanation

An existing report is user data and could be destroyed or replaced.

An existing report is user data and could be destroyed or replaced. A unique temporary path isolates the exercise and cleanup keeps the practice artifact from becoming accidental permanent storage.

Keep practice files separate from user data

An existing report is user data and could be destroyed or replaced. A unique temporary path isolates the exercise and cleanup keeps the practice artifact from becoming accidental permanent storage. File access can fail because of permissions, missing directories or unavailable storage.

Further reading: official Swift language guide.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Codable and JSON data →