Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and/or Write to a file

Tags:

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.

The following

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

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, working in Delphi XE.

like image 808
Eric G Avatar asked Oct 20 '11 02:10

Eric G


People also ask

How do you create a new file and write to a file in Java?

java File file = new File("JavaFile. java"); We then use the createNewFile() method of the File class to create new file to the specified path.


2 Answers

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);  
like image 126
RRUZ Avatar answered Sep 23 '22 21:09

RRUZ


Any solution that uses FileExists to choose how to open the file has a race condition. If the file's existence changes between the time you test it and the time you attempt to open the file, your program will fail. Delphi doesn't provide any way to solve that problem with its native file I/O routines.

If your Delphi version is new enough to offer it, you can use the TFile.Open with the fmOpenOrCreate open mode, which does exactly what you want; it returns a TFileStream.

Otherwise, you can use the Windows API function CreateFile to open your file instead. Set the dwCreationDisposition parameter to OPEN_ALWAYS, which tells it to create the file if it doesn't already exist.

like image 27
Rob Kennedy Avatar answered Sep 23 '22 21:09

Rob Kennedy