io interleaving?

Bengt Kleberg eleberg@REDACTED
Mon Feb 24 14:39:33 CET 2003


greetings,

where should io:fwrite() place things in a file?

i have the following file

line r1
line r2
line r3

if i open the file [read, write], write ''line w1'' and read ''line
r2'' i have the contents:

line w1
line r2
line r3

however, if i open the file [read, write], read ''line r1'' and write
''line w1'' i have the contents:

line r1
line r2
line r3
line w1


i would have expected:

line r1
line w1
line r3

is this a bug, or, why is it like this?


bengt
-------------- next part --------------
-module(io_interleaveing).

-export([main/1]).


main( [_Prog|Args] ) ->
	File = file( Args ),
	R = lines( "r" ),
	W = lists:nth( 1, lines( "w" )),
	write_read( File, R, W ),
	read_write( File, R, W ),
	init:stop().

lines( Direction ) ->
	Line = lists:append( "line ", Direction ),
	[lists:append( Line, X) || X <- ["1\n", "2\n", "3\n"]].

fill_file( File, Contents ) ->
	{ok, Io} = file:open( File, [write] ),
	io:fwrite( Io, "~s", [Contents] ),
	file:close( Io ).

write_read( File, R, W ) ->
	fill_file( File, R ),
	write_read_io( file:open( File, [read, write] ), W, lists:nth( 2, R) ),
	contents( File, lists:append( [W, lists:nth( 2, R), lists:nth( 3, R)] ) ).

write_read_io( {ok, Io}, W, R ) ->
	io:fwrite( Io, "~s", [W] ),
	R = io:get_line( Io, '' ),
	file:close( Io ).

read_write(File, R, W) ->
	fill_file( File, R ),
	read_write_io( file:open( File, [read, write] ), lists:nth( 1, R), W ),
	contents( File, lists:append( [lists:nth( 1, R), W, lists:nth( 3, R)] ) ).

read_write_io( {ok, Io}, R, W ) ->
	R = io:get_line( Io, '' ),
	io:fwrite( Io, "~s", [W] ),
	file:close( Io ).


contents( File, Lines ) ->
	{ok, Bin} = file:read_file( File ),
	Bin = erlang:list_to_binary( Lines ).

file( [] ) ->
	"/tmp/afile";
file( [File|_T] ) ->
	File.


More information about the erlang-questions mailing list