Text Files · 17 / 17 Exercise Hard

Read a file of unknown encoding

Objective

Old text files are often in Latin-1 and modern ones in UTF-8. A byte such as 0xF1 is usually an error in UTF-8 and a valid letter in Latin-1; this lets you try one first and, if it fails, the other.

Instructions

  • The first line has the number n of files; then one name per line (they exist in the working folder).
  • Read each file in binary and decode it as utf-8; if it is not valid, as latin-1. Show name (encoding): text.
Input
2
a.txt
b.txt
Output
a.txt (utf-8): café
b.txt (latin-1): café

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise