Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Error on while reading a blank text file?

Tags:

vb6

Using VB6

When I Reading the blank text file, showing error as Input Past end of file

Code.

Dim fso As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set fso = New FileSystemObject
Set TS = fso.OpenTextFile(txtSourceDatabaseFile & "\" & FileName, ForReading)
Final = TS.ReadAll
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

How to check whether the text file is empty or not? If empty no need to read the contents, else it should read contents.

Need VB6 code Help

like image 684
Gopal Avatar asked Dec 30 '22 13:12

Gopal


2 Answers

You're doing this:

Final = TS.ReadAll
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop

You should check for AtEndOfStream before calling ReadAll, something like:

If TS.AtEndOfStream Then
   Final = ""
Else
    Final = TS.ReadAll
    Do Until TS.AtEndOfStream
        TempS = TS.ReadLine
        Final = Final & TempS & vbCrLf
    Loop
End If

As a note though, you've got a logic error in there: ReadAll will read the entire file into memory. So subsequently calling ReadLine will return nothing. Either use ReadAll and parse the input with string manipulation, or call ReadLine exclusively. Don't use both.

like image 189
Chris J Avatar answered Jan 01 '23 02:01

Chris J


If you just want to read a text file into a string, Stefan answered that on one of your questions in July. The answer is still the same.

strFilename = "C:\1.txt"
iFile = FreeFile
Open strFilename For Input As #iFile
strTheData = StrConv(InputB(LOF(iFile), iFile), vbUnicode)
Close #iFile

If the file is empty (zero-length), strTheData will contain an empty string "". Alternatively you can check the length of a file with FileLen.

If FileLen("C:\1.txt") = 0 Then MsgBox "Empty file"

I recommend avoiding FileSystemObject: it's sometimes missing on user's machines - possibly because over zealous IT departments are scared of viruses? EDIT: in fact I've just heard from my colleagues about a user problem last week that turned out to be a FileSystemObject problem.

like image 38
MarkJ Avatar answered Jan 01 '23 02:01

MarkJ