3

I am having problems constructing text files from a Windows machine to be read on a Linux environment.

def test

    my_file = Tempfile.new('filetemp.txt')

    my_file.print "This is on the first line"
    my_file.print "\x0A"
    my_file.print "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end

0Ais the ASCII code for line feed, yet when I open the resulting file in Notepad++, I see it has appended CR and LF on the end of the line.

How do I add only a Line Feed as the new line character?

kaybee99
  • 4,566
  • 2
  • 32
  • 42

2 Answers2

3

try setting the output separator $\ to \n.

def test
    $\ = "\n"
    my_file = Tempfile.new('filetemp.txt')

    my_file.print "This is on the first line"
    my_file.print "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end

or you should be able to use #write which will not add the output separator

def test
    my_file = Tempfile.new('filetemp.txt')

    my_file.write "This is on the first line"
    my_file.write "\x0A"
    my_file.write "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end
Doon
  • 19,719
  • 3
  • 40
  • 44
  • This still gives me the same issue - the problem seems to be the way in which "\n" is interpreted in a Windows environment. It's trying to be a bit too clever I think – kaybee99 May 13 '15 at 08:17
  • Are you Touching the file with a windows program after ruby? How are you getting the files to the Linux machine – Doon May 13 '15 at 10:39
  • Currently I'm not moving it anywhere, merely opening it on my Windows machine to check the line endings. I've managed to solve the problem however - I'll post it in an answer shortly – kaybee99 May 13 '15 at 11:10
2

Opening the file in binary mode causes Ruby to 'suppress EOL <-> CRLF conversion on Windows' (see here).

The problem is that Tempfiles are automatically opened in w+ mode. I couldn't find a way to change this on creation of the Tempfile.

The answer is to change it after creation using binmode:

def test


    my_file = Tempfile.new('filetemp.txt')
    my_file.binmode 

    my_file.print "This is on the first line"
    my_file.print "\x0A"    # \n now also works as a newline character
    my_file.print "This is on the second line"

    my_file.close

    FileUtils.mv(my_file.path, "C:/Users/me/Desktop/Folder/test.usr")

end
Community
  • 1
  • 1
kaybee99
  • 4,566
  • 2
  • 32
  • 42