PDA

Click to See Complete Forum and Search --> : Removing Blank Lines From Text Files


MethadoneBoy
Jul 6th, 2006, 04:24 AM
Hi guys,

I'm looking for an easier way to remove blank lines from .txt or .dat format files. The current method I'm using is working but is pretty inelegant -

Dim filedata() As String
Dim finaldata() As String

Public Function ReadFromFile(ByVal passedfilename As String)
On Error GoTo Err:

Dim arrlen As Integer: arrlen = 1
Dim count As Integer: count = 1
Dim incomingtext As String
Dim overalltext As String: overalltext = ""

'I start by opening the file. The example file I'm using is full of data like so-
'"Filedatablahblahblah"
'<blank line>
'"Filedatablahblahblah"
'<blank line>
'"Filedatablahblahblah"
'<blank line>
'etc.
Open passedfilename For Input As #1

'What I do here is basically read in every line of data in the file
'to a slot in one of two String arrays. The idea is that the first
'array will contain every line in the file, while the second array
'will ultimately contain only those lines that aren't blank
Do While Not EOF(1)

'Read a line from the file
Line Input #1, incomingtext
'Keep a record of every input
overalltext = overalltext & incomingtext
'Resize the array
ReDim Preserve filedata(count)
'Input the current line of text in the file to the array
filedata(count) = incomingtext
'Increment the pointer
count = count + 1

Loop


'Close the file
Close #1

'This is the second array. This should only contain non-blank lines
'once processing has finished
ReDim finaldata(UBound(filedata)) As String

Dim pointer As Integer: pointer = 1
Dim i As Integer: i = 0

'For every item in the first array
For i = 0 To UBound(filedata)

'If the item is blank, do not write to the second array
If filedata(i) = "" Then

filedata(i) = filedata(i)

Else

'If it isn't blank, resize the second array and input the item
ReDim Preserve finaldata(pointer)
finaldata(pointer - 1) = filedata(i)
pointer = pointer + 1

End If

Next


For i = 0 To UBound(finaldata)

MsgBox finaldata(i)

Next

Exit Function
Err:
MsgBox Err.Description
Exit Function
End Function

The above code is working fine, but I was wondering if there was an easier solution to removing blank lines from a file than the above. (I'm aware that the code I posted won't remove the lines from the file istelf - I intend to write the values of the second array into the file at a later point in the process).

If anyone could help, that would be appreciated.

Many thanks.

westconn1
Jul 6th, 2006, 05:43 AM
Dim f1 As Integer, strfile As String, cnt As Integer, mylen As Integer

f1 = FreeFile
Open "myfile.txt" For Input As f1
strfile = Input(LOF(f1), #f1)
Close f1

Do Until mylen = Len(strfile)
mylen = Len(strfile)
strfile = Replace(strfile, vbNewLine & vbNewLine, vbNewLine)
Loop
Open "new.txt" For Output As f1
Print #f1, strfile
Close f1


this looks a bit shorter

pete