How to stop Ruby by automatically adding carriage returns

I am having problems generating text files from a Windows computer to be read in 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

      

0A

is the ASCII code for the line feed, but when I open the resulting file in Notepad ++ I see that it added CR and LF at the end of the line.

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

+3


source to share


2 answers


Opening the file in binary mode causes Ruby to "suppress the EOL ↔ CRLF conversion on Windows" (see here ).

The problem is that Tempfiles automatically opens inw+

. I couldn't find a way to change this when creating the Tempfile.



The answer is to change it after creation with 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

      

+1


source


try setting the output delimiter $\

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 can use #write

that 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

      

+3


source







All Articles