1

Text file:

test1

test2

test3

test4

I want to write after "test2" - something. I tried first time to open the file and I read the position where is test2. After that I opened the text file in Append format but I don't know how to write on specific position.

I must to use next commands or others in Visual Basic:

  • for reading from a text file: Open Test_Filename For Input As #

  • for appending in a text file: Open Test_Filename For Append As #3

Any helps will be great.


Edit:

LineNum = 1
LineRead = 0
Test_Filename ="path/test.txt"

If Len(Dir$(Test_Filename)) = 0 Then
    MsgBox ("Cannot find the file")
End If

Open Test_Filename For Input As #3
Do While Not EOF(3)

    LineNum = 1
    strData1 = ""
    LineNext = 0

    For LineNum = 1 To 2

        If EOF(3) Then
            Exit For
        End If

        Line Input #3, strLine
        On Error GoTo 0 'reset error handling
        LineRead = LineRead + 1

        If Left(strLine, 4) = "test1" Then
                strData1 = "test1"
                LineNum = 1
        End If

        If (strData1 = "test1") And (Left(strLine, 2) = "test2") And (LineNum = 2) Then
                strData2 = strData2 & strLine + vbCrLf
                strData1 = ""
            Else
                strData2 = ""
        End If

    Next LineNum

Loop


Close #3

Open Test_Filename For Append As #3
    If (InStr(strData2, "test2") <> 0) Then
        Print #3, "Something"
        Else
        Print #3, "Error"

    End If
Close #3

In this code I want to write after "test2" and other condition "Something". I must to open the file twice time because when I open with "For Input" I can't to write in the file.

But in this situation I wrote on the end of the file "Something" and I must to write to a specific position, after "test2".

Dmitry
  • 6,716
  • 14
  • 37
  • 39
Pop Adrian
  • 11
  • 1
  • 5
  • You can't `Append` (i.e. write to the end of a file) information in the **middle** of a file. If it was possible, that would be called `Insert`, but it's not possible. You need to read the original file up to the point where you want to insert something while writing the contents to a new file as you do so, write the new information to the new file, then continue reading the old file and writing to the new file. – YowE3K Oct 31 '17 at 06:50
  • That is what I want, but when I translate in code doesn't work. To many alternate with Open - Close the file. First time: Open - Close the file for Input(read), Second time Open-Close the file for Append, and on the end Open-Close for Input(read). The problem what I meet: the line is not saved when the file is closed and when I re-opened for Append the word was put on the end of file. – Pop Adrian Oct 31 '17 at 07:47
  • "Append" means "add to the **end**" - it does **not** mean "insert somewhere in the middle". So, naturally, if you open the file in `Append` mode, it will add the data at the end. – YowE3K Oct 31 '17 at 18:27

1 Answers1

2

You could use:

Print #3, "This is my text to write to file."

Example here. If you need more information that this, please post the code you have so far.


Edit:

Try this:

Sub testWriteFile()

    Const Test_Filename = "c:\testfile.txt"
    Const findText = "test2"  ' what to find in file
    Const insertText = "!!!SOMETHING!!!"  ' what to put in line after [findText]

    Dim LinesRead As Integer, LinesInserted As Integer, outputText As String

    'If file doesn't exist then exit sub
    If Dir(Test_Filename) = "" Then
        MsgBox ("Cannot find the file")
        Exit Sub
    End If

    Open Test_Filename For Input As #3
    Do While Not EOF(3)

            'read line from input file
            Line Input #3, strLine
            LinesRead = LinesRead + 1

            'write line to output string
            outputText = outputText & strLine & vbCrLf

            'if line says
            If LCase(Left(strLine, Len(findText))) = LCase(findText) Then
                    outputText = outputText & insertText & vbCrLf  ' "insert" this line at the current position of output string
                    LinesInserted = LinesInserted + 1
            End If
    Loop

    'close output file
    Close #3


    'replace output file with output string
    Open Test_Filename For Output As #3
    Print #3, outputText
    Close #3

End Sub
ashleedawg
  • 20,365
  • 9
  • 72
  • 105
  • I would prefer to doesn't use "For Output" because there is no point in overwriting the all file. Sure if I don't find another variant I will use it your idea. Thanks – Pop Adrian Oct 31 '17 at 07:51
  • Is there a reason not to overwrite the whole file? There's no way to "insert" into a text file (and_ technically_, **the*whole file is re-written** by the Windows Filesystem **anytime it's edited** anyhow) – ashleedawg Oct 31 '17 at 07:57
  • I will use this function in a very large file and I prefer doesn't overwriting. – Pop Adrian Oct 31 '17 at 08:02
  • Besides the "pseudo-inserted" rows,the only change to the file would be the file's "created/modified/accessed dates", but if need be, those can also be duplicated on the new file. The only one who would know it's not the original file would be you... and me... (everyone else *shhhh, don't tell!*) – ashleedawg Oct 31 '17 at 08:04
  • @Pop-Adrian the size of the file is irrelevant since, just like any text editor, the entire file is deleted and re-written any time you edit a file. (Windows just makes us *think* it's the same file.) Speed wouldn't be affected regardless of the text file's size. If you find another way be sure to let the rest of us know! Also, you're pretty new here still, just so you know, if you get an "acceptable" answer that works for you, be sure to click it's "check mark". This gives the answer's poster 10 rep points, plus 2 rep points for you, for accepting an answer. Good luck! – ashleedawg Oct 31 '17 at 08:11
  • Edited files being recreated every time is the same reason [you don't want a Star Trek 'Transporter'](http://www.popularmechanics.com/culture/tv/a19793/the-trouble-with-the-star-trek-transporter/). :-) – ashleedawg Oct 31 '17 at 08:15
  • Strictly speaking, if the file was being appended to, a completely new file would not **necessarily** be created. All that would happen is extra block(s) (if necessary) would be allocated to the file and most of the existing data would not need to be rewritten. But given that the OP does not want to **append** data, that rather that they want to **insert** it in the middle, everything from the insertion point onwards **would** have to be rewritten. So you are definitely right in this situation. – YowE3K Oct 31 '17 at 18:35
  • @PopAdrian As an analogy, grab a sheet of paper (preferably one that is "lined", i.e. that has lines across it to keep the information written on it neatly spaced) and fill it with a list such as "test1", "test2", "test3", "test4". Make each list item completely fill a line. This represents your current file. Now, on that sheet of paper, insert "something" after the line saying "test2", while preserving line spacing (i.e. you can't write "something" very small so you can effectively redesign how your "text file" looks) and without changing anything else on that page. – YowE3K Oct 31 '17 at 18:39
  • @PopAdrian Or perhaps a quicker example - write down the numbers 1, 2, 3, 4, 5, e.g. `12345`. Now, insert the number 8 after the number 2 (to create `128345`), *while not moving the existing numbers from their respective positions* - i.e. keeping `4` as the 4th character rather than having it become the 5th character. – YowE3K Oct 31 '17 at 19:28
  • @YowE3K I understand what do you mention and I think I will apply this option. Thanks a lot for your help! – Pop Adrian Nov 01 '17 at 05:49
  • @ashleedawg I read the OP's comment as saying that they now understand what I was talking about and they will now apply the option provided **in this answer**. (At least that's what I hope that comment meant.) Which reminds me, it's about time I +1ed it. – YowE3K Nov 01 '17 at 07:22