This should never work but it does. Why?

G

Guest

I've just fixed what should be a bug in a simple function to log a message to
a file. The thing is, the original code worked!

Protected Sub LogMessage(ByVal filename As String, ByVal message As
String)
Dim fileNum As Integer

fileNum = FreeFile()
FileSystem.FileOpen(FreeFile(), filename, OpenMode.Append)
FileSystem.PrintLine(fileNum, DateTime.Now.ToString + " - " + message)
FileSystem.FileClose(fileNum)
End Sub

I'm opening the file with one number and then using a different file number
to write the data! Surely the PrintLine and the FileClose should fail. But
the application works and logs mesages to the log file with no problems.

Can anyone explain?

--- Al.
 
B

Brian Cryer

TVR Fan said:
I've just fixed what should be a bug in a simple function to log a message to
a file. The thing is, the original code worked!

Protected Sub LogMessage(ByVal filename As String, ByVal message As
String)
Dim fileNum As Integer

fileNum = FreeFile()
FileSystem.FileOpen(FreeFile(), filename, OpenMode.Append)
FileSystem.PrintLine(fileNum, DateTime.Now.ToString + " - " + message)
FileSystem.FileClose(fileNum)
End Sub

I'm opening the file with one number and then using a different file number
to write the data! Surely the PrintLine and the FileClose should fail. But
the application works and logs mesages to the log file with no problems.

Can anyone explain?

--- Al.

The original worked because you are using the same file number.

FreeFile returns the next free file number that is not currently in use. The
thing to remember is that until you open a file using that file number, that
file number isn't in use. Therefore the second call to FreeFile returned the
same file number as the first.

However I do agree that it is better style to use:

fileNum = FreeFile()
FileSystem.FileOpen(fileNum ....

hope this helps,

Brian Cryer

www.cryer.co.uk/brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top