Print vs write

Hello,
I have a file like below:

Hello
Hello

I want to write a program that reads this file and writes its contents along with line numbers to another file. I wrote the following program:

function readwrite()
    inn = open("input.txt","r")
    out = open("output.txt","w")
    counter = 0
    while !eof(inn)
        r = readline(inn)
        counter +=1
        println(out, counter,": ",r)
    end
    close(inn)
    close(out)
end

readwrite()

This program works fine, but does not work with the following command:

write(out, counter,": ",r)

Why?

Thank you.

When I put the variable inside " ", then it works fine:

        write(out, "$counter :", r)

Why?

write() for a numeric value will output the raw bytes, while it preserves the strings encoding.

3 Likes

Hi,
Sorry, I can’t understand it.

Check out the difference in this simple example:

write("test1.dat", 12)
write("test2.dat", "12")

read("test1.dat")
8-element Vector{UInt8}:
0x0c
0x00
0x00
0x00
0x00
0x00
0x00
0x00

read("test2.dat")
2-element Vector{UInt8}:
 0x31
 0x32

Decimal number 12 corresponds to hexadecimal letter C, and ASCII symbols 1 and 2 correspond to hexadecimals 31 and 32.

1 Like

(It might be clearer to call C (or c) a ‘digit’ in this context, not to be confused with the character 'C' with ASCII code 67 in decimal (0x43 hexadecimal) :slight_smile: )

2 Likes