Difference between revisions of "Use a random access file"

From CodeCodex

 
(Erlang)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
==Implementations==
 
==Implementations==
===Java===
+
 
 +
===Erlang===
 
<pre>
 
<pre>
 +
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).
 +
</pre>
 +
 +
===Java===
 +
<pre class="java">
 
     try {
 
     try {
 
         File f = new File("filename");
 
         File f = new File("filename");
Line 19: Line 33:
 
</pre>
 
</pre>
  
 +
===Ruby===
 +
<pre class="ruby">
 +
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
 +
</pre>
 +
 +
[[Category:Erlang]]
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Ruby]]
 
[[Category:I/O]]
 
[[Category:I/O]]

Latest revision as of 07:34, 8 February 2011

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