Use a random access file

From CodeCodex

Implementations[edit]

Erlang[edit]

random_access_file(Filename) ->
    {ok, IoDevice} = file:open(Filename, [read, write]),
    {ok, S1} = file:pread(IoDevice, bof, 10),            % bof : begin of file
    io:format("~p~n", [S1]),
    {ok, S2} = file:pread(IoDevice, {eof, -8}, 8),       % eof : end of file
    io:format("~p~n", [S2]),
    ok = file:pwrite(IoDevice, bof, string:to_upper(S1)),   % over write
    ok = file:pwrite(IoDevice, eof, "add line\n"),
    ok = file:close(IoDevice).

Java[edit]

    try {
        File f = new File("filename");
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
    
        // Read a character
        char ch = raf.readChar();
    
        // Seek to end of file
        raf.seek(f.length());
    
        // Append to the end
        raf.writeChars("aString");
        raf.close();
    } catch (IOException e) {
    }

Ruby[edit]

filename = "/work/temp.txt"
open(filename, "r+") do |fp|
  chr = File.read(fp,1)         # Read a character
  fp.seek(0, IO::SEEK_END)      # Seek to end of file
  fp.write("aString")           # Append to the end
  fp.seek(0)                    # Seek to start of file
  fp.write("test")              # Overwriting of the file
end