简体   繁体   English

R:使用cat()获取类似Unix的linebreak LF写入文件

[英]R: Getting Unix-like linebreak LF writing files with cat()

I try to write a character vector to a textfile under Windows 7 / R 3.2.2 x64, and I want unix LF - not Windows CRLF: 我尝试在Windows 7 / R 3.2.2 x64下将字符向量写入文本文件,我想要unix LF - 而不是Windows CRLF:

v <- c("a","b","c")
cat(nl,file="textfile.txt",sep="\n")

writes

> a[CRLF] 
> b[CRLF] 
> c[CRLF]

cat(paste(nl,sep="\n",collapse="\n"),file="t2.txt")

writes

> a[CRLF] 
> b[CRLF] 
> c

I have also tried write.table(eol="\\n") - unsuccessfully as it seems to use cat internally. 我也尝试过write.table(eol =“\\ n”) - 没有成功,因为它似乎在内部使用cat。

I have looked for other workarounds; 我找了其他的解决方法; I tried to find sth. 我试图找到某事。 in R\\src\\main\\scan.c, locating the relevant code in line 387ff. 在R \\ src \\ main \\ scan.c中,在387ff行中找到相关代码。

Anyone who knows how I can get UNIX-like LF in my output file? 有谁知道如何在输出文件中获得类似UNIX的LF?

Try to open a file connection in "binary" mode (instead of "text" mode) to prevent system-dependent encoding of the end-of-line: 尝试以“二进制”模式(而不是“文本”模式)打开文件连接,以防止对行尾的系统相关编码:

v <- c("a","b","c")
f <- file("textfile.txt", open="wb")
cat(v,file=f,sep="\n")
close(f)

based on the answer from @xb 基于@xb的答案

converter <- function(infile){
    print(infile)
    txt <- readLines(infile)
    f <- file(infile, open="wb")
    cat(txt, file=f, sep="\n")
    close(f)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM