473,417 Members | 1,343 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,417 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 15614
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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...

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.