1 1 . 3
U S I N G T H E A P I
201
One of the nice features of the C++
BFile
object is that it will properly
dispose of any previous file references each time
SetTo()
is called, and it
automatically cleans up any resources used when it is destroyed. This feature
removes the possibility of leaking file descriptors when manipulating many
files.
Issuing a Query
The last part of our example shows how to issue a query for files that con-
tain a particular keyword. The setup for issuing the query has few surprises.
We construct the predicate for the query, which is a string that contains the
expression
Keyword = *<word>*
. The
<word>
portion of the query is a string
parameter to the function. The use of the asterisks surrounding the query
make the expression a substring match.
void
do_query(BVolume *vol, char *word)
{
char
buff[512];
BQuery
query;
BEntry
match_entry;
BPath
path;
sprintf(buff, "%s = *%s*", INDEX_NAME, word);
query.SetPredicate(buff);
query.SetVolume(vol);
query.Fetch();
while(query.GetNextEntry(&match_entry) == B_NO_ERROR) {
match_entry.GetPath(&path);
printf("%s\n", path.Path());
}
}
The last step to set up the query is to specify what volume to issue the
query on using
SetPredicate()
. To start the query we call
Fetch()
. Of course,
a real program would check for errors from
Fetch()
.
The last phase of the query is to iterate over the results by calling
Get-
NextEntry()
. This is similar to how we iterated over a directory in the
gen-
erate keywords()
function above. Calling
GetNextEntry()
instead of
GetNex-
tRef()
allows us to get at the path of the file that matches the query. For our
purposes here, the path is all we are interested in. If the files needed to be
opened and read, then calling
GetNextRef()
might be more appropriate.
Practical File System Design:The Be File System
, Dominic Giampaolo
page 201