I have a .txt file created in Notepad and it contains a 4 digit number (Job ID). I am recieving the dreaded "Bad File Mode" (#54) error when writing back the file.
I would like to OPEN it as R/W locked, read it, increment it by 1 and write it back. Am perfectly willing to create the .txt as non-binary if that is causing the issue. Any suggestions would be greatly appreciated.
:confused:
Bad File Mode: Writing To Locked Binary .txt File
-
-
-
Re: Write To A Locked Binary .txt File
Not sure I get your drift. Text files cannot be locked or set to read/write can they?
-
Re: Bad File Mode: Writing To Locked Binary .txt File
Hi Mumphis,
This is a follow up to your thread about flat file locking.
However, to answer your question here, you do not need to open the file in Binary mode.
A TXT file, whilst a Binary files (all files are binary when you think about it), is a special case where there should not be any binary data in it such as bitmaps etc.
You need to use the Random clause as outlined in the examples already given as if you open the file for 'OUTPUT' it is deleted first. For 'APPEND', the data is added to the end of the file so that doesn't help.
BINARY mode requires you to PUT or GET from specific byte positions so INPUT # and WRITE # won't work.
The easiest way is to use a RANDOM access file that allows you to read or write anywhere in the file based upon a record number rather than a byte position. This makes handling things much easier in the programming.
Regards
Rich
-
Re: Bad File Mode: Writing To Locked Binary .txt File
Personally for just 1 number I would use normal file input and output
[vba]Sub x()
Dim jinFP As String
jinFP = "JIN.txt"
WriteIDNumber jinFP, ReadIDNumber(jinFP) + 1
End Sub
Function ReadIDNumber(Filename) As Long
Dim intUnit As Integer
Dim lngID As Long
On Error GoTo ErrReadIDNumber
intUnit = FreeFile
Open Filename For Input As intUnit
Input #intUnit, lngID
ErrReadIDNumber:
Close intUnit
ReadIDNumber = lngID
End Function
Function WriteIDNumber(Filename, Number As Long)
Dim intUnit As Integer
Dim lngID As Long
On Error GoTo ErrWriteIDNumber
intUnit = FreeFile
Open Filename For Output As intUnit
Write #intUnit, Number
ErrWriteIDNumber:
Close intUnit
End Function[/vba] -
Re: Bad File Mode: Writing To Locked Binary .txt File
Hi Andy,
Yep, but this is also related to the thread about file locking.
As your code stands at the moment there is no file locking happening so you could get a double read.
The reason I suggested Random files rather than plain text files is that I'm not particularly sure what happens with the output clause - does it delete the file or truncate it ? And what happens if a read and a write are coincidental ?
With Random access files, I know that the open will always either create the file or open it.
Regards
Rich
-
Participate now!
Don’t have an account yet? Register yourself now and be a part of our community!