Link to home
Start Free TrialLog in
Avatar of a6106a
a6106a

asked on

How to strip off last character from text file

I have a text file that includes a page-break or page-feed character at the end.
Show me the code that will strip off the last char (or # of chars) from the end of the file and write it back out again using the same filename.
??
Avatar of wsh2
wsh2

<----- Code Begin ----->

   Dim strBuffer As String
   Dim strFileName As String
   Dim intFreeFile As Integer
   Dim intNumberOfCharacters
   
   intNumberOfCharacters = 2
   strFileName = "c:\MyPath\MyFile.txt"
   intFreeFile = FreeFile
   
   Open strFileName For Binary Access Read As intFreeFile
   strBuffer = Space$(LOF(intFreeFile))
   Get intFreeFile, , strBuffer
   Close intFreeFile
   
   Kill strFileName
   
   Open strFileName For Binary Access Write As intFreeFile
   strBuffer = Left(strBuffer, Len(strBuffer) - intNumberOfCharacters)
   Put intFreeFile, , strBuffer
   Close intFreeFile

<----- Code End ----->
Try this sub.
Call it by passing the FULL path for the file concerned and the number of chars you wish to remove from the end of it.

Sub Resize_File(strFile As String, iRemoveChar As Integer)

    'This proc reads an ascii file,
    'removes iRemoveChar characters from the end of it and rewrites it
    'with the original filename
   
    Dim strText As String
    Dim iFileNum As Integer
    Dim lNewSize As Long
   
   
    iFileNum = FreeFile
    'Open the file
    Open strFile For Binary As #iFileNum
    'Get number of chars to read (keep)
    lNewSize = FileLen(strFile) - iRemoveChar
    'Get the chars to keep
    strText = String(lNewSize, " ")
    Get #iFileNum, , strText
    'Close the file
    Close #iFileNum
    'Nuke the old file
    Kill strFile
   
    'Now put it back in
    'Create the file
    Open strFile For Binary As #iFileNum
   
    Put #iFileNum, , strText
   
    'Close the file
    Close #iFileNum
   
   
   
End Sub

nothing wrong with this code at all but what if the file is extremely large?  perhaps implement a constant chunk size to grab, check to see that the remaining size of the file is larger than the chunk size...when you find that it is not...thats when you would do the last step of subtracting off the needed length of characters.
my comment was in reference to wsh2's post initially but it applies to both...and wsh2's response came FIRST and was CORRECT <ahem>
I must be missing something.
I'm only new here but is there a reason why someone would an answer as a comment and not as an answer?
Also, for the record, wsh2's comment was posted somewhere between me seeing no comments and posting the answer.
I copy nobody.
welcome to EE spikedog...i'm not trying to give you a hard time...it is customary at this site to post comments for two reasons:

1)  The questioner can accept a comment as an answer at any time

2)  When you post an answer to a question rather than a comment, you remove it from the more active section down to the "Answered questions waiting to be graded" section.  Most experts do not look through that section, only the "Questions awaiting answers" section.  By posting comments you supply the questioner with sound advice and a good solution (as both you and wsh2 did in this case) as well as leave it open to comments from other experts who might have a better solution or who might make some valid suggestions.

You can always retract your answer to a comment with no harm done to allow it to be reopened for further input.
SpikeDog changed the proposed answer to a comment
Open file for APPEND and add one backspace character. :-)
Avatar of a6106a

ASKER

wsh:
I can increase the number of points some if you can adjust this a little.

These files that have the extra char at the end all reside in the same directory.
Can you add to your program so that the code goes through the directory and picks out the files with "bill" at the beginning of the filename and then gets rid of the extra char on those only.?
example:
   bill23456.txt
   bill 3288.txt
   bill 8876.txt
got about 20 more points left I think.

thanks a million...
Spikedog:
First of all welcome to EE.. <smile>.

Unless the answer is totally obvious, the custom here is to hit comment rather than answer. In hitting answer, you lock a question down which often times preclude others from commenting.. and/or allow the questioner to refine the text of his question.. possibly reducing the benefit of both experts and questioner in fully participating in the thread. As such, it is a courtesy thing to comment rather than answer. As to the points of the question.. the questioner will ultimately decide as to whom deserves them by selecting the comment OR answer which they feel is best. All in all, this sytem works very well.. and in 99% of the cases is very just to one and all.

As you spend some more time here.. you are going to find that Azra is one of the good guyz here.. and you will quickly learn extremely capable. The comment he made about chunking through the file is a very good one. With very large files.. copying files the way you and I propose.. has a tendency to lock the machine up.. giving the user an unseemly application interface look and feel. Chunking through a file eliminates this.. and additionally affords the opportunity of displaying a progress bar or other eye candy to keep the user visually occupied. To be honest, I tend to agree with you here the "text file" the questioner is alluding to here, is a small one.. but of that we cannot be sure until the questioner leaves further comment.

Spikedog.. we all look forward to working with you here and we are certainly happy that you decided to take some of your time to join the community effort. If you like, there is an option button on your screen to change your answer to a comment.. the decision is yours to do what YOU think is right.. <smile>.
Wow, you gotta love lag.
I already unlocked the question fellars.
Hey, it's 2:21am my time and I only came here to ask a question but I used to teach VB and old habits die hard.

Thanks for the intro ... maybe you should impress upon the owners of this very unique site to make the comment/answer issue part of the briefing. I'm just trying to get enough points to ask some tough questions.

Hope you get sort out your bills a6106a
this may be a good time to use the filesystemobject object


Dim filesys, files, f As Object
    Dim folderObj As Object
    Dim intFreeFile As Integer
    Dim strBuffer, strFileName As String

    Set filesys = CreateObject("Scripting.FileSystemObject")
    Set folderObj = filesys.Getfolder("C:\mybillpath\")
    Set files = folderObj.files
    For Each f In files
        If Left(f.Name, 4) = "bill" Then
            'do the stuff wsh2 said to do
    Next
Azra:
Thank YOU for the nice fill... <smile>. Get this I lost my glasses.. <sheesh>.. _... _.... and this braille keyboard is killing me !!! <LOL>.

SpikeDog:
Bad news.. Expert points can NOT be spent for anything but T-Shirts (and other prizes if you cahin yourself to the EE desk long enough.. LOL and a <sigh>. The only way to get Available points is to fill in the questionaires (if / when they appear), refer another screenanme in, rapidly amass them by signing on everyday (a whole 5 points everday you visit.. don't spend them all in one place).. or speciously buy them for 10cents apiece. As such, you want to marshal your points accordingly.

With that being said.. you are going to find that you still can ask a question and get help. More points certainly will garner your question added attenttion, but fewer points often will get you an answer as well.. <smile>. If you are low on points.. mention that in your question.. you will find that many of the experts are quite understanding.
Avatar of a6106a

ASKER

wsh:
I can't believe the conversation this has stirred up.
I still need to have this thing flip through all of the files in the directory and selectively do it's magic on all that end with .bil.
Then we got it.
same approach I mentioned except change this line:

If Left(f.Name, 4) = "bill"

to

If Right(f.Name, 3) = "bil"
Avatar of a6106a

ASKER

wsh:
I can't believe the conversation this has stirred up.
I still need to have this thing flip through all of the files in the directory and selectively do it's magic on all that end with .bil.
Then we got it.
Fellars, it's been a gas.
Now, I'm going to bed.
It's now 4:12am and my wife is wondering what on earth could be so interesting to keep me up so late.
The real answer is my Win2K development server keeps crashing whenever I use ADO.
Go Bill!

a6106a I hope you have your answers, azra and wsh I'll see you around.

Hi see if this can help you out

Sub RemoveChar(ZFilename As String, OldChar As String, NewChar)
 Dim StrBuffer As String
  Dim Filenum As Integer
  Filenum = FreeFile

  Open ZFilename For Input As #Filenum
  Open "C:\Test2.txt" For Append As 2#
   Do While Not EOF(Filenum)
   Input #Filenum, StrBuffer
   StrBuffer = Replace(StrBuffer, OldChar, NewChar)
   Print #2, StrBuffer
   DoEvents
   Loop
      Close #Filenum
      Close #2
     
End Sub

Private Sub Command1_Click()
RemoveShit "C:\Test.txt", "#", ""

End Sub
a6106a:
Conversation happens.. <smile>

Anyhow.. Azra has provided you with a very workable file find solution. Set a project reference (VB Menu -> Project -> References) to the "Microsoft Scripting Runtime" and then copy and paste his code into your program.. <smile>
ASKER CERTIFIED SOLUTION
Avatar of wsh2
wsh2

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ark
Hello!
Wsh2 and Azra - your code is great (as usual). BTW, if you already decided to use FSO, why not continue with it?
Private Function xFileFix(fname As String, nChars As Integer)
  Dim FSO As New FileSystemObject
  Dim FSTR As Scripting.TextStream
  Dim ret As Long, sText As String
  If FSO.FileExists(fname) Then
     Set FSTR = FSO.OpenTextFile(fname)
     sText = FSTR.Read(FileLen(fname) - nChars)
     FSTR.Close
     Set FSTR = FSO.OpenTextFile(fname, ForWriting)
     FSTR.Write sText
     FSTR.Close
     Set FSTR = Nothing
   Else
     ret = MsgBox("File Not Found", vbCritical)
   End If
   Set FSO = Nothing
End Function
Cheers
i had considered that but since wsh2 had already provided sound code to handle the open/write of the file, i left it in there.  besides, now the questioner has the best of both worlds, he gets to see two methods of file handling.

<offthread>
good to have you back Ark  =)
Avatar of a6106a

ASKER

This certainly has been an excersise in cooperation. Thanks a million.
a6106a