Erlang的file:write_file函数默认使用的是二进制模式,而中文字符在二进制模式下可能会出现乱码。要正确地将包含中文字符的字符串写入文件中,需要使用file:write函数,并指定文件的编码格式。

下面是一个示例代码,演示如何将包含中文字符的字符串写入文件中:

-module(file_example).
-export([write_file/2]).

write_file(FilePath, Content) ->
    {ok, File} = file:open(FilePath, [write, {encoding, utf8}]),
    io:fwrite(File, "~s", [Content]),
    file:close(File).

在上面的示例中,我们使用utf8编码格式打开文件,并使用io:fwrite函数将字符串Content写入文件中。然后,使用file:close函数关闭文件。

使用示例:

1> c(file_example).
2> file_example:write_file("example.txt", "你好,世界!").
ok

以上代码将会创建一个名为example.txt的文件,并将字符串"你好,世界!"写入文件中。

erlang filewrite_file 含有中文输出失败

原文地址: https://www.cveoy.top/t/topic/i73o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录