Operating System - Linux
1826631 Members
3241 Online
109695 Solutions
New Discussion

Wildcard matching inside a program

 
SOLVED
Go to solution
Greg White
Frequent Advisor

Wildcard matching inside a program

Hi experts:

How do I do something like match "*.dat" from inside a C program?

Thanks,
Greg
I know how to do it in pascal.
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Wildcard matching inside a program

Sometimes it's hard to beat the simple approach (I assume that this is a directory listing):

FILE *p = NULL;
int cc = 0;

p = popen("ls *.dat","r");
if (p != NULL)
{
char s[512],*q = NULL;
q = fgets(s,sizeof(s),p);
while (q != NULL)
{
printf("%s\n",q);
q = fgets(s,sizeof(s),p);
}
cc = pclose(p);
}

If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Wildcard matching inside a program

Oh (and again making the assumption that this is related to directories then you also have the ability to do this directly in a C program without fork()ing a process as popen() would do. Open the directory with opendir(); read each entry using readdir(); use the fnmatch() function to do the expression matching, and close the directory with closedir().

Man opendir,readdir,closedir,fnmatch for details.

If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Wildcard matching inside a program

and as a Plan C (and this will apply to any pattern matching, not just filenames): Use regcmp() and regex(). Man regcmp and regex for details. These give you are the power of regular expression matching from within your C/C++ code.

No points for this please. I should have added this earlier.
If it ain't broke, I can fix that.
Dennis Handly
Acclaimed Contributor

Re: Wildcard matching inside a program

If you are doing something as simple as *.dat, you could look at the last 4 chars of the string for ".dat".
Otherwise, what Clay said.