truncate_file <- function(filename, n_bytes) {

  
  stopifnot(
    "file does not exist"= file.exists(filename),
    "not enough bytes in file"= file.size(filename) >= n_bytes
  )

  
  input.con <- file(filename, "rb")
  bindata <- readBin(input.con, integer(), n=n_bytes/4)
  close(input.con)

  
  tmp.filename <- tempfile()
  output.con <- file(tmp.filename, "wb")
  writeBin(bindata, output.con)
  close(output.con)

  
  stopifnot(
    "temp file is not expected size"= file.size(tmp.filename) == n_bytes
  )

  
  file.rename(tmp.filename, filename)

}