Operating System - Linux
1748089 Members
4722 Online
108758 Solutions
New Discussion юеВ

Using C to check file patten on directory

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Using C to check file patten on directory

Hi Guys,

Just wondering is it possible to use C program to check whether files with certain pattern exists on a directory i.e. similar to using "ls pattern*"

regards
Henry
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Using C to check file patten on directory

Of course it is possible. How do you think the ls command ultimately does it? On the other hand, why reinvent the wheel when a:
File *f;
f = popen("ls xyz*","r");
would do the trick for you.

If you really want to do this then you use opendir() to open a directory, readdir() to read each directory entry, and then use the regcomp() and related functions for RE matching. Man regcomp for details.
If it ain't broke, I can fix that.
TwoProc
Honored Contributor

Re: Using C to check file patten on directory

Yes, possible in plenty, plenty of ways.

As many ways as you care to write a string matching algorithm.
We are the people our parents warned us about --Jimmy Buffett
James R. Ferguson
Acclaimed Contributor

Re: Using C to check file patten on directory

Hi Henry:

Pattern matching uses regular expressions. This is easily done with 'Perl', 'awk' and 'sed'. If you would be more specific it would be easy to help.

Regards!

...JRF...
Peter Nikitka
Honored Contributor

Re: Using C to check file patten on directory

Hi,

of course regcomp()/regexec() is the interface that can do all the regular expression stuff.

But:
- if you need just the matching of a string like "ls fixedstring*", a simple strstr() in your readdir()-loop will do it.
- the regcmp()-pattern are that you use in grep, vi, .... These are NOT identical with the pattern in (k|c|tc)sh for filename globbing.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
Henry Chua
Super Advisor

Re: Using C to check file patten on directory

Thanks for the tips.. if I am using popen(), is there anyway to redirect the error message so that it will not show up on the screen? =)
Peter Nikitka
Honored Contributor

Re: Using C to check file patten on directory

Hi,

act just as you would do in normal shell command, e.g.

f = popen("ls xyz* 2>/dev/null","r");

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"