Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia - write to the beginning of file

Tags:

file-io

julia

I've been trying to develop an algorithm which would at some point need to write results either to the beginning of a file, or to the end of it.

I'm trying to create a sorting algorithm which wouldn't use as much RAM as my files to be sorted are too big for my current specs. So for the cost of additional time, I would like to do this directly to file instead to RAM.

I know one can write files in Julia in this manner>

write(outfile,"A, B, C, D\n")

But I cannot seem to find how to write to the beginning of it.

like image 487
sdgaw erzswer Avatar asked Feb 11 '16 04:02

sdgaw erzswer


2 Answers

s=open("test.txt", "a+");
write(s,"B");
write(s,"C");
position(s) # => 2
seekstart(s);
position(s) # => 0
write(s,"A"); # be careful you are overwriting B!
position(s) # => 1
close(s);
s=open("test.txt", "r");
read(s,Char) # => 'A'
read(s,Char) # => 'C' # we lost 'B'!

So if you like to prepend! something to a file stream, the above solution do not work.

cdata=readall(s);
seekstart(s);
write(s,prependdata);
write(s,cdata);
like image 139
Reza Afzalan Avatar answered Sep 22 '22 00:09

Reza Afzalan


You can use two files instead of one, as when you implement a deque with two stacks:

  • To append data, append to the first file: it will store the tail of the data.

  • To prepend data, append to the second file: it will store the head of the data, but in reverse order.

  • When you need the data in a single file (probably just once, at the end of your algorithm), reverse the lines in the second file and concatenate the files.

like image 45
Vincent Zoonekynd Avatar answered Sep 19 '22 00:09

Vincent Zoonekynd