?
Solved

Manipulatuing a text file:  Important (but not enough points)

Posted on 2003-03-16
16
Medium Priority
?
256 Views
Last Modified: 2008-02-01
Ok, here is my problem
I have a text file that contains some 10000 lines like this:
x1x1x1x1x1x1 "y1y1y1y1y1y1y1y1" "w1" "z1z1z1z1z1z1z1z1z1z1"
x2x2x2x2x2x2 "y2y2y2y2y2y2y2y2" "w2" "z2z2z2z2z2z2z2z2z2z2"
...

Now my problem is, when I want to edit for instance a line were the "yxyxyxyxyxyx" = "stofferken" I need to load the whole file and I need to check every line for it.  Then I have to write back the whole file with just 1 line changed.  This goes extremely slow so Id like to know if there are different ways to do this, just to "edit" a line and not to re-write the whole file or something.
0
Comment
Question by:Stofferken
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
  • 2
  • +3
16 Comments
 
LVL 11

Expert Comment

by:rdrunner
ID: 8150450
Its not possible ....

You need to import the whole file and write it back in order to change one line...  Textfiles are this way unfortunally...

If you have a binary file you could update the "field" and be done... but you dont know the location of yxyxyxyxyxyxyx and if the length of yxyxy <> len("stofferken") then its also not possible...

Are  you REALLY only editing ONE line or can the user edit another one later? If he can edit anotherone later then save the file only after all edits are complete and keep it in memory during that time
0
 
LVL 1

Expert Comment

by:Fischermaen
ID: 8150483
Hi Stofferken,

have you ever thought of using a database? Your problem looks to as an configuration file ... But if you have "some 10000 lines", i think a configuration file won't fit. A database is more useful for that. If you need the text file to configure some other processes, you could add an "export" -function to you software, which generates the text-file from the database. That works pretty much faster. I would go on like this:

Open the text file
Read in every line and put it in a database.
Let the user edit those "lines"
When the user has finished, export (automatically or on demand - depends on your software design) the text file.

I hope my ideas will help you

greetings

Andy
0
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 8150641
Hi Stofferken,

What I would do in a case like yours is the following:

1. I would first count how many times "yxyxyxyxyxyx" = "stofferken" appears in all of the textstream
2. I would then split all of the textstream exactly where "yxyxyxyxyxyx" = "stofferken" appears (as seperator)
3. I would then add chunk(0) & first changed text & chunk(1) & second changed text & chunk(2) and so on until all chunks and all changed text pieces are added
4. I would finally write all of the new textstream back to a file

This should even work with e good performance because we don't have to read every "mid" of the stream!

Hope this helps!

Best regards, Raisor
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 4

Expert Comment

by:barnesd1
ID: 8151520
Make a new reference in your project to the FileSystemObject (scrrun.dll).  With this you can read and write lLINES of data.  Use instr() function on a line at a time.  Suggest you write out each line to a second file so your example would work in 10000 reads and 10000 writes and finally delete the input file and rename the output file to the input filename.  Should be quite quick especially if files are on a local drive.

An example of the FSO in use follows:
Sub LogError(errX As ErrObject, _
             Optional strProcName As String)
             
   ' This procedure logs errors to a text file. It is used in
   ' this chapter to log synchronization errors.
   '
   ' Arguments:
   ' errX: A variable that refers to the VBA Err object.

   Dim fsoSysObj    As FileSystemObject
   Dim filFile      As File
   Dim txsStream    As TextStream
   Dim lngErrNum    As Long
   Dim strPath      As String
   Dim strErrText   As String
   
   Set fsoSysObj = New FileSystemObject
   
   ' Store error information.
   lngErrNum = errX.Number
   strErrText = errX.Description
   ' Clear error.
   errX.Clear
   ' Return Windows Temp folder.
   strPath = GetTempDir
   If Len(strPath) = 0 Then
      GoTo LogError_End
   End If
   
   On Error Resume Next
   ' See if file already exists.
   Set filFile = fsoSysObj.GetFile(strPath & APP_ERROR_LOG)
   ' If not, then create it.
   If Err <> 0 Then
      Set filFile = fsoSysObj.CreateTextFile(strPath & APP_ERROR_LOG)
   End If
   On Error GoTo 0

   ' Open file as text stream for reading.
   Set txsStream = filFile.OpenAsTextStream(ForAppending)
   ' Write error information and close.
   With txsStream
      .WriteLine lngErrNum
      .WriteLine strErrText
      If Len(strProcName) > 0 Then .WriteLine strProcName
      .WriteLine Now
      .WriteBlankLines 1
      .Close
   End With

LogError_End:
   Exit Sub
End Sub


0
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 8151912
@barnesd1

Hi,

I do not agree at all with your proposal ... the problem would be easily solved with the solution I've proposed earlier ... by now it should already be implemented! ;-)

Best regards, Raisor
0
 

Author Comment

by:Stofferken
ID: 8153313
My file is the same as a database, but Ive never learnt how to use a database.
Like with php(mysql) you can create a column: "names" were you put all the names in, next to it another column: "status" were you put the status in.

Well this is what my textfile contains:
for instance
 Column1   Column2 Column3   ...
"numberID" "john1" "member"  ...
"numberID" "john2" "crew member" ...
...

And I, "the admin" can switch the status of John458 to anything I want.
So I just need to change 1 value: the status of John458

So I read the whole file, I create some loops that check for " ", @ the 2th space I know I will get the name.
I check the name if it is "John458",
if it is:
- I copy the Mid(line,1,counter) & newstatus & vbcrlf to a text field
if it isnt:
- I copy the whole line to a text field

After that I just write the content of my text field to my text file.

@ Fischermaen: How can I use a database then?  (What is a database with vb?)
0
 
LVL 11

Expert Comment

by:supunr
ID: 8156758
what about if you use RichTextControl.

Add a richtext control to a form and hide that control.  then use code similar to below.

Private Sub FunctionName()
    Dim findAt As Long
    Dim SearchStr As String
    Dim ReplaceStr As String
    Dim FileName As String
   
    SearchStr = "yxyxyxyxyxyx"
    ReplaceStr = "stofferken"
    FileName = "C:\DataFile.txt"
   
    With RichTextBox1
        .LoadFile FileName, rtfText
        Do
            findAt = .find(SearchStr, 0)  ' always start from the begining
            If (findAt < 0) Then Exit Do
            .SelText = ReplaceText
        Loop
        .SaveFile FileName, rtfText
    End With
End Sub


Hope this works for you.

Good Luck!
0
 

Author Comment

by:Stofferken
ID: 8157269
@supunr thx Ill try it but,
Is it possible to change the line, I know for instance that I have to change line 452?

0
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 8157346
Hi Stofferken,

Is your text formated with fields or is it really a database engine you're looking for?

If, then: try working with ADO and .mdb files

... you never have to open the db with Access and it's very easy to learn and to handle.

An impression you'll get here:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odeopg/html/deovropeningaccessdatabasebyusingado.asp

The GetJetConnection procedure can be found in the OpenDatabase module of the DataAccess.mdb sample file, which is available in the ODETools\V9\Samples\OPG\Samples\CH14 subfolder on the Office 2000 Developer CD-ROM

Best regards, Raisor
0
 
LVL 1

Expert Comment

by:Fischermaen
ID: 8157473
@ stofferken

"Using a database" means to me e.g. using the data-control provided by microsoft, create a database (e.g. *.mdb) with a proper index. (You can use all those advantages liek databindung-controls a.s.o.) Then use that database generally for you program or just to read in the textfile, manipulate the data intended and then export the textfile. It all depends on how you intend your software to work. I always take databases whenever they fits, they make those purposes you told much easier to handle.

regards

Andy
0
 

Author Comment

by:Stofferken
ID: 8160659
I dont find that file to connect to a database (I dont have that cd)

@supunr:  What if there are more variables with the same value, and I only want to change the one on line 458?
0
 
LVL 11

Accepted Solution

by:
supunr earned 260 total points
ID: 8162912
Private Sub FunctionName()
   Dim findAt As Long
   Dim SearchStr As String
   Dim ReplaceStr As String
   Dim FileName As String
   Dim replaceLine As Long
   
   SearchStr = "yxyxyxyxyxyx"
   ReplaceStr = "stofferken"
   FileName = "C:\DataFile.txt"
   replaceLine = 458
   
   With RichTextBox1
       .LoadFile FileName, rtfText
       Do
           findAt = .Find(SearchStr, 0)  ' always start from the begining
           If (findAt < 0) Then Exit Do
           If (.GetLineFromChar(findAt) = replaceLine) Then
               .SelText = ReplaceText   ' replace text
           End If
       Loop
       .SaveFile FileName, rtfText
   End With
End Sub

0
 

Author Comment

by:Stofferken
ID: 8164640
thx alot,
when I have more points Ill open a question how databases work
0
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 8165108
Hi Stofferken,

You don't need "more" points ... give me a streight example of what you're up to do and I'll sent you the solution you need ... I don't have the time to write your application for you ... but with a working example I'll be able to sort out some "old" sequences from my "old-app-collection" ... I used to work a lot with database "files" in the last century ...

Best regards, Raisor
0
 

Author Comment

by:Stofferken
ID: 8166981
Private Sub chstatus(tmp)
   Dim findAt As Long
   Dim SearchStr As String
   Dim ReplaceStr As String
   Dim FileName As String
   
    stat = 0
    If List3.Text = "Normal" Then
        stat = 1
    End If
    If List3.Text = "Friend" Then
        stat = 2
    End If
   
        tmptxt = List4.Text
        If tmptxt = "none" Then
            tmptxt = ""
        End If
   SearchStr = List1.Text & " " & List2.Text & stat & " " & Chr(34) & tmptxt & Chr(34)
   
   If Combo1.Text <> "auto added" Then
        stat = 0
        If Combo1.Text = "Normal" Then
            stat = 1
        End If
        If Combo1.Text = "Friend" Then
            stat = 2
        End If
   
        ReplaceStr = List1.Text & " " & List2.Text & stat & " " & Chr(34) & tmptxt & Chr(34)

        FileName = App.Path & "\db.txt"

        With RichTextBox1
            .LoadFile FileName, rtfText

            Do
               findAt = .Find(SearchStr, 0)               If (findAt < 0) Then Exit Do
                    .SelText = ReplaceStr
            Loop
            .SaveFile FileName, rtfText
        End With
end if
        List1.Clear
        List2.Clear
        List3.Clear
        List4.Clear
        Combo1.Clear
        Combo1.Text = "auto added"
        Command2.Visible = False
        Command3.Visible = False
        Combo1.Visible = False
        ldmain (0)
    End If
End Sub

Well this is the function that I use now thx to supunr
when you look you see there are 4 columns:
each column is displayed in a listbox, when I select an item a combo box apears were I can set the status.
These 4 columns are in a text file like this:
specificusernumber "namesoftheperson" statusnumber "comments"
123 "john,stoffer,john and stoffer" 1 "this is an example of a row in my text file"

So it would be very usefull to be able to just put column1 up to 4 in a database.
But I dont find that file to add a component for using databases and I have no idea how to write and read from a database.
0
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 8168638
Hi Stofferken,

I was searching through my CD collection but the CD with a good example for you isn't here with me, sorry!

Still a good example you'll find at http://www.microsoft.com/mspress/books/sampchap/3162d.asp

You don't have to buy it, the sample chapter should give you enaugh information on how to use data objects in visual basic and how to handle records.

A MDB file can be created on the fly ... you never really have to open it with Access. If you don't have the possibility to use a SQL Server then it's probably the best solution!

Best regards, Raisor
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction In a recent article (http://www.experts-exchange.com/A_7811-A-Better-Concatenate-Function.html) for the Excel community, I showed an improved version of the Excel Concatenate() function.  While writing that article I realized that no o…
Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
Suggested Courses
Course of the Month10 days, 8 hours left to enroll

765 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