Programming Concept

File Input/Output

Processing files — paths, error handling, buffering, and binary vs text files.

Chapter 9 (pp. 183–196) of Computer Science I.

Topics

SectionPageContent
Processing Files183Paths, error handling, buffered vs unbuffered, binary vs text.

Key Ideas

  • Buffered vs unbuffered I/O — performance vs immediacy tradeoff.
  • Binary vs text files — encoding matters when reading/writing.
  • File errors motivate error handling (open can fail).
  • Reading files relies on string tokenizing.
  • PHP extends file reading to URLs.

Examples

Read a file line by line

file ← open("data.txt", read)
if file = error:
  return error "cannot open"
while not endOfFile(file):
  line ← readLine(file)
  print line
close(file)

Always check the open result and close the handle when done.

In Java

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null)
        System.out.println(line);
}   // try-with-resources closes the reader automatically

Citations

[1] Computer Science I, Ch. 9, pp. 183–196.