473,218 Members | 1,472 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,218 software developers and data experts.

Search and Delete Files Based on Mask

Ben
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!
Jul 17 '05 #1
11 15595
Ben wrote:
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!


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 : bi****@eton.powernet.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
Jul 17 '05 #2
On Sat, 21 Feb 2004 09:15:10 +0000, Richard Heathfield
<in*****@address.co.uk.invalid> wrote:
Ben wrote:
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!


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?)


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
Jul 17 '05 #3
# > 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*.TXT";
char *format = "find '%s' -name '%s' -print | xargs rm";
char command[strlen(directory)+strlen(pattern)+strlen(format)+1];
sprintf(command,format,directory,pattern);
system(command);

--
Derk Gwen http://derkgwen.250free.com/html/index.html
I have no respect for people with no shopping agenda.
Jul 17 '05 #4
On Sat, 21 Feb 2004 11:03:21 -0000, in comp.programming , Derk Gwen
<de******@HotPOP.com> wrote:
# > 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


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.com/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 =---
Jul 17 '05 #5
"Ben" <be**@bellsouth.nizzle> wrote in message <news:os*******************@bignews3.bellsouth.net >...
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!


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:jlfoster%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!
Jul 17 '05 #6

"Ben" <be**@bellsouth.nizzle> wrote in message
news:os*******************@bignews3.bellsouth.net. ..
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!

You may also want to check out the FileSystemObject ( for VB add a project
reference to the Microsoft scripting runtime)
..
Jul 17 '05 #7
On Sat, 21 Feb 2004 17:27:05 GMT, "Old Enough to Know Better"
<Sp*******@NoSpam.com> wrote:

<snip>
You may also want to check out the FileSystemObject ( for VB add a project
reference to the Microsoft scripting runtime)


Are you joking ?

Jul 17 '05 #8
> 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!


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

Path = "d:\temp\test"
Mask = "*File29*.txt"
Shell Environ("comspec") & " /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
Jul 17 '05 #9

"J French" <er*****@nowhere.com> wrote in message
news:40***************@news.btclick.com...
On Sat, 21 Feb 2004 17:27:05 GMT, "Old Enough to Know Better"
<Sp*******@NoSpam.com> wrote:

<snip>
You may also want to check out the FileSystemObject ( for VB add a projectreference to the Microsoft scripting runtime)


Are you joking ?


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 FileSystemObject
http://support.microsoft.com/default...b;EN-US;185601

Option Explicit

Dim fso As New FileSystemObject
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", _
"FileSystemObjects example", "C:\")
sSrchString = InputBox("Type the file name that you want to search for",
_
"FileSystemObjects 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(sFol)
FileName = Dir(fso.BuildPath(fld.Path, sFile), vbNormal Or _
vbHidden Or vbSystem Or vbReadOnly)
While Len(FileName) <> 0
FindFile = FindFile + FileLen(fso.BuildPath(fld.Path, _
FileName))
nFiles = nFiles + 1
List1.AddItem fso.BuildPath(fld.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.Path, 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 FileSystemObject.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
Jul 17 '05 #10
Mark McIntyre wrote:
The basic command is
find $directory -name '*FILE29*.TXT' -print | xargs rm


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.


Except--speaking as one regular of c.p--I didn't find it terribly
off-topic. comp.programming 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 <Ch***@Sonnack.com> _____________| How's my programming? |
|_ http://www.Sonnack.com/ ___________________| Call: 1-800-DEV-NULL |
|_____________________________________________|___ ____________________|
Jul 17 '05 #11
Richard Heathfield wrote:
(Does anyone remember filling the DTA using INT 21 sub 4E and sub
4F? Surely it wasn't /that/ long ago, was it?)


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

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

--
|_ CJSonnack <Ch***@Sonnack.com> _____________| How's my programming? |
|_ http://www.Sonnack.com/ ___________________| Call: 1-800-DEV-NULL |
|_____________________________________________|___ ____________________|
Jul 17 '05 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
by: Georgy Pruss | last post by:
On Windows XP glob.glob doesn't work properly for files without extensions. E.g. C:\Temp contains 4 files: 2 with extensions, 2 without. C:\Temp>dir /b * aaaaa.aaa bbbbb.bbb ccccc ddddd ...
10
by: Case Nelson | last post by:
Hi there I've just been playing around with some python code and I've got a fun little optimization problem I could use some help with. Basically, the program needs to take in a random list of no...
11
by: Viviana Vc | last post by:
Hi all, I would like to delete from a directory all the files that match: bar*.* I know that I could do for instance: system("del bar*.*"), but this will bring up the command prompt window and...
16
by: Philip Boonzaaier | last post by:
I want to be able to generate SQL statements that will go through a list of data, effectively row by row, enquire on the database if this exists in the selected table- If it exists, then the colums...
4
by: Ben Fidge | last post by:
Hi What is the most efficient way to gather a list of files under a given folder recursively with the ability to specify exclusion file masks? For example, say I wanted to get a list of all...
1
by: Earl Teigrob | last post by:
Does someone have or know of an algorythm (method) that will delete all files under a give directory and its subdirectories based on a wildcard mask? I can use this for one directory for each...
3
by: richardkreidl | last post by:
I have the following module that I delete old files based on how old they are: Sub Main() Dim First_Date As String = Date.Today.AddDays(-7) Dim Archive_Files() As String =...
9
by: Lloyd Sheen | last post by:
For all those who don't think that a recursive search of files in folders is a good thing in the Microsoft.VisualBasic.FileIO.FileSystem namespace listen to this. I am reorg my mp3 collection. ...
0
Debadatta Mishra
by: Debadatta Mishra | last post by:
Introduction In this article I will provide you an approach to manipulate an image file. This article gives you an insight into some tricks in java so that you can conceal sensitive information...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.