program to list all files of .txt extension

i am trying to list all files in the directory with .txt extension but in vain.please help me with the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <dirent.h>
#include <stdio.h>

int main(void)
{
    DIR *d;
    char *p;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            p=strtok(dir->d_name,".");
            p=strtok(NULL,".");
            if(p=="txt")
                printf("%s\n",dir->d_name);
        }
        closedir(d);
    }
    return(0);
}
Last edited on
on line 16: You compare to [c string] pointer. Use strcmp instead
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    DIR *d;
    char *p;
    int ret;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            p=strtok(dir->d_name,".");
            p=strtok(NULL,".");
            ret=strcmp(p,"txt");
            if(ret==0)
                printf("%s",dir->d_name);
        }
        closedir(d);
    }
    return(0);
}

now there's a run time error
Last edited on
now there's a run time error
Yes. What happens if dir->d_name does not contain "."?

Read this:

http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <dirent.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    DIR *d;
    char *p1,*p2;
    int ret;
    struct dirent *dir;
    d = opendir(".");
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            p1=strtok(dir->d_name,".");
            p2=strtok(NULL,".");
            if(p2!=NULL)
            {
                ret=strcmp(p2,"txt");
                if(ret==0)
                {
                    printf("%s\t",p1);
                }
            }

        }
        closedir(d);
    }
    return(0);
}

now my prob is solved..thnx
Topic archived. No new replies allowed.