Search and Delete Files Based on Mask

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ben

    Search and Delete Files Based on Mask

    Greetings,
    I am looking for a way to search for and delete files based on a pattern
    mask. For example, the search method would find all files matching a
    certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for a
    way to do this in either Visual Basic or C(++). Thanks!


  • Richard Heathfield

    #2
    Re: Search and Delete Files Based on Mask

    Ben wrote:
    [color=blue]
    > Greetings,
    > I am looking for a way to search for and delete files based on a
    > pattern
    > mask. For example, the search method would find all files matching a
    > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for
    > a
    > way to do this in either Visual Basic or C(++). Thanks![/color]

    Look up the Windows SDK functions FindFirstFile() , FindNextFile(),
    FindClose() and the WIN32_FIND_DATA type.

    Every now and again, Microsoft change the preferred way to parse files, so
    don't be surprised if your code is considered archaic in, say, a year or
    two. (Does anyone remember filling the DTA using INT 21 sub 4E and sub 4F?
    Surely it wasn't /that/ long ago, was it?)

    --
    Richard Heathfield : binary@eton.pow ernet.co.uk
    "Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
    C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
    K&R answers, C books, etc: http://users.powernet.co.uk/eton

    Comment

    • J French

      #3
      Re: Search and Delete Files Based on Mask

      On Sat, 21 Feb 2004 09:15:10 +0000, Richard Heathfield
      <invalid@addres s.co.uk.invalid > wrote:
      [color=blue]
      >Ben wrote:
      >[color=green]
      >> Greetings,
      >> I am looking for a way to search for and delete files based on a
      >> pattern
      >> mask. For example, the search method would find all files matching a
      >> certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for
      >> a
      >> way to do this in either Visual Basic or C(++). Thanks![/color]
      >
      >Look up the Windows SDK functions FindFirstFile() , FindNextFile(),
      >FindClose() and the WIN32_FIND_DATA type.
      >
      >Every now and again, Microsoft change the preferred way to parse files, so
      >don't be surprised if your code is considered archaic in, say, a year or
      >two. (Does anyone remember filling the DTA using INT 21 sub 4E and sub 4F?
      >Surely it wasn't /that/ long ago, was it?)[/color]

      Yup - and I also remember how essential it was to restore the DTA ...

      To the OP - it would be best to write your own 'matching' algorithm
      - that leading '*' in '*FILE29*.TXT' is very non-standard


      Comment

      • Derk Gwen

        #4
        Re: Search and Delete Files Based on Mask

        # > I am looking for a way to search for and delete files based on a
        # > pattern
        # > mask. For example, the search method would find all files matching a
        # > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for
        # > a
        # > way to do this in either Visual Basic or C(++). Thanks!

        The basic command is
        find $directory -name '*FILE29*.TXT' -print | xargs rm

        You can embed that into a C program with the system() function.
        char *directory = "...";
        char *pattern = "*FILE29*.T XT";
        char *format = "find '%s' -name '%s' -print | xargs rm";
        char command[strlen(director y)+strlen(patte rn)+strlen(form at)+1];
        sprintf(command ,format,directo ry,pattern);
        system(command) ;

        --
        Derk Gwen http://derkgwen.250free.com/html/index.html
        I have no respect for people with no shopping agenda.

        Comment

        • Mark McIntyre

          #5
          Re: Search and Delete Files Based on Mask

          On Sat, 21 Feb 2004 11:03:21 -0000, in comp.programmin g , Derk Gwen
          <derkgwen@HotPO P.com> wrote:
          [color=blue]
          ># > I am looking for a way to search for and delete files based on a
          ># > pattern
          ># > mask. For example, the search method would find all files matching a
          ># > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for
          ># > a
          ># > way to do this in either Visual Basic or C(++). Thanks!
          >
          >The basic command is
          > find $directory -name '*FILE29*.TXT' -print | xargs rm[/color]

          if you're going to post absurdly offtopic answers to offtopic questions, at
          least put some comment in to that effect, and point out that the question
          was offtopic in the first place.


          --
          Mark McIntyre
          CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
          CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>


          ----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
          http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
          ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---

          Comment

          • Joe \Nuke Me Xemu\ Foster

            #6
            Re: Search and Delete Files Based on Mask

            "Ben" <benj@bellsouth .nizzle> wrote in message <news:oszZb.113 88$ld7.10812@bi gnews3.bellsout h.net>...
            [color=blue]
            > I am looking for a way to search for and delete files based on a pattern
            > mask. For example, the search method would find all files matching a
            > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for a
            > way to do this in either Visual Basic or C(++). Thanks![/color]

            Here's how I might have done it in VB3...

            Sub TrashDisk (ByVal Start As String, ByVal Pattern As String, ByVal AttrMask As Integer)
            Dim DirCount As Long, Dirs() As String
            ReDim Dirs(0 To 3): DirCount = 1
            If Right$(Start, 1) = "\" Then
            Dirs(0) = Start
            ElseIf Start Like "[A-Za-z][:]" Then
            Dirs(0) = Start
            Else
            Dirs(0) = Start & "\"
            End If
            Dim DejaVu As Integer
            While DirCount
            DirCount = DirCount - 1
            Start = Dirs(DirCount)
            If DejaVu Then On Error Resume Next
            Dim File As String: File = Dir$(Start, AttrMask Or ATTR_DIRECTORY)
            If DejaVu Then On Error GoTo 0 Else DejaVu = True
            While Len(File)
            Dim SubDir As Integer
            If File = "." Or File = ".." Then
            SubDir = False
            Else
            On Error Resume Next
            SubDir = False
            SubDir = (GetAttr(Start & File) And ATTR_DIRECTORY) = ATTR_DIRECTORY
            On Error GoTo 0
            End If
            If SubDir Then
            If DirCount > UBound(Dirs) Then
            ReDim Preserve Dirs(0 To UBound(Dirs) * 2 Or 6)
            End If
            Dirs(DirCount) = Start & File & "\"
            DirCount = DirCount + 1
            ElseIf File Like Pattern Then
            ' On Error Resume Next
            Kill Start & File
            ' On Error GoTo 0
            End If
            File = Dir$
            Wend
            Wend
            End Sub

            --
            Joe Foster <mailto:jlfoste r%40znet.com> Got Thetans? <http://www.xenu.net/>
            WARNING: I cannot be held responsible for the above They're coming to
            because my cats have apparently learned to type. take me away, ha ha!


            Comment

            • Old Enough to Know Better

              #7
              Re: Search and Delete Files Based on Mask


              "Ben" <benj@bellsouth .nizzle> wrote in message
              news:oszZb.1138 8$ld7.10812@big news3.bellsouth .net...[color=blue]
              > Greetings,
              > I am looking for a way to search for and delete files based on a[/color]
              pattern[color=blue]
              > mask. For example, the search method would find all files matching a
              > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for[/color]
              a[color=blue]
              > way to do this in either Visual Basic or C(++). Thanks!
              >
              >[/color]
              You may also want to check out the FileSystemObjec t ( for VB add a project
              reference to the Microsoft scripting runtime)
              ..


              Comment

              • J French

                #8
                Re: Search and Delete Files Based on Mask

                On Sat, 21 Feb 2004 17:27:05 GMT, "Old Enough to Know Better"
                <SpamSucks@NoSp am.com> wrote:

                <snip>
                [color=blue]
                >You may also want to check out the FileSystemObjec t ( for VB add a project
                >reference to the Microsoft scripting runtime)[/color]

                Are you joking ?

                Comment

                • Rick Rothstein

                  #9
                  Re: Search and Delete Files Based on Mask

                  > I am looking for a way to search for and delete files based on a
                  pattern[color=blue]
                  > mask. For example, the search method would find all files matching a
                  > certain pattern containing wildcards (e.g. *FILE29*.TXT). I'm looking for[/color]
                  a[color=blue]
                  > way to do this in either Visual Basic or C(++). Thanks![/color]

                  You can always go back to the old DOS roots...

                  Path = "d:\temp\te st"
                  Mask = "*File29*.t xt"
                  Shell Environ("comspe c") & " /c del " & _
                  Path & "\" & Mask & " /q"

                  Note that the Path assignment is made without the trailing backslash. That
                  is because I am concatenating it in within the Shell statement directly.

                  Rick - MVP


                  Comment

                  • Old Enough to Know Better

                    #10
                    Re: Search and Delete Files Based on Mask


                    "J French" <erewhon@nowher e.com> wrote in message
                    news:4037a5cd.3 1401336@news.bt click.com...[color=blue]
                    > On Sat, 21 Feb 2004 17:27:05 GMT, "Old Enough to Know Better"
                    > <SpamSucks@NoSp am.com> wrote:
                    >
                    > <snip>
                    >[color=green]
                    > >You may also want to check out the FileSystemObjec t ( for VB add a[/color][/color]
                    project[color=blue][color=green]
                    > >reference to the Microsoft scripting runtime)[/color]
                    >
                    > Are you joking ?
                    >[/color]

                    I make no guarentees on this code because I didn't spend a lot of time
                    verifing it but here
                    is a MS knowledge base example of how to recursively search using wildcards
                    and FSO in VB6.
                    Maybe OP can spend a few minutes and paste it into a VB form and see if it's
                    what they want.
                    If you're not familiar with VB you can reference the KB article for complete
                    instructions.

                    HOW TO: Recursively Search Directories by Using FileSystemObjec t


                    Option Explicit

                    Dim fso As New FileSystemObjec t
                    Dim fld As Folder

                    Private Sub Command1_Click( )
                    Dim nDirs As Long, nFiles As Long, lSize As Currency
                    Dim sDir As String, sSrchString As String
                    sDir = InputBox("Type the directory that you want to search for", _
                    "FileSystemObje cts example", "C:\")
                    sSrchString = InputBox("Type the file name that you want to search for",
                    _
                    "FileSystemObje cts example", "vb.ini")
                    MousePointer = vbHourglass
                    Label1.Caption = "Searching " & vbCrLf & UCase(sDir) & "..."
                    lSize = FindFile(sDir, sSrchString, nDirs, nFiles)
                    MousePointer = vbDefault
                    MsgBox Str(nFiles) & " files found in" & Str(nDirs) & _
                    " directories", vbInformation
                    MsgBox "Total Size = " & lSize & " bytes"
                    End Sub

                    Private Function FindFile(ByVal sFol As String, sFile As String, _
                    nDirs As Long, nFiles As Long) As Currency
                    Dim tFld As Folder, tFil As File, FileName As String

                    On Error GoTo Catch
                    Set fld = fso.GetFolder(s Fol)
                    FileName = Dir(fso.BuildPa th(fld.Path, sFile), vbNormal Or _
                    vbHidden Or vbSystem Or vbReadOnly)
                    While Len(FileName) <> 0
                    FindFile = FindFile + FileLen(fso.Bui ldPath(fld.Path , _
                    FileName))
                    nFiles = nFiles + 1
                    List1.AddItem fso.BuildPath(f ld.Path, FileName) ' Load ListBox
                    FileName = Dir() ' Get next file
                    DoEvents
                    Wend
                    Label1 = "Searching " & vbCrLf & fld.Path & "..."
                    nDirs = nDirs + 1
                    If fld.SubFolders. Count > 0 Then
                    For Each tFld In fld.SubFolders
                    DoEvents
                    FindFile = FindFile + FindFile(tFld.P ath, sFile, nDirs, nFiles)
                    Next
                    End If
                    Exit Function
                    Catch: FileName = ""
                    Resume Next
                    End Function

                    Of course the sample code above doesn't actually delete the files it just
                    gives a listing, which you could then use for review before deleting. To
                    delete files use the FileSystemObjec t.DeleteFile method.

                    fso.DeleteFile ( filespec[, force] );
                    Arguments
                    filespec - Required. The name of the file to delete. The filespec can
                    contain wildcard characters in the last path component.
                    force - Optional. Boolean value that is true if files with the read-only
                    attribute set are to be deleted; false (default) if they are not.

                    Remarks
                    An error occurs if no matching files are found. The DeleteFile method stops
                    on the first error it encounters. No attempt is made to roll back or undo
                    any changes that were made before an error occurred.

                    Hope this helps


                    Comment

                    • Programmer Dude

                      #11
                      Re: Search and Delete Files Based on Mask

                      Mark McIntyre wrote:
                      [color=blue][color=green]
                      >> The basic command is
                      >> find $directory -name '*FILE29*.TXT' -print | xargs rm[/color]
                      >
                      > if you're going to post absurdly offtopic answers to offtopic
                      > questions, at least put some comment in to that effect, and
                      > point out that the question was offtopic in the first place.[/color]

                      Except--speaking as one regular of c.p--I didn't find it terribly
                      off-topic. comp.programmin g is pretty lenient about topic, because
                      we're a small enough group not to worry about traffic.

                      If it's genuinely computer programming related (and it was IMO)
                      then (again, IMO) it's fine.

                      Completely bogus answers are somewhat less fine, tho....

                      --
                      |_ CJSonnack <Chris@Sonnack. com> _____________| How's my programming? |
                      |_ http://www.Sonnack.com/ _______________ ____| Call: 1-800-DEV-NULL |
                      |______________ _______________ _______________ _|_____________ __________|

                      Comment

                      • Programmer Dude

                        #12
                        Re: Search and Delete Files Based on Mask

                        Richard Heathfield wrote:
                        [color=blue]
                        > (Does anyone remember filling the DTA using INT 21 sub 4E and sub
                        > 4F? Surely it wasn't /that/ long ago, was it?)[/color]

                        Heh! In "computer years" it's several generations ago! (-:

                        (In human years, probably close to a decade by now.)

                        --
                        |_ CJSonnack <Chris@Sonnack. com> _____________| How's my programming? |
                        |_ http://www.Sonnack.com/ _______________ ____| Call: 1-800-DEV-NULL |
                        |______________ _______________ _______________ _|_____________ __________|

                        Comment

                        Working...