0

我怎么能做这个

content[i].gsub("\n", "\\n")

将(类似)写入文件

str = "some text\n"

我正在编写一段代码来获取一个文件并从中构建一个字符串,如果这有帮助的话,可以将其插入回您使用的源代码中

如果我弄错了,我的错误实际上是在代码中的其他地方,这里是:

#!/bin/usr/ruby
#reads a file and parses into a single string declaration in language of choice
#another little snippet to make my job easier when writing lots of code
#programmed by michael ward
# h3xc0ntr0l@gmail.com | gists.github.com/michaelfward


# ***************************************
#              example scrips
#  with writefiles 
#   | writefiles [file with paths] [file to write*]
#   | makestring [file to write* (actually is read, but same as above)] [lang] 
#****************************************


def readFile(path)
  fd = File.open(path, "r")
  content = []
  fd.each_line {|x| content.push(x)}
  content = fixnewlines(content)
  str = content.join()
  str
end

def fixnewlines(content)
  content.each_index do |i|
    content[i].gsub("\n", "\\n")
  end
end

def usage
  puts "makestring [file to read] [language output]"
  exit
end

langs = {"rb"=>"str =", "js" => "var str =", "c"=> "char str[] ="}

usage unless ARGV.length == 2
lang = ARGV[1]
path = ARGV[0]
str = readFile(path)
if langs[lang] == nil
  if lang == "c++" || lang == "cpp" || lang == "c#"
    puts "#{lang[c]}#{str}"
  else
    puts "unrecognized language found. supported languages are"
    langs.each_key {|k| puts "   #{k}"}
    exit
  end
else
  puts "#{langs[lang]} #{str}"
end
4

2 回答 2

0

这取决于您使用的平台。Unix 使用\n作为行结束符,而 windows 使用\r\n. 看起来您正在替换所有换行符,尽管\\n它转义了我不希望在任何一个平台上工作的换行符。

于 2015-03-31T22:06:09.323 回答
0

Just remove fixnewlines and change readFile:

def readFile(path)
  File.read(path).gsub("\n", '\n')
end

Hope it helps. On Windows use \r\n instead of \n. There's no need to escape slashes inside single brackets.

于 2015-03-31T22:16:29.660 回答