read_utf8: Read / write files encoded in UTF-8

View source: R/io.R

read_utf8R Documentation

Read / write files encoded in UTF-8

Description

Read or write files, assuming they are encoded in UTF-8. read_utf8() is roughly readLines(encoding = 'UTF-8') (a warning will be issued if non-UTF8 lines are found), and write_utf8() calls writeLines(enc2utf8(text), useBytes = TRUE).

Usage

read_utf8(con, error = FALSE, binary = FALSE)

write_utf8(text, con, ...)

append_utf8(text, con, sort = TRUE)

append_unique(text, con, sort = function(x) base::sort(unique(x)))

Arguments

con

A connection or a file path.

error

Whether to signal an error when non-UTF8 characters are detected (if FALSE, only a warning message is issued).

binary

Whether to read the file via a binary-mode connection. On Windows, readLines() on a text-mode connection (the default) treats a Ctrl+Z byte (⁠\x1a⁠) as end-of-file and silently truncates the file (e.g., self-contained HTML embedding the PNG signature ⁠\x89PNG\r\n\x1a\n⁠ in JavaScript). Set binary = TRUE to read the whole file regardless of Ctrl+Z bytes (this has a small overhead and is only necessary on Windows). This argument is only used when con is a file path.

text

A character vector (will be converted to UTF-8 via enc2utf8()).

...

Other arguments passed to writeLines() (except useBytes, which is TRUE in write_utf8()).

sort

Logical (FALSE means not to sort the content) or a function to sort the content; TRUE is equivalent to base::sort.

Details

The function append_utf8() appends UTF-8 content to a file or connection based on read_utf8() and write_utf8(), and optionally sort the content. The function append_unique() appends unique lines to a file or connection.

Value

read_utf8() returns a character vector of the file content; write_utf8() returns the con argument (invisibly).


xfun documentation built on July 9, 2026, 5:08 p.m.