File created by an external program

New to FreeBASIC? Post your questions here.
Carlos Herrera
Posts: 81
Joined: Nov 28, 2011 13:29
Location: Dictatorship

File created by an external program

Postby Carlos Herrera » Sep 20, 2019 8:06

File is created by external program and FreeBasic should wait until it is done.
I tried to introduce the necessary delay by checking the file length:

Code: Select all

Dim As String pathim
Dim As Integer length1, length2
' check if file is ready
Do
   length1 = Filelen(pathim)
   Sleep 100
   length2 = Filelen(pathim)
Loop Until length1 = length2

It works, however, the "sleeping" time is quite arbitrary, so maybe there is a better way?
grindstone
Posts: 721
Joined: May 05, 2015 5:35
Location: Germany

Re: File created by an external program

Postby grindstone » Sep 20, 2019 9:38

In Windows, you could try to open the file in exclusive mode. This will fail as long as the file is accessed by an other program:

Code: Select all

#Include "windows.bi"

Dim As HANDLE fh
Dim As String filename = "c:\testfile.txt"

Do
   fh = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL)
   If fh = INVALID_HANDLE_VALUE Then
      Print "File doesn't exist or is used by an other process"
   Else
      Print "File is free to be accessed"
   EndIf
   CloseHandle(fh)   
   Sleep 1000
   fh = 0
Loop Until InKey = " "

Try to create / access / delete the file while running this snippet.
MrSwiss
Posts: 3513
Joined: Jun 02, 2013 9:27
Location: Switzerland

Re: File created by an external program

Postby MrSwiss » Sep 20, 2019 12:02

There is another method, based more on messaging, which I've used in similar scenario.

This let's the external process deal with the file, as long as it takes. After finishing, it
simply creates a second, empty "message-file" that tells your program that the other
process is finished (your process can simply delete it, when it is done).

The other process is thereafter also informed, that you are "done" (file deleted).
A bit more complex but, it sort of works: both ways.

The check in your program is therefore simplified to a: FileExists("message-file") call.
Carlos Herrera
Posts: 81
Joined: Nov 28, 2011 13:29
Location: Dictatorship

Re: File created by an external program

Postby Carlos Herrera » Sep 20, 2019 17:01

@grindstone
This is very nice solution but I would rather avoid windows.bi, therefore
I will follow MrSwiss suggestion. In fact, I have contemplated something similar
with renaming of a "control" file.
Thank you both.
jj2007
Posts: 1466
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: File created by an external program

Postby jj2007 » Sep 21, 2019 2:26

Under Windows, there are much better options for interprocess communication, the simplest being a SendMessage().

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 2 guests