JD, we do that in the digest package via serialize()
to/from raw
. That is nice as you can store serialized objects in SQL and other places. I would actually store this as RData as well which is way quicker to load()
(no parsing!) and save()
.
Or, if it has to be RawToChar()
and ascii then use something like this (taken straight from help(digest)
where we compare serialization of the file COPYING:
# test 'length' parameter and file input
fname <- file.path(R.home(),"COPYING")
x <- readChar(fname, file.info(fname)$size) # read file
for (alg in c("sha1", "md5", "crc32")) {
# partial file
h1 <- digest(x , length=18000, algo=alg, serialize=FALSE)
h2 <- digest(fname, length=18000, algo=alg, serialize=FALSE, file=TRUE)
h3 <- digest( substr(x,1,18000) , algo=alg, serialize=FALSE)
stopifnot( identical(h1,h2), identical(h1,h3) )
# whole file
h1 <- digest(x , algo=alg, serialize=FALSE)
h2 <- digest(fname, algo=alg, serialize=FALSE, file=TRUE)
stopifnot( identical(h1,h2) )
}
so with that your example becomes this:
R> outCon <- file("/tmp/jd.txt", "w")
R> mychars <- rawToChar(serialize(1:10, NULL, ascii=T))
R> cat(mychars, file=outCon); close(outCon)
R> fname <- "/tmp/jd.txt"
R> readChar(fname, file.info(fname)$size)
[1] "A
2
133633
131840
13
10
1
2
3
4
5
6
7
8
9
10
"
R> unserialize(charToRaw(readChar(fname, file.info(fname)$size)))
[1] 1 2 3 4 5 6 7 8 9 10
R>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…