RacketI/OFile-HandlingStreams

Input/Output and File Handling in Racket | Schema Programming Part 9

2.935 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

Programs need to read data and write results. Racket treats all I/O sources (files, keyboard, network) as Ports.

Advertisement

Reading from Console

To interact with the user via the command line:

(display "What is your name? ")
(define name (read-line))
(printf "Hello, ~a!\n" name)
  • display: Prints text.
  • read-line: Reads a full line of text as a string.
  • read: Reads a complete S-expression (useful for parsing code).

Writing to Files

Racket makes it easy to write to files using with-output-to-file.

(with-output-to-file "output.txt"
  (lambda ()
    (printf "Line 1\n")
    (printf "Line 2\n"))
  #:exists 'replace) ; Overwrite if exists

Reading from Files

Similarly, use with-input-from-file.

(define content
  (with-input-from-file "output.txt"
    (lambda ()
      (port->string)))) ; Read entire file into string

(display content)

Walking Directory Trees

You can programmatically explore folders.

(for ([path (in-directory)])
  (displayln path))

Advertisement

Web I/O (Bonus)

Racket has a built-in web server!

#lang racket
(require web-server/servlet
         web-server/servlet-env)

(define (response-generator request)
  (response/xexpr
   '(html
     (body (h1 "Hello from Racket Web Server!")))))

(serve/servlet response-generator
               #:launch-browser? #f
               #:quit? #f)

Summary

Racket provides unified abstractions (ports) for all I/O, making it easy to read files, console input, or even web requests.

Next is the grand finale: Building a Complete Project.

Quick Quiz

What is the common abstraction for I/O sources in Racket?

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like