测试以查看文件是否已存在

时间:2014-10-10 20:50:25

标签: livecode

我有一个iOS游戏,我正在尝试将设置(通常存储在数组中)保存到文件中。

目前,我已打开文件并在openStack处理程序中读取;我把文件写在关机处理程序中......

但是,在openStack处理程序中,我如何测试以查看文件是否实际已经创建...如果它不存在我想创建一个并写入一些默认设置

最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以检查文件是否已存在,如果该文件不存在,您可以将默认值放入文件中,然后创建该文件。 见下文

if there is not a file "mysettings.dat" 
then put myDefaultsettings into URL "binfile:mysettings.dat"

答案 1 :(得分:0)

通常,我只是打开并阅读该文件。接下来,我将内容放入变量中。如果内容恰好是空的,那么我使用默认值。这使得无需检查文件是否存在,更重要的是,它与软件的未来版本更兼容。

on readPrefs
  put specialFolderpath("documents") & "/prefs.dat" into myPath
  put url ("binfile:" & myPath) into myPrefs
  // here, the result may contain "can't open file"
  put line 1 of myPrefs into gHighscore
  if gHighScore is empty then put 0 into gHighscore
  put line 2 of myPrefs into gLicenseKey
  if gLicenseKey is empty then put "unregistered" into gLicenseKey
end readPrefs

您还可以检查文件并使用略有不同的脚本:

on readPrefs
  put specialFolderpath("documents") & "/prefs.dat" into myPath
  if there is a file myPath then
    put url ("binfile:" & myPath) into myPrefs
    put line 1 of myPrefs into gHighscore
    put line 2 of myPrefs into gLicenseKey
  end if
  if gHighScore is empty then put 0 into gHighscore
  if gLicenseKey is empty then put "unregistered" into gLicenseKey
end readPrefs

可能有更多变化,例如如果无法打开文件,您可以检查结果并设置默认值。

相关问题