Solved

How to strip off last character from text file

Posted on 2000-05-12
23
181 Views
Last Modified: 2010-05-02
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.
??
0
Comment
Question by:a6106a
  • 6
  • 5
  • 5
  • +4
23 Comments
 
LVL 14

Expert Comment

by:wsh2
ID: 2805425
<----- 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 ----->
0
 

Expert Comment

by:SpikeDog
ID: 2805506
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

0
 
LVL 28

Expert Comment

by:AzraSound
ID: 2805514
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.
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 2805518
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>
0
 

Expert Comment

by:SpikeDog
ID: 2805541
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.
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 2805576
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.
0
 

Expert Comment

by:SpikeDog
ID: 2805611
SpikeDog changed the proposed answer to a comment
0
 
LVL 15

Expert Comment

by:ameba
ID: 2805648
Open file for APPEND and add one backspace character. :-)
0
 

Author Comment

by:a6106a
ID: 2805689
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...
0
 
LVL 14

Expert Comment

by:wsh2
ID: 2805694
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>.
0
 

Expert Comment

by:SpikeDog
ID: 2805704
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
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 28

Expert Comment

by:AzraSound
ID: 2805790
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
0
 
LVL 14

Expert Comment

by:wsh2
ID: 2805826
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.
0
 

Author Comment

by:a6106a
ID: 2805889
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.
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 2805899
same approach I mentioned except change this line:

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

to

If Right(f.Name, 3) = "bil"
0
 

Author Comment

by:a6106a
ID: 2806014
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.
0
 

Expert Comment

by:SpikeDog
ID: 2806028
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.

0
 
LVL 4

Expert Comment

by:dreamvb
ID: 2806030
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
0
 
LVL 14

Expert Comment

by:wsh2
ID: 2806043
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>
0
 
LVL 14

Accepted Solution

by:
wsh2 earned 50 total points
ID: 2806139
Putting it all together..

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

Option Explicit

Private Sub Form_Load()
   
   Dim fsoMain As FileSystemObject
   Set fsoMain = CreateObject("Scripting.FileSystemObject")
   
   Dim fsoFolder As Folder
   Set fsoFolder = fsoMain.Getfolder("C:\tempwork\")
   
   Dim fsoFile As File
   For Each fsoFile In fsoFolder.files
      If UCase(Right(fsoFile.Name, 3)) = "BIL" _
      Then
         Call xFileFix(fsoFile.Path, 2)
      End If
   Next

End Sub

Private Sub xFileFix(ByVal strFilePath As String, ByVal intNumberOfCharacters2Clip As Integer)

   Dim strBuffer As String
   Dim intFreeFile As Integer
   intFreeFile = FreeFile
   
   Open strFilePath For Binary Access Read As intFreeFile
   strBuffer = Space$(LOF(intFreeFile))
   Get intFreeFile, , strBuffer
   Close intFreeFile
   
   Kill strFilePath
   
   Open strFilePath For Binary Access Write As intFreeFile
   strBuffer = Left(strBuffer, Len(strBuffer) - intNumberOfCharacters2Clip)
   Put intFreeFile, , strBuffer
   Close intFreeFile

End Sub

<----- Code End ----->

Pssssttt.. Don't forget to add a Project Reference to "Microsoft Scripting Runtime" for this to work.

0
 
LVL 27

Expert Comment

by:Ark
ID: 2806357
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
0
 
LVL 28

Expert Comment

by:AzraSound
ID: 2806415
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  =)
0
 

Author Comment

by:a6106a
ID: 2806728
This certainly has been an excersise in cooperation. Thanks a million.
a6106a
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

I’ve seen a number of people looking for examples of how to access web services from VB6.  I’ve been using a test harness I built in VB6 (using many resources I found online) that I use for small projects to work out how to communicate with web serv…
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now