Results 1 to 15 of 15

Thread: Add a string if not exist in text file

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Add a string if not exist in text file

    Hello Vbforums community
    I'm having a little trouble with textfile.
    This is the Sub I use:
    Code:
    Private Sub WriteFile(ByVal file_name As String, ByVal txt As String)
    Dim fnum As Integer
    fnum = FreeFile
        Open file_name For Output As fnum
        Print #fnum, txt;
        Close fnum
    End Sub
    Code:
    WriteFile app.Path & "\Types.txt", txt & Text2.Text
    My first worry is that each time I add a line, a new blank line is created at beginning of text file.

    However my main concern is:
    I want to add a new line if the same line does not exist.
    I don't know if that possible or not
    thank you all

  2. #2
    PowerPoster
    Join Date
    Nov 2017
    Posts
    3,116

    Re: Add a string if not exist in text file

    Your ultimate goal isn't exactly clear. Also, your wording makes it seem like you believe that if you do something like this:

    Code:
    WriteFile "C:\Test.txt", "Line 1"
    WriteFile "C:\Test.txt", "Line 2"
    That you will end up with a file that contains both Line 1 and Line 2. That isn't the case as currently coded, since you are opening the file in Output mode, which will overwrite the contents of any existing file that has the filename you are opening. So the end result of my simple example above is you will have a file that only contains Line 2

    If you do want to be able to take an existing file with existing content and simply add to the end of it, then you need to open the file in Append mode.

    The other part of your question about checking if the line already exists or not can be easily accomplished by opening the file in Input mode first, looping through all of the lines in the file and comparing each line to the "txt" value passed to the WriteFile function. Then you can take desired action whether or not that text is already present in the file. Sorry, I'm not going to be able to post any code.
    Last edited by OptionBase1; Jul 12th, 2018 at 08:09 AM.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    If you do want to be able to take an existing file with existing content and simply add to the end of it, then you need to open the file in Append mode.
    Thank you sir
    The idea is clear
    Now is it possible to avoid duplication of the same line?

  4. #4
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: Add a string if not exist in text file

    Quote Originally Posted by Mustaphi View Post
    Thank you sir
    The idea is clear
    Now is it possible to avoid duplication of the same line?
    So your real question has nothing to do with duplicate data but rather keeping it from overwriting the file each time.
    When you use open for output that tells the system to create the file if it does not exist or overwrite it if it does
    When you use open for append that tells the system to create the file if it does not exist or append to the end of the file if it does.

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    This is what I am doing now

    Code:
    Open app.Path & "\types.txt" For Append As FileNum
        Print #FileNum, vbNewLine, Text2.Text
        Close FileNum
    I need to avoid duplication of the same line.
    I mean before adding a line I want to loop all the lines and check if there a line = text2.
    I can only add a new line if there is no line = Text2.text

  6. #6
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: Add a string if not exist in text file

    You should not need to add the newline in there, unless of course you want a blank line to appear between every line.

    Print # ..... sends a newline at the end by default. It can be suppressed by adding a ; to the end of the line where needed.

    As for the duplicate part then you would first need to open the file for input, read each line in a loop, until you find a match or reach the end. Close the file then if you did not find a match append to the file

  7. #7

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    As for the duplicate part then you would first need to open the file for input, read each line in a loop, until you find a match or reach the end. Close the file then if you did not find a match append to the file
    thanks
    this is exactly what I'm looking for and need someone to guide to reach that

  8. #8
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: Add a string if not exist in text file

    It is very basic code, tons of examples out there, also examples in the online help..

    pseudo code

    Code:
    If file exists
        Open file for input
        Do Until EOF
             LineInput NextLine
             Compare text to the line read
             If match then 
                  Exists=True
                  Exit Do
             End IF
        Loop
      Close File
    End IF
    If Not Exists then do Append

  9. #9

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    DataMiser
    please a link

  10. #10
    PowerPoster
    Join Date
    Feb 2012
    Location
    West Virginia
    Posts
    14,205

    Re: Add a string if not exist in text file

    Quote Originally Posted by Mustaphi View Post
    DataMiser
    please a link
    Sorry, I'm not going to go search for a link for you. I showed you the concept, the code needed is simple and easy to write. Why don't you at least try to write it yourself. You will learn much more by doing than you will ever learn from copy paste.

    Maybe start with a quick search for LineInput VB6

  11. #11
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    Location
    To the moon and then left
    Posts
    4,418

    Re: Add a string if not exist in text file

    Or just read the whole content of the file into memory in one go, do an InStr-Check on that content if it contains the line you want to append, if true skip, of not enter your write-sub
    Last edited by Zvoni; Tomorrow at 31:69 PM.
    ----------------------------------------------------------------------------------------

    One System to rule them all, One Code to find them,
    One IDE to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    ---------------------------------------------------------------------------------
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    ---------------------------------------------------------------------------------
    Code is like a joke: If you have to explain it, it's bad

  12. #12

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    This is what I did so far but It seems that I'm unlucky thse days.
    Code:
    Private Function GetFileContents(ByVal sFilePath As String) As String
     Dim fnum As Integer
        fnum = FreeFile
        Open sFilePath For Input As fnum
        GetFileContents = Input(LOF(fnum), fnum)
        Close fnum
    End Function
    Code:
    Dim i As Long
     Dim sFileContents As String
     Dim arrStr() As String
     Dim sFilePath As String
        sFilePath = OrdoFolder & "\" & "types.Txt"
      sFileContents = GetFileContents(sFilePath)
    arrStr() = Split(sFileContents, vbCrLf)
        For i = 0 To UBound(arrStr())
      If arrStr(i) = Text2.Text Then
      Open App.Path & "\" & "types.Txt" For Append As #1
    Print #1, Text2.Text
    Close #1
    MsgBox "Les modifications ont été enregistrée avec succès. ", vbInformation
         Exit For
        Else
    Open App.Path & "\" & "types.Txt" For Append As #1
    Print #1, Text3.Text
    Close #1
    MsgBox "La nouvelle Lettre a été enregistrée avec succès. ", vbInformation
    Exit For
    End If
    Please someone teels me why ths statement is not recognized.
    Code:
     If arrStr(i) = Text2.Text Then
    I always get duplicated lines in the textfile.

  13. #13
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    9,145

    Re: Add a string if not exist in text file

    Well, could be many things....but first, do this:

    Code:
    if ucase(trim(arrStr(i))) = ucase(trim(Text2.text)) then
    If that doesn't work...attach your text file to your next post...

  14. #14
    PowerPoster SamOscarBrown's Avatar
    Join Date
    Aug 2012
    Location
    NC, USA
    Posts
    9,145

    Re: Add a string if not exist in text file

    Here....try this:

    Code:
    Option Explicit
    Private Function GetFileContents(ByVal sFilePath As String) As String
        Dim fnum As Integer
        fnum = FreeFile
        Open sFilePath For Input As fnum
        GetFileContents = Input(LOF(fnum), fnum)
        Close fnum
    End Function
    Private Sub cmdCheckFile_Click()
        Dim bFound As Boolean
        Dim i As Long
        Dim sFileContents As String
        Dim arrStr() As String
        Dim sFilePath As String
        sFilePath = App.Path & "\" & "types.Txt"
        sFileContents = GetFileContents(sFilePath)
        arrStr() = Split(sFileContents, vbCrLf)
        For i = 0 To UBound(arrStr())
            If ucase(trim(arrStr(i))) = ucase(trim(Text2.Text)) Then
                bFound = True
                MsgBox "Le texte est déjà dans le fichier.", vbInformation
                Exit For
            End If
        Next i
        If bFound = False Then
             Open App.Path & "\" & "types.Txt" For Append As #1
             Print #1, Text2.Text
             Close #1
             MsgBox "Les modifications ont été enregistrée avec succès. ", vbInformation
        End If
    End Sub
    Last edited by SamOscarBrown; Jul 15th, 2018 at 07:22 AM.

  15. #15

    Thread Starter
    Fanatic Member
    Join Date
    Jan 2016
    Posts
    753

    Re: Add a string if not exist in text file

    Million thanks sir
    solved

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