I would like to get names of only *.txt files in given directory, sth like this:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char **argv)
{
char *dirFilename = "dir";
DIR *directory = NULL;
directory = opendir (dirFilename);
if(directory == NULL)
return -1;
struct dirent *ent;
while ((ent = readdir (directory)) != NULL)
{
if(ent->d_name.extension == "txt")
printf ("%s\n", ent->d_name);
}
if(closedir(directory) < 0)
return -1;
return 0;
}
How can I do this in pure unixs c?
@BartFriedrich has points out the
glob()
function, however he didn't give an example of it's use. Very briefly (and wholly untested) you might try something like thisglob()
is actually a fairly complicated function in detail, and for more general file matching requirements I probably wouldn't use it, but it does handle your problem effectively. For more information, check outman glob
on your linux machine or look at the man page online.You're almost there, you just need to check if the filename ends with
.txt
. One way to do that is to usestrcmp
,strcasecmp
, ormemcmp
:It's a good idea to verify that it's a regular file (and not a directory or other type of special file) by calling
stat(2)
on the full file path and checking thest_mode
field with theS_ISxxx
macros. Note that thed_type
member of theDIR
struct returned byreaddir
isn't always supported, so it's not a good idea to rely on it.Alternatively, instead of using
opendir
,readdir
, andclosedir
, you can use theglob(3)
function:Firstly, Unix has no notion of file extensions, so there's no
extension
member onstruct dirent
. Second, you can't compare strings with==
. You can use something likeThe
> 4
part ensures that the filename.txt
is not matched.(Obtain
bool
from<stdbool.h>
.)You could write a endswith function:
Just do a reverse-loop (start from the end) throught the suffix and check if each char is the same.
You can use the
glob()
function call for that. More info using your favourite search engine, Linux man pages, or here.Possibility: