Erlang 的 write_file 函数用于将数据写入文件中。\n\n该函数的语法如下:\n\nerlang\nwrite_file(FileName, Data) -> ok | {error, Reason}\n\n\n其中,FileName 是文件的路径和名称,Data 是要写入文件的数据。\n\n如果写入文件成功,函数返回 ok;如果写入文件失败,函数返回 {error, Reason},其中 Reason 是写入失败的原因。\n\n示例:\n\nerlang\n-module(file_demo).\n-export([write_file/2]).\n\nwrite_file(FileName, Data) ->\n case file:open(FileName, [write]) of\n {ok, File} ->\n case io:fwrite(File, "~s", [Data]) of\n ok ->\n file:close(File),\n ok;\n _Error ->\n file:close(File),\n {error, "写入文件失败"}\n end;\n _Error ->\n {error, "打开文件失败"}\n end.\n\n\n在上述示例中,我们首先使用 file:open 函数打开要写入的文件,然后使用 io:fwrite 函数将数据写入文件中。如果写入成功,我们使用 file:close 函数关闭文件,并返回 ok;如果写入失败,我们同样使用 file:close 函数关闭文件,并返回 {error, "写入文件失败"}。\n\n使用示例:\n\nerlang\n1> c(file_demo).\n2> file_demo:write_file("test.txt", "Hello, world!").\nok\n\n\n在上述示例中,我们使用 write_file 函数将字符串 "Hello, world!" 写入了名为 test.txt 的文件中。写入成功后,函数返回 ok。

Erlang write_file 函数:文件写入详解及示例

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

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