473,520 Members | 3,258 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 15624
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
3063
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 C:\Temp>dir /b *.
10
3864
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 more than 10 letters, and find all possible mutations that match a word in my dictionary (80k words). However a wildcard letter '?' is also an...
11
454
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 as my app is a winmain app this wouldn't be nice. I could use DeleteFile, but you can not use wildcards in this one. How could I do this using...
16
16977
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 must be UPDATED, if not, they must be INSERTED. Logically then, I would like to SELECT * FROM <TABLE> WHERE ....<Values entered here>, and then...
4
7088
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 files under \Program Files and it's subdirectories that meet the following criteria:
1
383
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 file in Directory.GetFiles("pic1.*") file.Delete() but will need to use a recursive algorythm to get all its subdirectories
3
10050
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 = System.IO.Directory.GetFiles("C:\Turnover") Dim Filtered As New ArrayList For x As Integer = 0 To Archive_Files.Length - 1 If File.GetLastWriteTime(Archive_Files(x)) <...
9
1703
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. I have written my own catalog program and it has xml files to cache info from tags etc. To ensure that the process goes ok I went to delete all...
0
10717
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 inside an image, hide your complete image as text ,search for a particular image inside a directory, minimize the size of the image. However this is not...
0
7235
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7627
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7203
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5155
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3295
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3295
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
855
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
529
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.