Reputation: 3469
I'm trying to simply read in an arbitrary file into R as a string. Then save it to another location.
data = readLines("/path_to_file/")
con = file("/new_path_to_file", "w")
writeLines(data, con)
close(con)
Every time the new file is corrupted (testing with this image: http://lacuadramagazine.com/wp-content/uploads/sangeh-monkey-forest-101.jpg).
I also tried readChar
but depending on the file, I get a UTF-8 error.
I want to be able to do this with any file - image, text, etc. This is part of a larger analysis (so file.copy doesn't cut it), but I can't even get the basic read/write mechanism down. Should be simple but getting stumped.
Upvotes: 0
Views: 311
Reputation: 206207
You are working with binary data here, not character data. Most likely you should be working with
setwd("~/../Desktop")
fn<-"sangeh-monkey-forest-101.jpg"
img<-readBin(fn, raw(), file.info(fn)$size)
writeBin(img, "out.jpg")
You can try converting to character with functions like rawToChar(img)
but since R strings can't contain null values (which your's does -- which(img==0)
) you can't really represent this as a properly encoded string.
Upvotes: 1