sdgaw erzswer
sdgaw erzswer

Reputation: 2382

Write to the beginning of file

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.

Upvotes: 6

Views: 2706

Answers (3)

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32351

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.

Upvotes: 5

Shaung
Shaung

Reputation: 508

There is no way to prepend data to a disk file.

There is no "insert mode" when writing to a file stream.

If your files are too big for your current specs, I suggest using database instead.

If the size of the dataset is not an issue, you can always read the content of existing file into memory, prepend the new data to it, and then overwrite the whole file. It does not actually save RAM though, as the whole dataset still needs to be read into memory every time.

Upvotes: 0

Reza Afzalan
Reza Afzalan

Reputation: 5746

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);

Upvotes: 8

Related Questions