创建和/或写入文件 [英] Create and/or Write to a file

查看:75
本文介绍了创建和/或写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这应该很容易,但是Google目前完全让我失望。我想打开一个文件,或者创建一个不存在的文件并写入文件。

I feel like this should be easy, but google is totally failing me at the moment. I want to open a file, or create it if it doesn't exist, and write to it.

以下

AssignFile(logFile, 'Test.txt');
Append(logFile);

当文件尚不存在时,在第二行抛出错误,我认为这是预期的。但是我真的没有找到如何a)测试文件是否存在,以及b)在需要时创建文件的方法。

throws an error on the second line when the file doesn't exist yet, which I assume is expected. But I'm really failing at finding out how to a) test if the file exists and b) create it when needed.

FYI,在Delphi XE中工作。

FYI, working in Delphi XE.

推荐答案

您可以使用 FileExists 函数,然后使用 追加 (如果存在)或 重写 (如果没有)。

You can use the FileExists function and then use Append if exist or Rewrite if not.

    AssignFile(logFile, 'Test.txt');

    if FileExists('test.txt') then
      Append(logFile)
    else
      Rewrite(logFile);

   //do your stuff

    CloseFile(logFile); 

这篇关于创建和/或写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆