Geek
Geek

Reputation: 708

Writing a string in newline

How can we append a string in a file i newline in erlang? Till now I have done this:

file:write_file("test5.txt", "\\nAbh~~nimanyu", [append]).
file:write_file("test5.txt", "\nAbh~nimanyu", [append]).

Yes, it is writing the string in file, but it is not writing the string in newline.

Output in file is like this:

Abh~nimanyu\nAbh~nimanyu

Upvotes: 1

Views: 1539

Answers (1)

nu-ex
nu-ex

Reputation: 681

You can use the newline format sequence ~n or \n for creating strings with newlines when using the format string functions.

The issue is file:write_file is expecting an unformatted string and will not convert ~n to newlines automatically.

io_lib:format and io_lib:fwrite will properly expand strings with format expressions like ~n, ~p, ~s, etc. and return the formatted string.

The following should give the expected result:

Formatted = io_lib:format("\nAbh~nimanyu", []),
file:write_file("test5.txt", Formatted, [append]).

Alternatively you could just use \n and skip the io_lib:format function:

file:write_file("test5.txt", "\nAbh\nimanyu", [append]).

Upvotes: 1

Related Questions