Skip to content

Text Crunch

You'll read a file in, change it and write a file out, which is the job most working code actually does, with the usual traps built in on purpose.

About

Programs that only print to the screen are toys. Real ones read files and write files, and they do it without eating the file when something goes wrong. The classic mistake is opening the output for writing using the input's name, which empties the input with no undo. This badge is a weekend of file handling with the traps built in: encodings, big files, and the file that isn't there.

At a glance

Per requirement
25 XP
Completion bonus
150 XP
Requirements
6
Takes
One weekend
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
Nothing special
Where
At home
Other people
On your own
Locked for now
Earn two more Common badges in Coding to open this one. Log in to see how far along you are.

Requirements

  1. 1
    Read a text file and print its line count, word count and character count. Then check your numbers with wc on the command line. If they differ, find out why, because it's usually a trailing newline or the way you split words. Take a screenshot of your output next to the wc output. Photo
  2. 2
    Write a program that copies a file with every line numbered. Open the input for reading and the output for writing, then loop line by line. Don't read the whole file into memory, because it should work on a 500 MB file the same as a 5 KB one. Take a screenshot of the first ten lines of the output file. Photo
  3. 3
    Handle a missing file without crashing. Run your program on a path that doesn't exist. Catch the error, print a one-line message a human would understand, and exit with a non-zero code. There should be no stack trace in sight. Take a screenshot of the friendly error. Photo
  4. 4
    Convert a CSV of at least 100 rows into JSON, and back again. Use your language's CSV and JSON libraries, because writing a CSV parser by hand is a trap once quoted commas show up. Round-trip the data and diff the result against the original. Take a screenshot of the diff showing no changes. Photo
  5. 5
    Open a file with a non-ASCII character in it and print it correctly. Put café or 日本 in a text file and read it with the encoding set to UTF-8 explicitly. Then try reading it as ASCII and see what comes out. Knowing what mojibake looks like saves you hours later. Take a screenshot of the correct output and the garbled one or the error. Photo
  6. 6
    Write a search-and-replace that takes the file, the old word and the new word as arguments. Write to a temporary file first, then rename it over the original. If the program dies halfway through, the original is untouched, and that pattern is how every serious editor saves. Film a short clip of it running on a file, with the before and after shown. Video