CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: file question

  1. #1
    Join Date
    Jul 2001
    Posts
    430

    file question

    what is the better way to replace some lines with some new text in a text file?

    ********************** test.txt ***********
    Fill out the form below to post a message on the board. HTML is disabled for this board so you may not use it in your posts. Markup is enabled so you may use Markup on in your posts. Anonymous postings are not allowed, so you will need to register a Username before you can post.

    <- new code start ->

    Thanks. this is a test
    what is this?

    <- new test end - >

    Tip: You can enclose a block of source code within This will preserve the formatting and add syntax highlighting.
    ********************************************

    I want the following part

    <- new code start ->

    Thanks. this is a test
    what is this?

    <- new test end - >

    to be replaced by

    <- new line start ->

    what a nice day!
    I will be back soon.

    <- new line end - >





  2. #2
    Join Date
    Jan 2000
    Location
    Olen, Belgium
    Posts
    2,477

    Re: file question

    First read it in a string, then track the <- new code start -> and the <- new test end ->, and replace it with what you want. After that, rewrite the file

    dim strFile as string
    dim FFile as integer

    FFile = FreeFile
    Open "file.txt" for input as #FFile

    ' read the entire file
    strFile = input(FileLen("file.txt"),FFile)

    Close #FFile

    ' now do the replacing magic
    Dim iPosBeginTag as long
    Dim iPosEndTag as long

    Dim strSomeOtherText as string
    strSomeOtherText = "Whatever needs to com between the new stuff"

    iPosBeginTag = Instr(strLine,"<- new code start ->")
    iPosEndTag = Instr(strLine,"<- new test end ->") + len("<- new test end ->")

    strFile = Left(strFile, iPosBeginTag -1) & _
    "<- new line start ->" & _
    strSomeOtherText & _
    "<- new line end ->" & _
    mid(strLine,iPosEndTag)

    ' now write it back again
    FFile = FreeFile
    Open "file.txt" for output as #ffile
    print #Ffile, strFile
    Close #Ffile




    Tom Cannaerts
    [email protected]

    Programming today is a race between software engineers striving to build bigger and better idot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning -- Rich Cook
    Tom Cannaerts
    email: [email protected]
    www.tom.be (dutch site)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured