Question

file

Asked by: Sara_j_11

I have 4 text files in a directory. These are fixed length files and they have fields, which start at the same position. I mean the column names and their starting / ending position is the same , but the values will differ. All fields are either numeric (tight justified, left zero filles) or alphanumeric(left justified and right blank filled). I have given column names – just for clarity sake. In reality, these files do not display the  column names, but we can find that out since I know that the second column starts at positon 10.. it is sorted by id in every txt file.


Example of first txt file:

Id       name           number

01      tim              BY000

example for second txt file

id       name          number
   
13      donny         123GH


My aim is to write a function in VB 6.0 to take the contents of the 2nd , 3rd and 4th txt file and copy  it into  the  first txt file and then sort by id again… Kindly help.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-05-03 at 14:52:23ID21411581
Tags

vb

,

files

Topic

Visual Basic Programming

Participating Experts
4
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Justified Paragraph
    I've seen and heard about a <p align=justify> and tried it in vain, i got some info in a newsgroup that it was a feature of ns comm 4+ and msie 4+ and a future enhancement of html. I also heard that it was used with style sheets. So i would like to know the easy way (if...
  2. AIM of AOL
    does anyone know where i can find A system administrator's version of AIM ???with file tranfer and more!
  3. virtual reality software
    hi I am an architect who is wishing to transfer designs of houses onto computer and then allow users to 'walk' through the computer representation of the house with a virtual reality headset. What software would i need to do this with? regards Simon
  4. Justified Text
    How do you justify text? Thanks, -Caudax
  5. Problem with Aim
    Not really a big problem, but a very annoying one to say the least. I've downloaded the latest version of AOL instant messenger and installed it, but when I go to run it, it says there has been an error in the program and an error log is being created. I've looked all over ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: TheMCSEPosted on 2005-05-03 at 15:08:12ID: 13922117

Are all of the IDs globally unique (or the entire line)?  Do you want to copy the data from the 2nd, 3rd, and 4th files, or move it (if this process were to run again, there would be duplicates).  Based on the information you provided, I don't think that the other fields would be relevant to crafting this solution.  Are you opposed to using COM?  Realistically this could be created in VBS relatively easily, but the code should still work in VB.

 

by: JesterTooPosted on 2005-05-03 at 15:47:33ID: 13922339

Actually, you can do this is a batch file with only two commands if you'd prefer...

filename = combine.bat,  contents as follows:

   copy  file1.txt + file2.txt + file3.txt  tempfile.txt
   sort /r+1 tempfile.txt  /oNewFile.txt

This sill combine the 3 input files into a new one named "tempfile.txt" then sort it starting with column 1 creating a final output file named "NewFIle.txt"

You can add a third line to the batch file "del tempfile.txt" for cleanup if desired.

 

by: JesterTooPosted on 2005-05-03 at 15:50:38ID: 13922359

4 files... statement should have been:  copy file1.txt + file2.txt + file3.txt + file4.txt  tempfile.txt

Note, you can also build this batch file dynamically from within VB and shell.exec it for coding simplicity... I think you probably have to sort it that way... I'm not aware of any built-in filesort capabilities within VB or FSO.

-- Lynn

 

by: TheMCSEPosted on 2005-05-03 at 16:42:32ID: 13922578

The simplicity of batch is a beautiful thing :)  If you still want to do with VB(S), you could use something like this:


'begin
Option Explicit

Dim arrFile1, intCount, intCount2, objFSO, objFile1, strFile2, strFile3, strFile4, strLine, strTemp

Set objFSo = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFSO.OpenTextFile("file1.txt", 8)
strFile2 = objFSO.OpenTextFile("file2.txt").ReadAll
strFile3 = objFSO.OpenTextFile("file3.txt").ReadAll
strFile4 = objFSO.OpenTextFile("file4.txt").ReadAll

objFile1.Write vbCrLf & strFile2 & vbCrLf & strFile3 & vbCrLf & strFile4
objFile1.Close

arrFile1 = Split(objFSO.OpenTextFile("file1.txt").ReadAll, vbCrLf)

For intCount = (UBound(arrFile1) - 1) To 0 Step -1
    For intCount2 = 0 To intCount
        If UCase(arrFile1(intCount2)) > UCase(arrFile1(intCount2 + 1)) Then
            strTemp = arrFile1(intCount2 + 1)
            arrFile1(intCount2 + 1) = arrFile1(intCount2)
            arrFile1(intCount2) = strTemp
        End If
    Next
Next

Set objFile1 = objFSO.CreateTextFile("file1.txt", , True)
For Each strLine In arrFile1
    objFile1.WriteLine strLine
Next

MsgBox "Completed combining and sorting files.", vbInformation, "Execution completed"
'end

As JesterToo alluded to, there isn't a built-in sort functionality (none that I am aware of), but the good old-fashioned bubble sort should suffice.  This takes the datas from files 2, 3, and 4 (very original naming, no?) and writes it all to file 1; once this is complete, it reads all of file 1, sorts it, and rewrites it all to file 1.  Good luck!

 

by: JesterTooPosted on 2005-05-03 at 20:17:26ID: 13923640

Unless you know the record count to be sorted is very low (like less than 10,000 records) you don't want to use the bubble sort algorithm... this is the least efficient of all the sorting algorithms.  Choose a "shell, quick, or o-sort" algorithm instead.  Here's a quick comparison of the three:  I don't have discrete measurements for o-sort on these examples because it varies considerably based on how "sorted" the data already is.

# rows      Bubble            Shell              Quick
--------      --------           ------              ------
25                45 µSec        50 µSec           55 µSec
300           6000 µSec     1500 µSec       1000 µSec
5000           1.4 Sec        .035 Sec            .02 Sec
70000           10 Min         1.3 Sec              .5 Sec

You can see that the times for the Bubble sort rapidly increase with the number of rows being sorted.  There is another little known sort algorithm, the O-Sort (Oosterval Sort) which is only about 1.5 times as long as the Quick sort when the  data is fairly random.  However, if the data is already mostly in order then the sort time is about half as long as Quick sort.  Be advised that all these sorts are for "in memory" data... i.e. arrays.  It would require a masive undertaking to use these algorithms on data held in files if that data consisted large numbers of records and/or large record sizes.

 

by: fds_fatboyPosted on 2005-05-04 at 05:04:13ID: 13925732

with the caveats that JesterToo was refering to regarding massive files, you could  read the file into a 2d string array. In this PAQ, I have vb code that sorts a 2d array using the quicksort algorithm:

http://www.experts-exchange.com/AH_1945296.html

 

by: fds_fatboyPosted on 2005-05-04 at 05:05:53ID: 13925744

 

by: Sara_j_11Posted on 2005-05-04 at 07:45:51ID: 13927202

Can you please elaborate more on how to include the batch file logic in my program. Not familiar wit this process.
Kindly elaborate on how to do this.
Note, you can also build this batch file dynamically from within VB and shell.exec it for coding simplicity...
how do I acheive this:
copy  file1.txt + file2.txt + file3.txt  tempfile.txt
   sort /r+1 tempfile.txt  /oNewFile.txt
Sorry if it is a newbie question , but I am just a beginer..

 

by: JesterTooPosted on 2005-05-04 at 23:05:22ID: 13933323

Ok, here is a fairly complete VB6 program... lots of code (a bit over 200 lines) but it seems to work ok for me...

Attribute VB_Name = "ConcatSort"

'*****************************************************************************************
' ConcatSort.bas
'
'   Reads the command line for the names of the files to concatenate together and the
'   name of the file to create.  The last named file is the file to create.
'
' Sample usage:
'    ConcatSort /iFile1.txt /iFile2.txt /iFile3.txt /iFile4.txt /ttempfile.txt /oalltext.txt /c2 /bsorttest.bat
'
' Note:  Filenames with embedded spaces need to be enclosed in either single or double quotes.
'    ConcatSort "/iFile1 is here.txt" /iFile2.txt /iFile3.txt /iFile4.txt /ttempfile.txt /oalltext.txt /c2 '/bsorted data.bat'
'
' Switches can be specified on any order and any case...
'
'    /I     -    specifies Input file name... can have as many as can fit on command line.  Each file requires another switch.
'    /O    -    specifies Output filename (final sorted file)... should only be one of these.
'    /T    -    specifies temporary intermediate filename to contain the combined files prior to sorting
'    /B    -    specifies batch filename to generate
'    /C    -    specifies the column name in the combined file to begin the sorting operation
'    /D    -    specifies Ascending or Descending sort... values are A or D
'
'   Only the /I switch can legally exist multiple times, the /D switch defaults to Ascending, the /C switch defaults to 1.  The
'   batch file and the temporary file are both deleted when finished.
'*****************************************************************************************

Option Explicit

Dim sParam      As String
Dim sCmdLine    As String
Dim nCmdLineLen As Integer
Dim nPtr        As Integer
Dim oFSO        As Object

Sub Main()
Dim InpFile()   As String
Dim sSwitch     As String
Dim sCurSwitch  As String
Dim sSwitchVal  As String
Dim sTempFile   As String
Dim sOutFile    As String
Dim nSortColumn As Integer
Dim sSortDirect As String
Dim sBatFile    As String
Dim sString     As String
Dim n           As Integer
Dim nCount      As Integer
Dim oBatFile    As Object


   sCmdLine = Command()
   nCmdLineLen = Len(sCmdLine)
   nPtr = 1

   '-- find out how many input files there are...
   Do While nPtr < nCmdLineLen
      sParam = GetNextParam()
      If UCase$(Left$(sParam, 2)) = "/I" Then
         nCount = nCount + 1
      End If
   Loop

   If nCount > 0 Then
      ReDim InpFile(nCount - 1)
      nCount = 0
   Else
      Debug.Print "No input files specified... terminating now."
      End
   End If

   Set oFSO = CreateObject("Scripting.FileSystemObject")
   nPtr = 1

   Do While nPtr < nCmdLineLen
      sParam = GetNextParam()
      If LenB(sParam) > 0 Then
         sSwitch = UCase$(Left$(sParam, 2))
         sSwitchVal = Trim$(Mid$(sParam, 3))
         If Left$(sSwitchVal, 1) = "'" Or Left$(sSwitchVal, 1) = Chr$(34) Then
            sSwitchVal = Trim$(Mid$(sSwitchVal, 2, Len(sSwitchVal) - 1))
         End If
         Select Case sSwitch
            Case "/I"
               If LenB(sSwitchVal) > 0 Then
                  InpFile(nCount) = FixUp(sSwitchVal, True)
               End If
               nCount = nCount + 1
            Case "/T"
               If LenB(sSwitchVal) > 0 Then
                  If LenB(sTempFile) > 0 And UCase$(sOutFile) <> UCase$(sSwitchVal) Then
                     Debug.Print "Multiple temp filenames specified... last one will be used"
                  End If
                  sTempFile = FixUp(sSwitchVal)
               End If
            Case "/O"
               If LenB(sSwitchVal) > 0 Then
                  If LenB(sOutFile) > 0 And UCase$(sOutFile) <> UCase$(sSwitchVal) Then
                     Debug.Print "Multiple output filenames specified... last one will be used"
                  End If
                  sOutFile = FixUp(sSwitchVal)
               End If
            Case "/C"
               If LenB(sSwitchVal) > 0 Then
                  If nSortColumn <> 0 Then
                     nSortColumn = CInt(sSwitchVal)
                  ElseIf nSortColumn <> CInt(sSwitchVal) _
                     And nSortColumn <> 0 Then
                     Debug.Print "Multiple sort columns specified... last one will be used"
                     nSortColumn = CInt(sSwitchVal)
                  End If
               End If
            Case "/D"
               sSwitchVal = UCase$(Left$(sSwitchVal, 1))
               If LenB(sSwitchVal) > 0 Then
                  If LenB(sSortDirect) > 0 Then
                     sSortDirect = sSwitchVal
                  ElseIf sSwitchVal = "A" Or sSwitchVal = "D" Then
                     If sSortDirect <> sSwitchVal Then
                        Debug.Print "Sort direction specified multiple times... last one will be used"
                        sSortDirect = sSwitchVal
                     Else
                        Debug.Print "Invalid sort direction specified... defaulting to A"
                        sSortDirect = "A"
                     End If
                  End If
               End If
            Case "/B"
               If LenB(sSwitchVal) > 0 Then
                  If LenB(sBatFile) > 0 And UCase$(sBatFile) <> UCase$(sSwitchVal) Then
                     Debug.Print "Multiple BAT filenames specified... last one will be used"
                  End If
                  sBatFile = FixUp(sSwitchVal)
               End If
             Case Else
                  Debug.Print "Unknown command line parameter... ignoring."
         End Select
      End If
   Loop

   Set oBatFile = oFSO.CreateTextFile(sBatFile)

   oBatFile.WriteLine "@echo off"
   sString = "COPY /Y "
   For n = 0 To UBound(InpFile)
      If LenB(InpFile(n)) > 0 Then
         sString = sString & InpFile(n) & " + "
      End If
   Next
   sString = Left$(sString, Len(sString) - 2)

   oBatFile.WriteLine sString & sTempFile

   sString = "SORT "
   If nSortColumn <> 0 Then
      sString = sString & "/+" & CStr(nSortColumn) & " "
   End If
   If sSortDirect = "D" Then
      sString = sString & "/R" & " "
   End If
   sString = sString & sTempFile & " /O " & sOutFile
   oBatFile.WriteLine sString
   oBatFile.WriteLine "DEL " & sTempFile
   oBatFile.Close

   CreateObject("Wscript.Shell").Run sBatFile
'   Kill (sBatFile)

   Set oBatFile = Nothing
   Set oFSO = Nothing

End Sub


Function FixUp(sFileName, Optional bCheckExist)

   If Not IsMissing(bCheckExist) Then
      If bCheckExist Then
         If Not oFSO.FileExists(sFileName) Then
            Debug.Print "File " & sFileName & " doesn't exist... aborting!"
            End
         End If
      End If
   End If

   If InStr(sFileName, " ") Then
      sFileName = Chr(34) & sFileName & Chr(34)
   ElseIf InStr(sFileName, Chr(34)) Then
      sFileName = "'" & sFileName & "'"
   ElseIf InStr(sFileName, "'") Then
      sFileName = Chr(34) & sFileName & Chr(34)
   End If

   FixUp = sFileName
End Function


Function GetNextParam()
Dim sChar  As String
Dim bQuote As Boolean
Dim sParam As String

   Do While True
      If nPtr > nCmdLineLen Then
         GetNextParam = sParam
         Exit Function
      End If
      sChar = Mid$(sCmdLine, nPtr, 1)
      nPtr = nPtr + 1
      Select Case sChar
         Case "'", Chr$(34)
            If bQuote Then
               GetNextParam = sParam
               Exit Function
            Else
               bQuote = True
            End If
         Case " "
            If bQuote Then
               sParam = sParam & sChar
            Else
               GetNextParam = sParam
               Exit Function
            End If
         Case Else
            sParam = sParam & sChar
      End Select
   Loop

End Function


HTH,
Lynn

 

by: JesterTooPosted on 2005-05-04 at 23:10:03ID: 13933336

I just saw that I left a testing line in... uncomment the line that reads     '  Kill(sBatFile)
if you want it to delete the batch file.

Also, the first two lines of commentary in the "documentation block" at the top of the program aren't correct... That was written before I decided to use switches to identify the parameters.

-- Lynn

 

by: GPrentice00Posted on 2005-07-23 at 08:44:34ID: 14510378

sweet

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...