Reading files
Reading files as text:
action! read Red-by-example MyCode4fun
>> a: read %mySecondFile.txt
== {First line;^/Second line;^/Third line.^/Fourth line;^/Fifth li
Now the word (variable) "a" has the entire content of the file:
>> print a
First line;
Second line;
Third line.
Fourth line;
Fifth line;
Sixth line.
Reading files as series where every line is an element:
Notice that, so far, the word "a" above is just text with newlines. If you want to read the file as a series! having each line as an element, you should use read/lines:
>> a: read/lines %mySecondFile.txt
== ["First line;" "Second line;" "Third line." "Fourth line;"...
>> print pick a 2
Second line;
Read refinements:
/part => Partial read a given number of units (source relative).
/seek => Read from a specific position (source relative).
/binary => Preserves contents exactly.
/lines => Convert to block of strings.
/info =>
/as => Read with the specified encoding, default is 'UTF-8.
function! load Red-by-example MyCode4fun
Reading files as a series where every word (separated by space) is an element:
In this case, you should use load instead of read:
>> a: load %mySecondFile.txt
== [First line Second line Third line.
Fourth line Fifth...
>> print pick a 2
line
Reading and writing binary files:
To read or write a binary file such as an image or a sound, you should use the /binary refinement. The following code loads a bitmap image to variable a and saves that image with another name:
>> a: read/binary %heart.bmp
== #{
424D660700000000000036000000280000001E00000014000000010...
>> write/binary %newheart.bmp a